tla-ts 0.0.8 → 0.0.9-dev.5790648

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/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,
@@ -137,12 +140,18 @@ export interface Environment {
137
140
  instanceNames: Map<string, string>;
138
141
  variables: string[];
139
142
  variableIndex: Map<string, number>;
140
- definitionValues: Map<Definition, Value>;
141
- constantLevels: Map<Definition, boolean>;
143
+ facts: DefinitionFacts;
144
+ // The value of each constant definition TLC computed when it started, by the definition's id in
145
+ // facts. TLC evaluates a definition it failed to compute where the spec uses it.
146
+ startupValues: (Value | undefined)[];
142
147
  // The definitions an INSTANCE copies from a module that declares constants or variables. SANY
143
148
  // wraps the body of each in its substitutions.
144
149
  substitutedDefinitions: Set<Definition>;
150
+ // The compiled code of each expression, of each expression evaluated as a whole, which generated
151
+ // code can serve, and of each reference to a definition.
145
152
  evaluators: WeakMap<Expression, Evaluator>;
153
+ entryEvaluators: WeakMap<Expression, Evaluator>;
154
+ definitionEvaluators: WeakMap<Definition, Evaluator>;
146
155
  // The expressions being evaluated, outermost first, when the environment replays an error to
147
156
  // find where it occurred, as TLC's CallStackTool does.
148
157
  callStack?: CallStack;
@@ -434,57 +443,6 @@ export const expectBoolean = (value: Value, description: string) => {
434
443
  export const getDefinition = (name: string, environment: Environment) =>
435
444
  environment.definitions.get(environment.substitutions.get(name) ?? name);
436
445
 
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
446
  const getBoundExplanation = (set: Value, text: string) => {
489
447
  const quantified = `universally (\\A) or existentially (\\E) quantify over ${text}, because this would require checking an\ninfinite number of cases.`;
490
448
  if (typeof set === "object" && set.kind === "SequenceSet") {
@@ -519,7 +477,7 @@ const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion
519
477
  const getEnumeratedElements = (set: Value, expression: Expression, version: TlcVersion) => {
520
478
  checkEnumerable(set, expression, version);
521
479
  if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
522
- return getLazySubsets(set) ?? toFiniteSet(set).elements;
480
+ return getLazySubsets(set) ?? getNormalizedSetElements(set);
523
481
  };
524
482
 
525
483
  // The elements Tool.contexts binds to the bound of a quantifier or a set map. TLC 1.7.4 streams a
@@ -686,14 +644,10 @@ interface LazyFunctionTemplate {
686
644
  body: string;
687
645
  }
688
646
 
689
- const lazyFunctionTemplates = new WeakMap<Expression, LazyFunctionTemplate>();
690
-
691
647
  const getLazyFunctionTemplate = (bounds: Bound[], body: Expression) => {
692
- const cached = lazyFunctionTemplates.get(body);
693
- if (cached) return cached;
694
648
  const range = body.location.range;
695
649
  if (!range) return undefined;
696
- const template = {
650
+ return {
697
651
  parameters: bounds.flatMap((bound, index) =>
698
652
  index > 0 && bounds[index - 1].set === bound.set
699
653
  ? []
@@ -709,12 +663,13 @@ const getLazyFunctionTemplate = (bounds: Bound[], body: Expression) => {
709
663
  ),
710
664
  body: formatRange(range),
711
665
  };
712
- lazyFunctionTemplates.set(body, template);
713
- return template;
714
666
  };
715
667
 
716
- const getLazyFunctionSource = (bounds: Bound[], body: Expression, domain: Value) => {
717
- const template = getLazyFunctionTemplate(bounds, body);
668
+ const getLazyFunctionSource = (
669
+ template: LazyFunctionTemplate | undefined,
670
+ bounds: Bound[],
671
+ domain: Value,
672
+ ) => {
718
673
  if (!template) return undefined;
719
674
  const domains =
720
675
  bounds.length > 1 && typeof domain === "object" && domain.kind === "ProductSet"
@@ -729,49 +684,28 @@ const getLazyFunctionSource = (bounds: Bound[], body: Expression, domain: Value)
729
684
  };
730
685
  };
731
686
 
687
+ // TLC's FcnLambdaValue evaluates its body at each application.
732
688
  const createLazyFunction = (
733
689
  domain: Value,
734
690
  compute: (argument: Value, self: LazyFunctionValue) => Value,
735
691
  source: LazyFunctionSource | undefined,
736
692
  ) => {
737
- const memo = new Map<number, Value[]>();
738
693
  const self: LazyFunctionValue = {
739
694
  kind: "LazyFunction",
740
695
  domain,
741
696
  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
- },
697
+ apply: (argument) => compute(argument, self),
756
698
  };
757
699
  return self;
758
700
  };
759
701
 
760
- const definitionSources = new WeakMap<FunctionDefinition, Expression>();
761
-
762
702
  // 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
- };
703
+ const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
704
+ kind: "FunctionConstruction",
705
+ bounds: definition.bounds,
706
+ body: definition.body,
707
+ location: definition.location,
708
+ });
775
709
 
776
710
  const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
777
711
  const domain = getBoundsDomain(definition.bounds, context);
@@ -785,7 +719,11 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
785
719
  bindArgument(definition.bounds, bindValue(undefined, definition.name, self), argument),
786
720
  ),
787
721
  ),
