tla-ts 0.0.8 → 0.0.9-dev.331c500

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 (63) hide show
  1. package/README.md +23 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +48 -48
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +27 -9
  8. package/dist/index.d.ts +27 -9
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove.cjs +30 -30
  13. package/dist/prove.js +32 -32
  14. package/dist/run.cjs +28 -28
  15. package/dist/run.js +31 -31
  16. package/dist/tlapm.cjs +2 -2
  17. package/dist/tlapm.js +1 -1
  18. package/dist/transfer.cjs +30 -33
  19. package/dist/transfer.js +30 -33
  20. package/dist/worker.cjs +4 -4
  21. package/dist/worker.js +4 -4
  22. package/package.json +3 -1
  23. package/src/check.ts +77 -46
  24. package/src/cli/options.ts +2 -1
  25. package/src/cli/tlc.ts +26 -8
  26. package/src/cli/typescript.ts +26 -0
  27. package/src/codegen.ts +0 -5
  28. package/src/dependencies.ts +348 -24
  29. package/src/environment.ts +27 -11
  30. package/src/errors.ts +15 -0
  31. package/src/evaluate.ts +188 -712
  32. package/src/instances.ts +67 -6
  33. package/src/lexer.ts +140 -51
  34. package/src/liveness-checker.ts +6 -3
  35. package/src/liveness.ts +8 -18
  36. package/src/parallel-worker.ts +7 -5
  37. package/src/parallel.ts +18 -9
  38. package/src/prover/smt/solver/solver.ts +31 -27
  39. package/src/sany/generator.ts +9 -7
  40. package/src/sany/linter.ts +30 -21
  41. package/src/search.ts +48 -32
  42. package/src/spec-description.ts +1 -1
  43. package/src/successors.ts +6 -12
  44. package/src/symmetry.ts +32 -143
  45. package/src/tlc/fingerprint.ts +69 -116
  46. package/src/tlc/order.ts +27 -48
  47. package/src/tlc/replay.ts +1 -1
  48. package/src/typescript/actions.ts +494 -0
  49. package/src/typescript/collections.ts +615 -0
  50. package/src/typescript/compile.ts +70 -0
  51. package/src/typescript/context.ts +106 -0
  52. package/src/typescript/emit.ts +122 -0
  53. package/src/typescript/expressions.ts +508 -0
  54. package/src/typescript/formula.ts +160 -0
  55. package/src/typescript/functions.ts +295 -0
  56. package/src/typescript/model.ts +164 -0
  57. package/src/typescript/names.ts +116 -0
  58. package/src/typescript/program.ts +51 -0
  59. package/src/typescript/properties.ts +142 -0
  60. package/src/typescript/scope.ts +117 -0
  61. package/src/typescript/steps.ts +175 -0
  62. package/src/typescript/types.ts +178 -0
  63. package/src/values.ts +151 -85
package/src/evaluate.ts CHANGED
@@ -18,14 +18,18 @@ import { EXIT_STATUS, setExitCode } from "./exit-codes";
18
18
  import { generateEvaluator } from "./codegen";
19
19
  import { MESSAGE_CODE } from "./tlc/messages";
20
20
  import type { CheckerRuntime } from "./runtime";
21
- import { getReadVariables } from "./dependencies";
22
- import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
21
+ import {
22
+ isConstantLevel,
23
+ isImpureDefinition,
24
+ isNonconstant,
25
+ type DefinitionFacts,
26
+ } from "./dependencies";
27
+ import { contextualApplications } from "./instances";
23
28
  import { prettyPrint } from "./pretty-print";