788
- getLazyFunctionSource(definition.bounds, definition.body, domain),
722
+ getLazyFunctionSource(
723
+ getLazyFunctionTemplate(definition.bounds, definition.body),
724
+ definition.bounds,
725
+ domain,
726
+ ),
789
727
  );
790
728
  keepLambda({
791
729
  value: functionValue,
@@ -818,30 +756,41 @@ const toStartupValue = (definition: Definition, value: Value): Value => {
818
756
  }
819
757
  };
820
758
 
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;
759
+ // The code of a definition's body, evaluated as a whole. TLC evaluates a function definition that
760
+ // isn't recursive as it does a function constructor.
761
+ const compileDefinitionBody = (definition: Definition, environment: Environment): Evaluator => {
833
762
  if (definition.kind === "Operator" && definition.params.length > 0) {
834
- throw new TlaEvaluationError(
835
- `Operator ${definition.name} requires ${definition.params.length} arguments`,
836
- );
763
+ return () => {
764
+ throw new TlaEvaluationError(
765
+ `Operator ${definition.name} requires ${definition.params.length} arguments`,
766
+ );
767
+ };
837
768
  }
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;
769
+ if (definition.kind !== "Function") return getEntryEvaluator(definition.body, environment);
770
+ if (definition.isSelfReferential)
771
+ return (context) => createRecursiveFunction(definition, context);
772
+ return getEntryEvaluator(getDefinitionSource(definition), environment);
773
+ };
774
+
775
+ // The code that evaluates a reference to a definition: the value TLC computed at startup when it
776
+ // has one, and the body at the top level otherwise.
777
+ const getDefinitionEvaluator = (definition: Definition, environment: Environment): Evaluator => {
778
+ const compiled = environment.definitionEvaluators.get(definition);
779
+ if (compiled) return compiled;
780
+ const body = compileDefinitionBody(definition, environment);
781
+ const id = environment.facts.ids.get(definition);
782
+ const startupValues = environment.startupValues;
783
+ const evaluator: Evaluator =
784
+ id === undefined
785
+ ? (context) => body(withScope(context, undefined))
786
+ : (context) => startupValues[id] ?? body(withScope(context, undefined));
787
+ environment.definitionEvaluators.set(definition, evaluator);
788
+ return evaluator;
789
+ };
790
+
791
+ export const getStartupValue = (definition: Definition, environment: Environment) => {
792
+ const id = environment.facts.ids.get(definition);
793
+ return id === undefined ? undefined : environment.startupValues[id];
845
794
  };
846
795
 
847
796
  // TLC computes each constant definition the configuration doesn't replace when it starts, and
@@ -852,15 +801,15 @@ export const evaluateStartupDefinitions = (definitions: Definition[], environmen
852
801
  const name = definition.name;
853
802
  if (environment.constants.has(name) || environment.substitutions.has(name)) return;
854
803
  if (!isConstantLevel(definition, environment)) return;
804
+ const id = environment.facts.ids.get(definition);
805
+ if (id === undefined || environment.startupValues[id] !== undefined) return;
806
+ const context = { environment, scope: undefined, state: undefined, next: undefined };
855
807
  try {
856
- markNormalized(
857
- evaluateDefinitionValue(definition, {
858
- environment,
859
- scope: undefined,
860
- state: undefined,
861
- next: undefined,
862
- }),
808
+ const value = environment.runtime.evaluateAtStartup(() =>
809
+ toStartupValue(definition, compileDefinitionBody(definition, environment)(context)),
863
810
  );
811
+ markNormalized(value);
812
+ environment.startupValues[id] = value;
864
813
  } catch (error) {
865
814
  // TLC swallows whatever the definition throws, a stack overflow included.
866
815
  if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
@@ -875,21 +824,13 @@ const forceThunk = (thunk: Thunk, context: Context) => {
875
824
  return value;
876
825
  };
877
826
 
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
- };
827
+ const getDefinitionClosure = (definition: Definition & { kind: "Operator" }): Closure => ({
828
+ kind: "Closure",
829
+ name: definition.name,
830
+ params: definition.params,
831
+ body: definition.body,
832
+ scope: undefined,
833
+ });
893
834
 
894
835
  export const resolveGlobalOperator = (
895
836
  name: string,
@@ -902,21 +843,14 @@ export const resolveGlobalOperator = (
902
843
  return environment.builtins.get(name);
903
844
  };
904
845
 
905
- const globalApplyOperators = new WeakMap<Expression, Operator | null>();
906
-
907
846
  export const resolveApplyOperator = (
908
847
  expression: Expression & { kind: "Apply" },
909
848
  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
- };
849
+ ): Operator | undefined =>
850
+ isLocallyResolved(expression)
851
+ ? resolveOperator(expression.operator, context)
852
+ : (resolveGlobalOperator(expression.operator, context.environment) ??
853
+ resolveOperator(expression.operator, context));
920
854
 
921
855
  export const resolveOperator = (name: string, context: Context): Operator | undefined => {
922
856
  const binding = lookupScope(context.scope, name);
@@ -1050,16 +984,6 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
1050
984
  return (context) => createThunk(argument, context);
1051
985
  };
1052
986
 
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
987
  export const bindOperatorArguments = (
1064
988
  closure: Closure,
1065
989
  args: Expression[],
@@ -1073,36 +997,23 @@ export const bindOperatorArguments = (
1073
997
  const binding: Binding =
1074
998
  param.arity > 0
1075
999
  ? { kind: "Operator", operator: evaluateOperatorArgument(args[index], context) }
1076
- : (binders?.[index] ?? getArgumentBinder(args[index], context.environment))(context);
1000
+ : (binders?.[index] ?? compileArgumentBinder(args[index], context.environment))(context);
1077
1001
  scope = { name: param.name, binding, parent: scope };
1078
1002
  }
1079
1003
  return scope;
1080
1004
  };
1081
1005
 
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
1006
  const callOperator = (
1089
1007
  operator: Operator,
1090
1008
  args: Expression[],
1091
1009
  context: Context,
1092
- called: { entry: CalledBody | undefined },
1093
1010
  binders: ArgumentBinder[],
1094
1011
  ) => {
1095
1012
  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);
1013
+ return evaluate(
1014
+ operator.body,
1015
+ withScope(context, bindOperatorArguments(operator, args, context, binders)),
1016
+ );
1106
1017
  }
1107
1018
  if (operator.kind === "Operator") return operator.call(args.map((arg) => evaluate(arg, context)));
1108
1019
  if (operator.isLazy) return operator.evaluate(getLazyArguments(args, context), context);
@@ -1186,95 +1097,14 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1186
1097
  return value;
1187
1098
  }
1188
1099
  if (global?.kind === "Value") return global.value;
1189
- if (global?.kind === "Definition") return evaluateDefinitionValue(global.definition, context);
1100
+ if (global?.kind === "Definition") {
1101
+ return getDefinitionEvaluator(global.definition, context.environment)(context);
1102
+ }
1190
1103
  const builtin = context.environment.builtins.get(name);
1191
1104
  if (builtin?.arity === 0) return builtin.evaluate([], context);
1192
1105
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
1193
1106
  };
1194
1107
 
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
1108
  // TLC's next-state generator does not bind LET definitions to values, so each reference to one
1279
1109
  // evaluates it again: one that calls an impure builtin repeats its effects, and a set one builds
1280
1110
  // with UNION or \cup starts out uncached.
@@ -1284,160 +1114,21 @@ export const getReevaluatedDefinitions = (
1284
1114
  ): ReevaluatedDefinitions => ({
1285
1115
  impure: new Set(definitions.filter((definition) => isImpureDefinition(definition, environment))),
1286
1116
  streamed: new Set(
1287
- definitions.filter((definition) => isImpureDefinition(definition, environment, STREAMED_SET)),
1117
+ definitions.filter((definition) => isImpureDefinition(definition, environment, "streamed")),
1288
1118
  ),
1289
1119
  });
1290
1120
 
1291
1121
  export const isImpure = (environment: Environment) =>
1292
- [...environment.definitions.values()].some((definition) =>
1122
+ [...environment.facts.ids.keys()].some((definition) =>
1293
1123
  isImpureDefinition(definition, environment),
1294
1124
  );
1295
1125
 
1296
1126
  // Whether evaluating a definition again can show, such as by printing twice.
1297
1127
  export const hasRepeatedEffects = (environment: Environment) =>
1298
- [...environment.definitions.values()].some((definition) =>
1299
- isImpureDefinition(definition, environment, REPEATED_EFFECT),
1128
+ [...environment.facts.ids.keys()].some((definition) =>
1129
+ isImpureDefinition(definition, environment, "repeated"),
1300
1130
  );
1301
1131
 
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
1132
  // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1442
1133
  // environment.
1443
1134
  interface RebindableFilteredSet extends FilteredSetValue {
@@ -1543,6 +1234,8 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1543
1234
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1544
1235
  ...environment,
1545
1236
  evaluators: new WeakMap(),
1237
+ entryEvaluators: new WeakMap(),
1238
+ definitionEvaluators: new WeakMap(),
1546
1239
  callStack: {
1547
1240
  expressions: [],
1548
1241
  isFrozen: false,
@@ -1559,26 +1252,18 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1559
1252
  const callStack = environment.callStack;
1560
1253
  const evaluator = callStack
1561
1254
  ? traceEvaluator(expression, compiled, environment, callStack)
1562
- : isWorthCaching(expression) && isClosedConstant(expression, environment)
1563
- ? cacheFirstValue(compiled)
1564
- : isStateCached(expression, environment)
1565
- ? cacheStateValue(compiled)
1566
- : compiled;
1255
+ : compiled;
1567
1256
  environment.evaluators.set(expression, evaluator);
1568
1257
  return evaluator;
1569
1258
  };
1570
1259
 
1571
- const entryEvaluators = new WeakMap<Expression, Evaluator>();
1572
-
1573
1260
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1574
1261
  if (environment.callStack) return getEvaluator(expression, environment);
1575
- const cached = entryEvaluators.get(expression);
1576
- if (cached) return cached;
1262
+ const compiled = environment.entryEvaluators.get(expression);
1263
+ if (compiled) return compiled;
1577
1264
  const evaluator =
1578
- (isWorthCaching(expression) && isClosedConstant(expression, environment)
1579
- ? undefined
1580
- : generateEvaluator(expression, environment)) ?? getEvaluator(expression, environment);
1581
- entryEvaluators.set(expression, evaluator);
1265
+ generateEvaluator(expression, environment) ?? getEvaluator(expression, environment);
1266
+ environment.entryEvaluators.set(expression, evaluator);
1582
1267
  return evaluator;
1583
1268
  };
1584
1269
 
@@ -1603,60 +1288,17 @@ const compileIdentifier = (
1603
1288
  const value = global.value;
1604
1289
  return () => value;
1605
1290
  }
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
1291
  if (global?.kind === "Definition") {
1292
+ // The body compiles when the reference is first evaluated, as a recursive definition's body
1293
+ // refers back to it.
1622
1294
  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);
1295
+ const compiled = { reference: undefined as Evaluator | undefined };
1296
+ return (context) =>
1297
+ (compiled.reference ??= getDefinitionEvaluator(definition, environment))(context);
1627
1298
  }
1628
1299
  return (context) => evaluateLocalIdentifier(name, expression, context);
1629
1300
  };