24
- import { getReadLocals, isEnabled } from "./successors";
29
+ import { isEnabled } from "./successors";
25
30
  import {
26
31
  applyFunction,
27
32
  describeMissingArgument,
28
- combineHash,
29
33
  compareValues,
30
34
  createFunction,
31
35
  createNonIntegerKeyError,
@@ -44,13 +48,12 @@ import {
44
48
  getLazySubsets,
45
49
  getStreamedElements,
46
50
  getFunctionClass,
51
+ getNormalizedSetElements,
47
52
  getSequenceElements,
48
- getValueHash,
49
53
  isElementOf,
50
54
  isEnumerable,
51
55
  isFunctionValue,
52
56
  isOverriddenSet,
53
- isSameValue,
54
57
  markLambdaFunction,
55
58
  isReducibleSet,
56
59
  isSetValue,
@@ -116,6 +119,8 @@ export interface Thunk {
116
119
  // Whether the expression may build a set that streams until TLC caches it, so that the thunk
117
120
  // caches only a settled value.
118
121
  isStreamed: boolean;
122
+ // Whether the thunk dropped its scope after caching a value that holds in every state.
123
+ isReleased?: boolean;
119
124
  }
120
125
 
121
126
  type Binding = { kind: "Value"; value: Value } | Thunk | { kind: "Operator"; operator: Operator };
@@ -137,12 +142,18 @@ export interface Environment {
137
142
  instanceNames: Map<string, string>;
138
143
  variables: string[];
139
144
  variableIndex: Map<string, number>;
140
- definitionValues: Map<Definition, Value>;
141
- constantLevels: Map<Definition, boolean>;
145
+ facts: DefinitionFacts;
146
+ // The value of each constant definition TLC computed when it started, by the definition's id in
147
+ // facts. TLC evaluates a definition it failed to compute where the spec uses it.
148
+ startupValues: (Value | undefined)[];
142
149
  // The definitions an INSTANCE copies from a module that declares constants or variables. SANY
143
150
  // wraps the body of each in its substitutions.
144
151
  substitutedDefinitions: Set<Definition>;
152
+ // The compiled code of each expression, of each expression evaluated as a whole, which generated
153
+ // code can serve, and of each reference to a definition.
145
154
  evaluators: WeakMap<Expression, Evaluator>;
155
+ entryEvaluators: WeakMap<Expression, Evaluator>;
156
+ definitionEvaluators: WeakMap<Definition, Evaluator>;
146
157
  // The expressions being evaluated, outermost first, when the environment replays an error to
147
158
  // find where it occurred, as TLC's CallStackTool does.
148
159
  callStack?: CallStack;
@@ -434,57 +445,6 @@ export const expectBoolean = (value: Value, description: string) => {
434
445
  export const getDefinition = (name: string, environment: Environment) =>
435
446
  environment.definitions.get(environment.substitutions.get(name) ?? name);
436
447
 
437
- // TLC bounds the level of every action and temporal operator above constant, whatever its operands.
438
- const NONCONSTANT_KINDS = new Set<Expression["kind"]>([
439
- "Prime",
440
- "Unchanged",
441
- "Enabled",
442
- "BoxAction",
443
- "AngleAction",
444
- "Always",
445
- "Eventually",
446
- "WeakFairness",
447
- "StrongFairness",
448
- ]);
449
-
450
- const NONCONSTANT_OPERATORS = new Set(["~>", "-+->", "\\cdot"]);
451
-
452
- const isNonconstant = (expression: Expression, environment: Environment): boolean => {
453
- if (
454
- NONCONSTANT_KINDS.has(expression.kind) ||
455
- (expression.kind === "UnboundedQuantifier" && expression.isTemporal === true) ||
456
- (expression.kind === "Apply" && NONCONSTANT_OPERATORS.has(expression.operator))
457
- ) {
458
- return true;
459
- }
460
- const name =
461
- expression.kind === "Identifier"
462
- ? expression.name
463
- : expression.kind === "Apply"
464
- ? expression.operator
465
- : undefined;
466
- if (name !== undefined) {
467
- if (environment.variableIndex.has(name) || environment.builtins.get(name)?.isStateLevel)
468
- return true;
469
- const definition = getDefinition(name, environment);
470
- if (definition && !environment.constants.has(name) && !isConstantLevel(definition, environment))
471
- return true;
472
- }
473
- return getChildren(expression).some((child) => isNonconstant(child, environment));
474
- };
475
-
476
- export const isConstantLevel = (definition: Definition, environment: Environment): boolean => {
477
- const cached = environment.constantLevels.get(definition);
478
- if (cached !== undefined) return cached;
479
- environment.constantLevels.set(definition, true);
480
- const isConstant =
481
- !isNonconstant(definition.body, environment) &&
482
- (definition.kind === "Operator" ||
483
- !definition.bounds.some((bound) => isNonconstant(bound.set, environment)));
484
- environment.constantLevels.set(definition, isConstant);
485
- return isConstant;
486
- };
487
-
488
448
  const getBoundExplanation = (set: Value, text: string) => {
489
449
  const quantified = `universally (\\A) or existentially (\\E) quantify over ${text}, because this would require checking an\ninfinite number of cases.`;
490
450
  if (typeof set === "object" && set.kind === "SequenceSet") {
@@ -519,7 +479,7 @@ const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion
519
479
  const getEnumeratedElements = (set: Value, expression: Expression, version: TlcVersion) => {
520
480
  checkEnumerable(set, expression, version);
521
481
  if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
522
- return getLazySubsets(set) ?? toFiniteSet(set).elements;
482
+ return getLazySubsets(set) ?? getNormalizedSetElements(set);
523
483
  };
524
484
 
525
485
  // The elements Tool.contexts binds to the bound of a quantifier or a set map. TLC 1.7.4 streams a
@@ -686,14 +646,10 @@ interface LazyFunctionTemplate {
686
646
  body: string;
687
647
  }
688
648
 
689
- const lazyFunctionTemplates = new WeakMap<Expression, LazyFunctionTemplate>();
690
-
691
649
  const getLazyFunctionTemplate = (bounds: Bound[], body: Expression) => {
692
- const cached = lazyFunctionTemplates.get(body);
693
- if (cached) return cached;
694
650
  const range = body.location.range;
695
651
  if (!range) return undefined;
696
- const template = {
652
+ return {
697
653
  parameters: bounds.flatMap((bound, index) =>
698
654
  index > 0 && bounds[index - 1].set === bound.set
699
655
  ? []
@@ -709,12 +665,13 @@ const getLazyFunctionTemplate = (bounds: Bound[], body: Expression) => {
709
665
  ),
710
666
  body: formatRange(range),
711
667
  };
712
- lazyFunctionTemplates.set(body, template);
713
- return template;
714
668
  };
715
669
 
716
- const getLazyFunctionSource = (bounds: Bound[], body: Expression, domain: Value) => {
717
- const template = getLazyFunctionTemplate(bounds, body);
670
+ const getLazyFunctionSource = (
671
+ template: LazyFunctionTemplate | undefined,
672
+ bounds: Bound[],
673
+ domain: Value,
674
+ ) => {
718
675
  if (!template) return undefined;
719
676
  const domains =
720
677
  bounds.length > 1 && typeof domain === "object" && domain.kind === "ProductSet"
@@ -729,49 +686,28 @@ const getLazyFunctionSource = (bounds: Bound[], body: Expression, domain: Value)
729
686
  };
730
687
  };
731
688
 
689
+ // TLC's FcnLambdaValue evaluates its body at each application.
732
690
  const createLazyFunction = (
733
691
  domain: Value,
734
692
  compute: (argument: Value, self: LazyFunctionValue) => Value,
735
693
  source: LazyFunctionSource | undefined,
736
694
  ) => {
737
- const memo = new Map<number, Value[]>();
738
695
  const self: LazyFunctionValue = {
739
696
  kind: "LazyFunction",
740
697
  domain,
741
698
  source,
742
- apply: (argument) => {
743
- const hash = getValueHash(argument);
744
- const bucket = memo.get(hash);
745
- if (bucket !== undefined) {
746
- for (let index = 0; index < bucket.length; index += 2) {
747
- if (isSameValue(bucket[index], argument)) return bucket[index + 1];
748
- }
749
- }
750
- const value = compute(argument, self);
751
- const current = memo.get(hash);
752
- if (current === undefined) memo.set(hash, [argument, value]);
753
- else current.push(argument, value);
754
- return value;
755
- },
699
+ apply: (argument) => compute(argument, self),
756
700
  };
757
701
  return self;
758
702
  };
759
703
 
760
- const definitionSources = new WeakMap<FunctionDefinition, Expression>();
761
-
762
704
  // The function constructor of a definition, which SANY locates at the whole definition.
763
- const getDefinitionSource = (definition: FunctionDefinition) => {
764
- const cached = definitionSources.get(definition);
765
- if (cached) return cached;
766
- const source: Expression = {
767
- kind: "FunctionConstruction",
768
- bounds: definition.bounds,
769
- body: definition.body,
770
- location: definition.location,
771
- };
772
- definitionSources.set(definition, source);
773
- return source;
774
- };
705
+ const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
706
+ kind: "FunctionConstruction",
707
+ bounds: definition.bounds,
708
+ body: definition.body,
709
+ location: definition.location,
710
+ });
775
711
 
776
712
  const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
777
713
  const domain = getBoundsDomain(definition.bounds, context);
@@ -785,7 +721,11 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
785
721
  bindArgument(definition.bounds, bindValue(undefined, definition.name, self), argument),
786
722
  ),
787
723
  ),
788
- getLazyFunctionSource(definition.bounds, definition.body, domain),
724
+ getLazyFunctionSource(
725
+ getLazyFunctionTemplate(definition.bounds, definition.body),
726
+ definition.bounds,
727
+ domain,
728
+ ),
789
729
  );
790
730
  keepLambda({
791
731
  value: functionValue,
@@ -818,30 +758,41 @@ const toStartupValue = (definition: Definition, value: Value): Value => {
818
758
  }
819
759
  };
820
760
 
821
- // TLC evaluates a function definition that isn't recursive as it does a function constructor.
822
- const evaluateDefinitionBody = (definition: Definition, context: Context) => {
823
- if (definition.kind !== "Function") return evaluate(definition.body, context);
824
- return definition.isSelfReferential
825
- ? createRecursiveFunction(definition, context)
826
- : evaluate(getDefinitionSource(definition), context);
827
- };
828
-
829
- const evaluateDefinitionValue = (definition: Definition, context: Context) => {
830
- const isConstant = isConstantLevel(definition, context.environment);
831
- const cached = isConstant ? context.environment.definitionValues.get(definition) : undefined;
832
- if (cached !== undefined) return cached;
761
+ // The code of a definition's body, evaluated as a whole. TLC evaluates a function definition that
762
+ // isn't recursive as it does a function constructor.
763
+ const compileDefinitionBody = (definition: Definition, environment: Environment): Evaluator => {
833
764
  if (definition.kind === "Operator" && definition.params.length > 0) {
834
- throw new TlaEvaluationError(
835
- `Operator ${definition.name} requires ${definition.params.length} arguments`,
836
- );
765
+ return () => {
766
+ throw new TlaEvaluationError(
767
+ `Operator ${definition.name} requires ${definition.params.length} arguments`,
768
+ );
769
+ };
837
770
  }
838
- const topLevel = withScope(context, undefined);
839
- if (!isConstant) return evaluateDefinitionBody(definition, topLevel);
840
- const value = context.environment.runtime.evaluateAtStartup(() =>
841
- toStartupValue(definition, evaluateDefinitionBody(definition, topLevel)),
842
- );
843
- context.environment.definitionValues.set(definition, value);
844
- return value;
771
+ if (definition.kind !== "Function") return getEntryEvaluator(definition.body, environment);
772
+ if (definition.isSelfReferential)
773
+ return (context) => createRecursiveFunction(definition, context);
774
+ return getEntryEvaluator(getDefinitionSource(definition), environment);
775
+ };
776
+
777
+ // The code that evaluates a reference to a definition: the value TLC computed at startup when it
778
+ // has one, and the body at the top level otherwise.
779
+ const getDefinitionEvaluator = (definition: Definition, environment: Environment): Evaluator => {
780
+ const compiled = environment.definitionEvaluators.get(definition);
781
+ if (compiled) return compiled;
782
+ const body = compileDefinitionBody(definition, environment);
783
+ const id = environment.facts.ids.get(definition);
784
+ const startupValues = environment.startupValues;
785
+ const evaluator: Evaluator =
786
+ id === undefined
787
+ ? (context) => body(withScope(context, undefined))
788
+ : (context) => startupValues[id] ?? body(withScope(context, undefined));
789
+ environment.definitionEvaluators.set(definition, evaluator);
790
+ return evaluator;
791
+ };
792
+
793
+ export const getStartupValue = (definition: Definition, environment: Environment) => {
794
+ const id = environment.facts.ids.get(definition);
795
+ return id === undefined ? undefined : environment.startupValues[id];
845
796
  };
846
797
 
847
798
  // TLC computes each constant definition the configuration doesn't replace when it starts, and
@@ -852,15 +803,15 @@ export const evaluateStartupDefinitions = (definitions: Definition[], environmen
852
803
  const name = definition.name;
853
804
  if (environment.constants.has(name) || environment.substitutions.has(name)) return;
854
805
  if (!isConstantLevel(definition, environment)) return;
806
+ const id = environment.facts.ids.get(definition);
807
+ if (id === undefined || environment.startupValues[id] !== undefined) return;
808
+ const context = { environment, scope: undefined, state: undefined, next: undefined };
855
809
  try {
856
- markNormalized(
857
- evaluateDefinitionValue(definition, {
858
- environment,
859
- scope: undefined,
860
- state: undefined,
861
- next: undefined,
862
- }),
810
+ const value = environment.runtime.evaluateAtStartup(() =>
811
+ toStartupValue(definition, compileDefinitionBody(definition, environment)(context)),
863
812
  );
813
+ markNormalized(value);
814
+ environment.startupValues[id] = value;
864
815
  } catch (error) {
865
816
  // TLC swallows whatever the definition throws, a stack overflow included.
866
817
  if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
@@ -869,27 +820,25 @@ export const evaluateStartupDefinitions = (definitions: Definition[], environmen
869
820
 
870
821
  const forceThunk = (thunk: Thunk, context: Context) => {
871
822
  const isSameState = thunk.state === context.state && thunk.next === context.next;
872
- if (isSameState && thunk.cache !== undefined) return thunk.cache;
823
+ if (thunk.cache !== undefined && (isSameState || thunk.isReleased)) return thunk.cache;
873
824
  const value = evaluate(thunk.expression, withScope(context, thunk.scope));
874
825
  if (isSameState && (!thunk.isStreamed || isSettledValue(value))) thunk.cache = value;
826
+ // A value a thunk cached with no state read no variable, so it holds in every state. Releasing
827
+ // its scope frees the evaluations the scope's bindings cached, which a long script keeps alive.
828
+ if (thunk.cache !== undefined && thunk.state === undefined && thunk.next === undefined) {
829
+ thunk.scope = undefined;
830
+ thunk.isReleased = true;
831
+ }
875
832
  return value;
876
833
  };
877
834
 
878
- const definitionClosures = new WeakMap<Definition, Closure>();
879
-
880
- const getDefinitionClosure = (definition: Definition & { kind: "Operator" }) => {
881
- const cached = definitionClosures.get(definition);
882
- if (cached) return cached;
883
- const closure: Closure = {
884
- kind: "Closure",
885
- name: definition.name,
886
- params: definition.params,
887
- body: definition.body,
888
- scope: undefined,
889
- };
890
- definitionClosures.set(definition, closure);
891
- return closure;
892
- };
835
+ const getDefinitionClosure = (definition: Definition & { kind: "Operator" }): Closure => ({
836
+ kind: "Closure",
837
+ name: definition.name,
838
+ params: definition.params,
839
+ body: definition.body,
840
+ scope: undefined,
841
+ });
893
842
 
894
843
  export const resolveGlobalOperator = (
895
844
  name: string,
@@ -902,21 +851,14 @@ export const resolveGlobalOperator = (
902
851
  return environment.builtins.get(name);
903
852
  };
904
853
 
905
- const globalApplyOperators = new WeakMap<Expression, Operator | null>();
906
-
907
854
  export const resolveApplyOperator = (
908
855
  expression: Expression & { kind: "Apply" },
909
856
  context: Context,
910
- ): Operator | undefined => {
911
- if (isLocallyResolved(expression)) return resolveOperator(expression.operator, context);
912
- const cached = globalApplyOperators.get(expression);
913
- const global =
914
- cached === undefined
915
- ? (resolveGlobalOperator(expression.operator, context.environment) ?? null)
916
- : cached;
917
- if (cached === undefined) globalApplyOperators.set(expression, global);
918
- return global ?? resolveOperator(expression.operator, context);
919
- };
857
+ ): Operator | undefined =>
858
+ isLocallyResolved(expression)
859
+ ? resolveOperator(expression.operator, context)
860
+ : (resolveGlobalOperator(expression.operator, context.environment) ??
861
+ resolveOperator(expression.operator, context));
920
862
 
921
863
  export const resolveOperator = (name: string, context: Context): Operator | undefined => {
922
864
  const binding = lookupScope(context.scope, name);
@@ -1050,16 +992,6 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
1050
992
  return (context) => createThunk(argument, context);
1051
993
  };
1052
994
 
1053
- const argumentBinders = new WeakMap<Expression, ArgumentBinder>();
1054
-
1055
- const getArgumentBinder = (argument: Expression, environment: Environment) => {
1056
- const cached = argumentBinders.get(argument);
1057
- if (cached) return cached;
1058
- const binder = compileArgumentBinder(argument, environment);
1059
- argumentBinders.set(argument, binder);
1060
- return binder;
1061
- };
1062
-
1063
995
  export const bindOperatorArguments = (
1064
996
  closure: Closure,
1065
997
  args: Expression[],
@@ -1073,36 +1005,23 @@ export const bindOperatorArguments = (
1073
1005
  const binding: Binding =
1074
1006
  param.arity > 0
1075
1007
  ? { kind: "Operator", operator: evaluateOperatorArgument(args[index], context) }
1076
- : (binders?.[index] ?? getArgumentBinder(args[index], context.environment))(context);
1008
+ : (binders?.[index] ?? compileArgumentBinder(args[index], context.environment))(context);
1077
1009
  scope = { name: param.name, binding, parent: scope };
1078
1010
  }
1079
1011
  return scope;
1080
1012
  };
1081
1013
 
1082
- // The body a call site last called and its evaluator, as a site mostly calls one closure.
1083
- interface CalledBody {
1084
- body: Expression;
1085
- evaluator: Evaluator;
1086
- }
1087
-
1088
1014
  const callOperator = (
1089
1015
  operator: Operator,
1090
1016
  args: Expression[],
1091
1017
  context: Context,
1092
- called: { entry: CalledBody | undefined },
1093
1018
  binders: ArgumentBinder[],
1094
1019
  ) => {
1095
1020
  if (operator.kind === "Closure") {
1096
- const bodyContext = withScope(context, bindOperatorArguments(operator, args, context, binders));
1097
- if (context.environment.callStack) return evaluate(operator.body, bodyContext);
1098
- const entry =
1099
- called.entry?.body === operator.body
1100
- ? called.entry
1101
- : (called.entry = {
1102
- body: operator.body,
1103
- evaluator: getEntryEvaluator(operator.body, context.environment),
1104
- });
1105
- return entry.evaluator(bodyContext);
1021
+ return evaluate(
1022
+ operator.body,
1023
+ withScope(context, bindOperatorArguments(operator, args, context, binders)),
1024
+ );
1106
1025
  }
1107
1026
  if (operator.kind === "Operator") return operator.call(args.map((arg) => evaluate(arg, context)));
1108
1027
  if (operator.isLazy) return operator.evaluate(getLazyArguments(args, context), context);
@@ -1115,6 +1034,24 @@ interface ReevaluatedDefinitions {
1115
1034
  streamed: ReadonlySet<Definition>;
1116
1035
  }
1117
1036
 
1037
+ // A LET's function definition has one function constructor, as in SANY, so its code compiles once
1038
+ // however often the LET is evaluated.
1039
+ const letFunctionConstructions = new WeakMap<FunctionDefinition, Expression>();
1040
+
1041
+ const getLetFunctionConstruction = (definition: FunctionDefinition): Expression => {
1042
+ const known = letFunctionConstructions.get(definition);
1043
+ if (known) return known;
1044
+ const construction: Expression = {
1045
+ kind: "FunctionConstruction",
1046
+ bounds: definition.bounds,
1047
+ body: definition.body,
1048
+ location: definition.location,
1049
+ isRecursive: true,
1050
+ };
1051
+ letFunctionConstructions.set(definition, construction);
1052
+ return construction;
1053
+ };
1054
+
1118
1055
  export const bindDefinitions = (
1119
1056
  definitions: Definition[],
1120
1057
  context: Context,
@@ -1129,13 +1066,7 @@ export const bindDefinitions = (
1129
1066
  if (definition.kind === "Function") {
1130
1067
  node.binding = {
1131
1068
  kind: "Thunk",
1132
- expression: {
1133
- kind: "FunctionConstruction",
1134
- bounds: definition.bounds,
1135
- body: definition.body,
1136
- location: definition.location,
1137
- isRecursive: true,
1138
- },
1069
+ expression: getLetFunctionConstruction(definition),
1139
1070
  scope: node,
1140
1071
  state: context.state,
1141
1072
  next: context.next,
@@ -1186,95 +1117,14 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1186
1117
  return value;
1187
1118
  }
1188
1119
  if (global?.kind === "Value") return global.value;
1189
- if (global?.kind === "Definition") return evaluateDefinitionValue(global.definition, context);
1120
+ if (global?.kind === "Definition") {
1121
+ return getDefinitionEvaluator(global.definition, context.environment)(context);
1122
+ }
1190
1123
  const builtin = context.environment.builtins.get(name);
1191
1124
  if (builtin?.arity === 0) return builtin.evaluate([], context);
1192
1125
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
1193
1126
  };
1194
1127
 
1195
- const IMPURE_BUILTINS = new Set([
1196
- "Print",
1197
- "PrintT",
1198
- "Assert",
1199
- "JavaTime",
1200
- "RandomElement",
1201
- "TLCGet",
1202
- "TLCSet",
1203
- ]);
1204
-
1205
- export const isImpureBuiltin = (name: string, environment: Environment) =>
1206
- IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
1207
-
1208
- interface Impurity {
1209
- builtins: Set<string>;
1210
- definitions: WeakMap<Definition, boolean>;
1211
- }
1212
-
1213
- const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
1214
-
1215
- // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
1216
- const REPEATED_EFFECT: Impurity = {
1217
- builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
1218
- definitions: new WeakMap(),
1219
- };
1220
-
1221
- const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
1222
- definition.kind === "Operator" &&
1223
- definition.params.length === 0 &&
1224
- isConstantLevel(definition, environment);
1225
-
1226
- const callsImpureBuiltin = (
1227
- expression: Expression,
1228
- environment: Environment,
1229
- impurity: Impurity,
1230
- ): boolean => {
1231
- const name =
1232
- expression.kind === "Identifier"
1233
- ? expression.name
1234
- : expression.kind === "Apply" || expression.kind === "OperatorReference"
1235
- ? expression.operator
1236
- : undefined;
1237
- if (name !== undefined && !isLocallyResolved(expression)) {
1238
- const definition = getDefinition(name, environment);
1239
- const isImpureCall =
1240
- impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
1241
- if (!definition && isImpureCall) return true;
1242
- if (
1243
- definition &&
1244
- !isEvaluatedOnce(definition, environment) &&
1245
- isImpureDefinition(definition, environment, impurity)
1246
- ) {
1247
- return true;
1248
- }
1249
- }
1250
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
1251
- };
1252
-
1253
- // TLC evaluates a constant definition without parameters once, so only other definitions pass
1254
- // on the side effects and random choices of the builtins they call.
1255
- const isImpureDefinition = (
1256
- definition: Definition,
1257
- environment: Environment,
1258
- impurity = ANY_EFFECT,
1259
- ): boolean => {
1260
- const cached = impurity.definitions.get(definition);
1261
- if (cached !== undefined) return cached;
1262
- impurity.definitions.set(definition, false);
1263
- const isImpure =
1264
- callsImpureBuiltin(definition.body, environment, impurity) ||
1265
- (definition.kind === "Function" &&
1266
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
1267
- impurity.definitions.set(definition, isImpure);
1268
- return isImpure;
1269
- };
1270
-
1271
- // UNION and \cup build sets that stream the sets they combine until TLC caches them, and TLC
1272
- // builds a new one at each evaluation.
1273
- const STREAMED_SET: Impurity = {
1274
- builtins: new Set(["UNION", "\\cup"]),
1275
- definitions: new WeakMap(),
1276
- };
1277
-
1278
1128
  // TLC's next-state generator does not bind LET definitions to values, so each reference to one
1279
1129
  // evaluates it again: one that calls an impure builtin repeats its effects, and a set one builds
1280
1130
  // with UNION or \cup starts out uncached.
@@ -1284,160 +1134,21 @@ export const getReevaluatedDefinitions = (
1284
1134
  ): ReevaluatedDefinitions => ({
1285
1135
  impure: new Set(definitions.filter((definition) => isImpureDefinition(definition, environment))),
1286
1136
  streamed: new Set(
1287
- definitions.filter((definition) => isImpureDefinition(definition, environment, STREAMED_SET)),
1137
+ definitions.filter((definition) => isImpureDefinition(definition, environment, "streamed")),
1288
1138
  ),
1289
1139
  });
1290
1140
 
1291
1141
  export const isImpure = (environment: Environment) =>
1292
- [...environment.definitions.values()].some((definition) =>
1142
+ [...environment.facts.ids.keys()].some((definition) =>
1293
1143
  isImpureDefinition(definition, environment),
1294
1144
  );
1295
1145
 
1296
1146
  // Whether evaluating a definition again can show, such as by printing twice.
1297
1147
  export const hasRepeatedEffects = (environment: Environment) =>
1298
- [...environment.definitions.values()].some((definition) =>
1299
- isImpureDefinition(definition, environment, REPEATED_EFFECT),
1148
+ [...environment.facts.ids.keys()].some((definition) =>
1149
+ isImpureDefinition(definition, environment, "repeated"),
1300
1150
  );
1301
1151
 
1302
- const closedConstants = new WeakMap<Expression, boolean>();
1303
-
1304
- export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
1305
- const cached = closedConstants.get(expression);
1306
- if (cached !== undefined) return cached;
1307
- const isClosed = computeIsClosedConstant(expression, environment, NO_BOUND_NAMES);
1308
- closedConstants.set(expression, isClosed);
1309
- return isClosed;
1310
- };
1311
-
1312
- const CLOSED_KINDS = new Set([
1313
- "Number",
1314
- "String",
1315
- "Identifier",
1316
- "Apply",
1317
- "And",
1318
- "Or",
1319
- "If",
1320
- "Case",
1321
- "SetEnumeration",
1322
- "Tuple",
1323
- "FunctionSet",
1324
- "Record",
1325
- "RecordSet",
1326
- "FunctionApplication",
1327
- "FieldAccess",
1328
- "Product",
1329
- "SetFilter",
1330
- "SetMap",
1331
- "Forall",
1332
- "Exists",
1333
- "Choose",
1334
- "FunctionConstruction",
1335
- "Let",
1336
- ]);
1337
-
1338
- const NO_BOUND_NAMES: ReadonlySet<string> = new Set();
1339
-
1340
- const isClosedIn = (
1341
- expression: Expression,
1342
- environment: Environment,
1343
- bound: ReadonlySet<string>,
1344
- ) =>
1345
- bound.size === 0
1346
- ? isClosedConstant(expression, environment)
1347
- : computeIsClosedConstant(expression, environment, bound);
1348
-
1349
- const computeIsClosedConstant = (
1350
- expression: Expression,
1351
- environment: Environment,
1352
- bound: ReadonlySet<string>,
1353
- ): boolean => {
1354
- if (!CLOSED_KINDS.has(expression.kind)) return false;
1355
- if (expression.kind === "Identifier" && isLocallyResolved(expression)) {
1356
- return bound.has(expression.name);
1357
- }
1358
- if (isLocallyResolved(expression)) return false;
1359
- if (expression.kind === "Identifier") {
1360
- const global = findGlobalName(expression.name, environment);
1361
- if (global?.kind === "Value") return true;
1362
- return global?.kind === "Definition" && isEvaluatedOnce(global.definition, environment);
1363
- }
1364
- if (expression.kind === "Apply") {
1365
- if (
1366
- isImpureBuiltin(expression.operator, environment) ||
1367
- STREAMED_SET.builtins.has(expression.operator) ||
1368
- expression.operator === "~>"
1369
- ) {
1370
- return false;
1371
- }
1372
- const operator = resolveGlobalOperator(expression.operator, environment);
1373
- if (operator?.kind !== "Builtin" && operator?.kind !== "Closure") return false;
1374
- if (operator.kind === "Closure") {
1375
- const definition = getDefinition(expression.operator, environment);
1376
- if (
1377
- !definition ||
1378
- !isConstantLevel(definition, environment) ||
1379
- isImpureDefinition(definition, environment)
1380
- ) {
1381
- return false;
1382
- }
1383
- }
1384
- const params = operator.kind === "Closure" ? operator.params : [];
1385
- const hasOperatorArgument = params.some((param) => param.arity > 0);
1386
- if (hasOperatorArgument) return false;
1387
- return expression.args.every(
1388
- (arg) =>
1389
- arg.kind !== "Lambda" &&
1390
- arg.kind !== "OperatorReference" &&
1391
- isClosedIn(arg, environment, bound),
1392
- );
1393
- }
1394
- const isClosed = { value: true };
1395
- mapChildren(expression, (child, names) => {
1396
- isClosed.value &&= isClosedIn(
1397
- child,
1398
- environment,
1399
- names.length === 0 ? bound : new Set([...bound, ...names]),
1400
- );
1401
- return child;
1402
- });
1403
- return isClosed.value;
1404
- };
1405
-
1406
- export const isWorthCaching = (expression: Expression) =>
1407
- expression.kind !== "Number" && expression.kind !== "String" && expression.kind !== "Identifier";
1408
-
1409
- const cacheFirstValue = (evaluator: Evaluator): Evaluator => {
1410
- const cache = { value: undefined as Value | undefined };
1411
- return (context) => {
1412
- if (cache.value !== undefined) return cache.value;
1413
- const value = evaluator(context);
1414
- cache.value = value;
1415
- return value;
1416
- };
1417
- };
1418
-
1419
- const hasFreeLocals = (expression: Expression, bound: ReadonlySet<string>): boolean => {
1420
- if (expression.kind === "Identifier" && isLocallyResolved(expression)) {
1421
- return !bound.has(expression.name);
1422
- }
1423
- if (isLocallyResolved(expression)) return true;
1424
- const isFree = { value: false };
1425
- mapChildren(expression, (child, names) => {
1426
- isFree.value ||= hasFreeLocals(
1427
- child,
1428
- names.length === 0 ? bound : new Set([...bound, ...names]),
1429
- );
1430
- return child;
1431
- });
1432
- return isFree.value;
1433
- };
1434
-
1435
- const isStateCached = (expression: Expression, environment: Environment) =>
1436
- substitutedExpressions.has(expression) &&
1437
- isWorthCaching(expression) &&
1438
- getReadVariables(expression, environment) !== undefined &&
1439
- !hasFreeLocals(expression, NO_BOUND_NAMES);
1440
-
1441
1152
  // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1442
1153
  // environment.
1443
1154
  interface RebindableFilteredSet extends FilteredSetValue {
@@ -1543,6 +1254,8 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1543
1254
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1544
1255
  ...environment,
1545
1256
  evaluators: new WeakMap(),
1257
+ entryEvaluators: new WeakMap(),
1258
+ definitionEvaluators: new WeakMap(),
1546
1259
  callStack: {
1547
1260
  expressions: [],
1548
1261
  isFrozen: false,
@@ -1559,26 +1272,18 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1559
1272
  const callStack = environment.callStack;
1560
1273
  const evaluator = callStack
1561
1274
  ? traceEvaluator(expression, compiled, environment, callStack)
1562
- : isWorthCaching(expression) && isClosedConstant(expression, environment)
1563
- ? cacheFirstValue(compiled)
1564
- : isStateCached(expression, environment)
1565
- ? cacheStateValue(compiled)
1566
- : compiled;
1275
+ : compiled;
1567
1276
  environment.evaluators.set(expression, evaluator);
1568
1277
  return evaluator;
1569
1278
  };
1570
1279
 
1571
- const entryEvaluators = new WeakMap<Expression, Evaluator>();
1572
-
1573
1280
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1574
1281
  if (environment.callStack) return getEvaluator(expression, environment);
1575
- const cached = entryEvaluators.get(expression);
1576
- if (cached) return cached;
1282
+ const compiled = environment.entryEvaluators.get(expression);
1283
+ if (compiled) return compiled;
1577
1284
  const evaluator =
1578
- (isWorthCaching(expression) && isClosedConstant(expression, environment)
1579
- ? undefined
1580
- : generateEvaluator(expression, environment)) ?? getEvaluator(expression, environment);
1581
- entryEvaluators.set(expression, evaluator);
1285
+ generateEvaluator(expression, environment) ?? getEvaluator(expression, environment);
1286
+ environment.entryEvaluators.set(expression, evaluator);
1582
1287
  return evaluator;
1583
1288
  };
1584
1289
 
@@ -1603,60 +1308,17 @@ const compileIdentifier = (
1603
1308
  const value = global.value;
1604
1309
  return () => value;
1605
1310
  }
1606
- if (global?.kind === "Definition" && global.definition.kind === "Operator") {
1607
- const definition = global.definition;
1608
- if (definition.params.length === 0 && isConstantLevel(definition, environment)) {
1609
- return (context) => evaluateDefinitionValue(definition, context);
1610
- }
1611
- if (definition.params.length === 0) {
1612
- const compiled = { body: undefined as Evaluator | undefined };
1613
- const evaluator: Evaluator = (context) => {
1614
- compiled.body ??= getEntryEvaluator(definition.body, environment);
1615
- return compiled.body(withScope(context, undefined));
1616
- };
1617
- return isStatePure(definition, environment) ? cacheStateValue(evaluator) : evaluator;
1618
- }
1619
- return (context) => evaluateDefinitionValue(definition, context);
1620
- }
1621
1311
  if (global?.kind === "Definition") {
1312
+ // The body compiles when the reference is first evaluated, as a recursive definition's body
1313
+ // refers back to it.
1622
1314
  const definition = global.definition;
1623
- const evaluator: Evaluator = (context) => evaluateDefinitionValue(definition, context);
1624
- return isConstantLevel(definition, environment) || !isStatePure(definition, environment)
1625
- ? evaluator
1626
- : cacheStateValue(evaluator);
1315
+ const compiled = { reference: undefined as Evaluator | undefined };
1316
+ return (context) =>
1317
+ (compiled.reference ??= getDefinitionEvaluator(definition, environment))(context);
1627
1318
  }
1628
1319
  return (context) => evaluateLocalIdentifier(name, expression, context);
1629
1320
  };
1630
1321
 
1631
- const isStatePure = (definition: Definition, environment: Environment) =>
1632
- getReadVariables(definition.body, environment) !== undefined &&
1633
- (definition.kind === "Operator" ||
1634
- definition.bounds.every((bound) => getReadVariables(bound.set, environment) !== undefined));
1635
-
1636
- const cacheStateValue = (evaluator: Evaluator): Evaluator => {
1637
- const cache = {
1638
- recent: undefined as Context["state"],
1639
- recentValue: undefined as Value | undefined,
1640
- previous: undefined as Context["state"],
1641
- previousValue: undefined as Value | undefined,
1642
- };
1643
- return (context) => {
1644
- const state = context.state;
1645
- if (state !== undefined && cache.recent === state && cache.recentValue !== undefined) {
1646
- return cache.recentValue;
1647
- }
1648
- if (state !== undefined && cache.previous === state && cache.previousValue !== undefined) {
1649
- return cache.previousValue;
1650
- }
1651
- const value = evaluator(context);
1652
- cache.previous = cache.recent;
1653
- cache.previousValue = cache.recentValue;
1654
- cache.recent = state;
1655
- cache.recentValue = value;
1656
- return value;
1657
- };
1658
- };
1659
-
1660
1322
  export const isValueArgument = (argument: Expression, environment: Environment) => {
1661
1323
  if (argument.kind === "Lambda" || argument.kind === "OperatorReference") return false;
1662
1324
  if (argument.kind !== "Identifier" || isLocallyResolved(argument)) return true;
@@ -1711,7 +1373,7 @@ export const compileArgumentScope = (
1711
1373
  }
1712
1374
  const params = closure.params;
1713
1375
  const binders = args.map((arg, index) =>
1714
- params[index].arity > 0 ? undefined : getArgumentBinder(arg, environment),
1376
+ params[index].arity > 0 ? undefined : compileArgumentBinder(arg, environment),
1715
1377
  );
1716
1378
  return (context) => {
1717
1379
  let scope = closure.scope;
@@ -1726,240 +1388,24 @@ export const compileArgumentScope = (
1726
1388
  };
1727
1389
  };
1728
1390
 
1729
- interface MemoizedCall {
1730
- sources: (Expression | undefined)[];
1731
- args: Value[];
1732
- value: Value;
1733
- }
1734
-
1735
- const MEMOIZED_CALL_LIMIT = 1 << 16;
1736
-
1737
- // A call site that finds fewer than half its calls in a state's memo after this many new ones
1738
- // stops paying for the lookups.
1739
- const MEMOIZED_TRIAL_CALLS = 1 << 10;
1740
-
1741
- interface CallMemo {
1742
- calls: Map<number, MemoizedCall[]>;
1743
- size: number;
1744
- state: Context["state"];
1745
- }
1746
-
1747
- interface CallMemos {
1748
- constant: CallMemo;
1749
- state: CallMemo;
1750
- }
1751
-
1752
- const createCallMemo = (): CallMemo => ({ calls: new Map(), size: 0, state: undefined });
1753
-
1754
- const callMemos = new WeakMap<Closure, CallMemos>();
1755
-
1756
- const getCallMemos = (closure: Closure) => {
1757
- const cached = callMemos.get(closure);
1758
- if (cached) return cached;
1759
- const memos = { constant: createCallMemo(), state: createCallMemo() };
1760
- callMemos.set(closure, memos);
1761
- return memos;
1762
- };
1763
-
1764
- const readsExceptAt = (expression: Expression): boolean =>
1765
- expression.kind === "ExceptAt" || getChildren(expression).some(readsExceptAt);
1766
-
1767
- // The locals an argument expression reads, when the state and their values decide its value. An @
1768
- // reads the value its EXCEPT binds.
1769
- const argumentLocals = new WeakMap<Expression, string[] | false>();
1770
-
1771
- const getArgumentLocals = (expression: Expression, environment: Environment) => {
1772
- const cached = argumentLocals.get(expression);
1773
- if (cached !== undefined) return cached;
1774
- const locals =
1775
- getReadVariables(expression, environment) !== undefined &&
1776
- getReadLocals(expression, NO_BOUND_NAMES);
1777
- const unique = locals && [
1778
- ...new Set(readsExceptAt(expression) ? [...locals, EXCEPT_AT] : locals),
1779
- ];
1780
- argumentLocals.set(expression, unique ?? false);
1781
- return unique ?? false;
1782
- };
1783
-
1784
- // Hashing a lazy set or function would enumerate it, which TLC does only when it has to.
1785
- const isEagerValue = (value: Value) =>
1786
- typeof value !== "object" ||
1787
- value.kind === "ModelValue" ||
1788
- value.kind === "Set" ||
1789
- value.kind === "Function" ||
1790
- value.kind === "Interval";
1791
-
1792
- // The key of the call being looked up, copied into the memo only when the call is new. Counts
1793
- // mark its ends, since shortening an array is slow.
1794
- const callKey = {
1795
- sources: [] as (Expression | undefined)[],
1796
- sourceCount: 0,
1797
- args: [] as Value[],
1798
- argCount: 0,
1799
- hash: 0,
1800
- isStateKeyed: false,
1801
- };
1802
-
1803
- // A model value's rank tells it apart without hashing its name.
1804
- const getKeyHash = (value: Value) =>
1805
- typeof value === "object" && value.kind === "ModelValue" ? value.rank : getValueHash(value);
1806
-
1807
- const pushKeyValue = (value: Value) => {
1808
- if (!isEagerValue(value)) return false;
1809
- callKey.sources[callKey.sourceCount++] = undefined;
1810
- callKey.args[callKey.argCount++] = value;
1811
- callKey.hash = combineHash(callKey.hash, getKeyHash(value));
1812
- return true;
1813
- };
1814
-
1815
- // An argument TLC has not evaluated yet stands for its expression and the values of the locals it
1816
- // reads, so a call keeps the laziness of its arguments.
1817
- const pushKeyExpression = (
1818
- expression: Expression,
1819
- locals: string[] | false,
1820
- scope: Scope | undefined,
1821
- ) => {
1822
- if (!locals) return false;
1823
- callKey.sources[callKey.sourceCount++] = expression;
1824
- callKey.isStateKeyed = true;
1825
- for (let index = 0; index < locals.length; index++) {
1826
- const local = lookupScope(scope, locals[index]);
1827
- if (local?.kind !== "Value" || !isEagerValue(local.value)) return false;
1828
- callKey.args[callKey.argCount++] = local.value;
1829
- callKey.hash = combineHash(callKey.hash, getKeyHash(local.value));
1830
- }
1831
- return true;
1832
- };
1833
-
1834
- // Each argument adds to the key what compileArgumentBinder would bind its parameter to.
1835
- const compileArgumentKey = (
1836
- argument: Expression,
1837
- environment: Environment,
1838
- ): ((context: Context) => boolean) => {
1839
- const isLiteral =
1840
- argument.kind === "String" || (argument.kind === "Number" && isTlcInteger(argument.value));
1841
- if (isLiteral) return () => pushKeyValue(argument.value);
1842
- if (argument.kind === "Identifier") {
1843
- const global = isLocallyResolved(argument)
1844
- ? undefined
1845
- : findGlobalName(argument.name, environment);
1846
- if (global?.kind === "Value") return () => pushKeyValue(global.value);
1847
- if (global === undefined) {
1848
- return (context) => {
1849
- const binding = lookupScope(context.scope, argument.name);
1850
- if (binding?.kind === "Value") return pushKeyValue(binding.value);
1851
- if (binding?.kind !== "Thunk" || binding.state !== context.state) return false;
1852
- return pushKeyExpression(
1853
- binding.expression,
1854
- getArgumentLocals(binding.expression, environment),
1855
- binding.scope,
1856
- );
1857
- };
1858
- }
1859
- }
1860
- const locals = getArgumentLocals(argument, environment);
1861
- return (context) => pushKeyExpression(argument, locals, context.scope);
1862
- };
1863
-
1864
- const isKnownCall = (call: MemoizedCall) => {
1865
- if (call.args.length !== callKey.argCount || call.sources.length !== callKey.sourceCount) {
1866
- return false;
1867
- }
1868
- for (let index = 0; index < callKey.sourceCount; index++) {
1869
- if (call.sources[index] !== callKey.sources[index]) return false;
1870
- }
1871
- for (let index = 0; index < callKey.argCount; index++) {
1872
- if (!isSameValue(call.args[index], callKey.args[index])) return false;
1873
- }
1874
- return true;
1875
- };
1876
-
1877
- const findCall = (bucket: MemoizedCall[] | undefined) => {
1878
- if (bucket === undefined) return undefined;
1879
- for (let index = 0; index < bucket.length; index++) {
1880
- if (isKnownCall(bucket[index])) return bucket[index];
1881
- }
1882
- return undefined;
1883
- };
1884
-
1885
- // An operator without side effects yields the same value for the same arguments, a state-level one
1886
- // in the same state, so its calls share one result.
1887
- const getMemoizedLevel = (expression: Expression & { kind: "Apply" }, environment: Environment) => {
1888
- const definition = getDefinition(expression.operator, environment);
1889
- const isMemoizable =
1890
- definition?.kind === "Operator" &&
1891
- definition.params.length > 0 &&
1892
- definition.params.every((param) => param.arity === 0) &&
1893
- !isImpureDefinition(definition, environment);
1894
- if (!isMemoizable) return undefined;
1895
- if (isConstantLevel(definition, environment)) return "constant";
1896
- return isStatePure(definition, environment) ? "state" : undefined;
1897
- };
1898
-
1899
1391
  const compileClosureCall = (
1900
1392
  closure: Closure,
1901
1393
  args: Expression[],
1902
1394
  environment: Environment,
1903
- memoizedLevel: "constant" | "state" | undefined,
1904
1395
  ): Evaluator => {
1905
1396
  const bindArguments = compileArgumentScope(closure, args, environment);
1397
+ // The body compiles when the call is first evaluated, as a recursive operator's body calls it.
1906
1398
  const compiled = { body: undefined as Evaluator | undefined };
1907
- const evaluateBody = (scope: Scope | undefined, context: Context) => {
1399
+ return (context) => {
1908
1400
  compiled.body ??= getEntryEvaluator(closure.body, environment);
1909
1401
  return compiled.body({
1910
1402
  environment,
1911
- scope,
1403
+ scope: bindArguments(context),
1912
1404
  state: context.state,
1913
1405
  next: context.next,
1914
1406
  isKeepLazy: context.isKeepLazy,
1915
1407
  });
1916
1408
  };
1917
- if (!memoizedLevel || args.length !== closure.params.length) {
1918
- return (context) => evaluateBody(bindArguments(context), context);
1919
- }
1920
- const memos = getCallMemos(closure);
1921
- const keys = args.map((arg) => compileArgumentKey(arg, environment));
1922
- const usage = { hits: 0, misses: 0 };
1923
- return (context) => {
1924
- // A call TLC evaluates with EvalControl.KeepLazy builds what a memoized one wouldn't.
1925
- if (context.isKeepLazy) return evaluateBody(bindArguments(context), context);
1926
- callKey.sourceCount = 0;
1927
- callKey.argCount = 0;
1928
- callKey.hash = args.length;
1929
- callKey.isStateKeyed = false;
1930
- for (let index = 0; index < keys.length; index++) {
1931
- if (!keys[index](context)) return evaluateBody(bindArguments(context), context);
1932
- }
1933
- const isStateKeyed = memoizedLevel === "state" || callKey.isStateKeyed;
1934
- if (isStateKeyed && usage.misses > MEMOIZED_TRIAL_CALLS && usage.hits < usage.misses) {
1935
- return evaluateBody(bindArguments(context), context);
1936
- }
1937
- const memo = isStateKeyed ? memos.state : memos.constant;
1938
- if (isStateKeyed && memo.state !== context.state) {
1939
- memo.state = context.state;
1940
- memo.calls.clear();
1941
- memo.size = 0;
1942
- }
1943
- // A small integer key keeps the Map from boxing it.
1944
- const hash = callKey.hash & 0x3fffffff;
1945
- const bucket = memo.calls.get(hash);
1946
- const known = findCall(bucket);
1947
- if (known) {
1948
- if (isStateKeyed) usage.hits++;
1949
- return known.value;
1950
- }
1951
- if (isStateKeyed) usage.misses++;
1952
- const sources = callKey.sources.slice(0, callKey.sourceCount);
1953
- const keyArgs = callKey.args.slice(0, callKey.argCount);
1954
- const value = evaluateBody(bindArguments(context), context);
1955
- if (memo.size < MEMOIZED_CALL_LIMIT) {
1956
- memo.size++;
1957
- const call = { sources, args: keyArgs, value };
1958
- if (bucket) bucket.push(call);
1959
- else memo.calls.set(hash, [call]);
1960
- }
1961
- return value;
1962
- };
1963
1409
  };
1964
1410
 
1965
1411
  const compileApply = (
@@ -1982,13 +1428,7 @@ const compileApply = (
1982
1428
  const global = isLocallyResolved(expression)
1983
1429
  ? undefined
1984
1430
  : resolveGlobalOperator(expression.operator, environment);
1985
- if (global?.kind === "Closure") {
1986
- // The replay records the evaluation of each call, which TLC repeats.
1987
- const memoizedLevel = environment.callStack
1988
- ? undefined
1989
- : getMemoizedLevel(expression, environment);
1990
- return compileClosureCall(global, args, environment, memoizedLevel);
1991
- }
1431
+ if (global?.kind === "Closure") return compileClosureCall(global, args, environment);
1992
1432
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1993
1433
  const operand = getEvaluator(args[0], environment);
1994
1434
  const domain = getDomainOperator(expression);
@@ -2020,11 +1460,10 @@ const compileApply = (
2020
1460
  );
2021
1461
  };
2022
1462
  }
2023
- const called = { entry: undefined as CalledBody | undefined };
2024
- const binders = args.map((arg) => getArgumentBinder(arg, environment));
1463
+ const binders = args.map((arg) => compileArgumentBinder(arg, environment));
2025
1464
  return (context) => {
2026
1465
  const operator = resolveOperator(expression.operator, context);
2027
- if (operator) return callOperator(operator, args, context, called, binders);
1466
+ if (operator) return callOperator(operator, args, context, binders);
2028
1467
  const definition = environment.definitions.get(expression.operator);
2029
1468
  if (definition?.kind === "Function") {
2030
1469
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
@@ -2110,6 +1549,39 @@ export const keepLazy = (expression: Expression) => {
2110
1549
  }
2111
1550
  };
2112
1551
 
1552
+ // The names an expression may look up in its scope, or undefined when a subexpression selector may
1553
+ // look up others.
1554
+ const scopeNames = new WeakMap<Expression, string[] | undefined>();
1555
+
1556
+ const getScopeNames = (expression: Expression) => {
1557
+ if (scopeNames.has(expression)) return scopeNames.get(expression);
1558
+ const names = new Set<string>();
1559
+ const visit = (node: Expression): boolean => {
1560
+ if (node.kind === "Subexpression") return false;
1561
+ if (node.kind === "Identifier") names.add(node.name);
1562
+ if (node.kind === "Apply" || node.kind === "OperatorReference") names.add(node.operator);
1563
+ if (node.kind === "ExceptAt") names.add(EXCEPT_AT);
1564
+ return getChildren(node).every(visit);
1565
+ };
1566
+ const result = visit(expression) ? [...names] : undefined;
1567
+ scopeNames.set(expression, result);
1568
+ return result;
1569
+ };
1570
+
1571
+ // The bindings of a scope that names look up, so that a lazy function keeps only those alive and
1572
+ // not the values its other bindings cached. An unnamed node ends the chain, since a TLCEval in the
1573
+ // body sorts its value only where no context binds a name.
1574
+ const trimScope = (scope: Scope | undefined, names: string[] | undefined) =>
1575
+ names === undefined || scope === undefined
1576
+ ? scope
1577
+ : names.reduce<Scope>(
1578
+ (trimmed, name) => {
1579
+ const binding = lookupScope(scope, name);
1580
+ return binding ? { name, binding, parent: trimmed } : trimmed;
1581
+ },
1582
+ { name: "", binding: { kind: "Value", value: false }, parent: undefined },
1583
+ );
1584
+
2113
1585
  const compileFunctionConstruction = (
2114
1586
  expression: Expression & { kind: "FunctionConstruction" },
2115
1587
  environment: Environment,
@@ -2149,16 +1621,20 @@ const compileFunctionConstruction = (
2149
1621
  });
2150
1622
  return createFunction(pairs);
2151
1623
  };
1624
+ const template = getLazyFunctionTemplate(bounds, expression.body);
1625
+ const bodyNames = getScopeNames(expression.body);
2152
1626
  const createLazy = (domain: Value, context: Context) => {
1627
+ const scope = trimScope(context.scope, bodyNames);
1628
+ const lambdaContext = withScope(context, scope);
2153
1629
  const functionValue = keepLambda({
2154
1630
  value: createLazyFunction(
2155
1631
  domain,
2156
- (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
2157
- getLazyFunctionSource(bounds, expression.body, domain),
1632
+ (argument) => body(withScope(lambdaContext, bindArgument(bounds, scope, argument))),
1633
+ getLazyFunctionSource(template, bounds, domain),
2158
1634
  ),
2159
1635
  bounds,
2160
1636
  body: expression.body,
2161
- scope: context.scope,
1637
+ scope,
2162
1638
  });
2163
1639
  return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
2164
1640
  };