1630
1301
 
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
1302
  export const isValueArgument = (argument: Expression, environment: Environment) => {
1661
1303
  if (argument.kind === "Lambda" || argument.kind === "OperatorReference") return false;
1662
1304
  if (argument.kind !== "Identifier" || isLocallyResolved(argument)) return true;
@@ -1711,7 +1353,7 @@ export const compileArgumentScope = (
1711
1353
  }
1712
1354
  const params = closure.params;
1713
1355
  const binders = args.map((arg, index) =>
1714
- params[index].arity > 0 ? undefined : getArgumentBinder(arg, environment),
1356
+ params[index].arity > 0 ? undefined : compileArgumentBinder(arg, environment),
1715
1357
  );
1716
1358
  return (context) => {
1717
1359
  let scope = closure.scope;
@@ -1726,240 +1368,24 @@ export const compileArgumentScope = (
1726
1368
  };
1727
1369
  };
1728
1370
 
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
1371
  const compileClosureCall = (
1900
1372
  closure: Closure,
1901
1373
  args: Expression[],
1902
1374
  environment: Environment,
1903
- memoizedLevel: "constant" | "state" | undefined,
1904
1375
  ): Evaluator => {
1905
1376
  const bindArguments = compileArgumentScope(closure, args, environment);
1377
+ // The body compiles when the call is first evaluated, as a recursive operator's body calls it.
1906
1378
  const compiled = { body: undefined as Evaluator | undefined };
1907
- const evaluateBody = (scope: Scope | undefined, context: Context) => {
1379
+ return (context) => {
1908
1380
  compiled.body ??= getEntryEvaluator(closure.body, environment);
1909
1381
  return compiled.body({
1910
1382
  environment,
1911
- scope,
1383
+ scope: bindArguments(context),
1912
1384
  state: context.state,
1913
1385
  next: context.next,
1914
1386
  isKeepLazy: context.isKeepLazy,
1915
1387
  });
1916
1388
  };
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
1389
  };
1964
1390
 
1965
1391
  const compileApply = (
@@ -1982,13 +1408,7 @@ const compileApply = (
1982
1408
  const global = isLocallyResolved(expression)
1983
1409
  ? undefined
1984
1410
  : 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
- }
1411
+ if (global?.kind === "Closure") return compileClosureCall(global, args, environment);
1992
1412
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1993
1413
  const operand = getEvaluator(args[0], environment);
1994
1414
  const domain = getDomainOperator(expression);
@@ -2020,11 +1440,10 @@ const compileApply = (
2020
1440
  );
2021
1441
  };
2022
1442
  }
2023
- const called = { entry: undefined as CalledBody | undefined };
2024
- const binders = args.map((arg) => getArgumentBinder(arg, environment));
1443
+ const binders = args.map((arg) => compileArgumentBinder(arg, environment));
2025
1444
  return (context) => {
2026
1445
  const operator = resolveOperator(expression.operator, context);
2027
- if (operator) return callOperator(operator, args, context, called, binders);
1446
+ if (operator) return callOperator(operator, args, context, binders);
2028
1447
  const definition = environment.definitions.get(expression.operator);
2029
1448
  if (definition?.kind === "Function") {
2030
1449
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
@@ -2149,16 +1568,18 @@ const compileFunctionConstruction = (
2149
1568
  });
2150
1569
  return createFunction(pairs);
2151
1570
  };
1571
+ const template = getLazyFunctionTemplate(bounds, expression.body);
2152
1572
  const createLazy = (domain: Value, context: Context) => {
1573
+ const scope = context.scope;
2153
1574
  const functionValue = keepLambda({
2154
1575
  value: createLazyFunction(
2155
1576
  domain,
2156
- (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
2157
- getLazyFunctionSource(bounds, expression.body, domain),
1577
+ (argument) => body(withScope(context, bindArgument(bounds, scope, argument))),
1578
+ getLazyFunctionSource(template, bounds, domain),
2158
1579
  ),
2159
1580
  bounds,
2160
1581
  body: expression.body,
2161
- scope: context.scope,
1582
+ scope,
2162
1583
  });
2163
1584
  return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
2164
1585
  };