tla 0.0.10-dev.c43a3006b → 0.0.10-dev.e5d473777

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/typed-tier.ts CHANGED
@@ -1754,6 +1754,13 @@ interface Frame {
1754
1754
  substitutions?: ReadonlyMap<Expression, Binding>;
1755
1755
  stateFunctions?: StateFunctionBindings[];
1756
1756
  isInit?: boolean;
1757
+ loop?: Loop;
1758
+ }
1759
+
1760
+ interface Loop {
1761
+ outer: ReadonlySet<Binding>;
1762
+ names: LazyDefinition[];
1763
+ parent: Loop | undefined;
1757
1764
  }
1758
1765
 
1759
1766
  interface SetLoop {
@@ -1806,6 +1813,12 @@ const getDeclarations = (definitions: LazyDefinition[]) =>
1806
1813
  .map((item) => `let ${item.name}; const ${item.name}f = () => ${item.value.emit()};`)
1807
1814
  .join(" ");
1808
1815
 
1816
+ const getDeclarationHeader = (program: Program, definitions: LazyDefinition[]) => {
1817
+ if (definitions.length === 0) return "";
1818
+ const pass = getName(program, "o");
1819
+ return `for (let ${definitions.map((item) => `${item.name}, ${item.name}f = () => ${item.value.emit()}`).join(", ")}, ${pass} = true; ${pass}; ${pass} = false) `;
1820
+ };
1821
+
1809
1822
  const isBuiltin = (program: Program, frame: Frame, operator: string, name: string) =>
1810
1823
  getBuiltinName(operator, program.environment) === name && !frame.scope.has(operator);
1811
1824
 
@@ -1909,7 +1922,11 @@ const compileRecursion = (
1909
1922
  );
1910
1923
  const body = inline(program, definition, () =>
1911
1924
  expectType(
1912
- compileValue(program, definition.body, { ...frame, scope: bodyScope }),
1925
+ compileValue(program, definition.body, {
1926
+ ...frame,
1927
+ scope: bodyScope,
1928
+ loop: isHoisted ? undefined : frame.loop,
1929
+ }),
1913
1930
  recursion.result,
1914
1931
  ),
1915
1932
  );
@@ -2301,7 +2318,7 @@ const compileIdentifier = (program: Program, name: string, frame: Frame): Compil
2301
2318
  const bound = shared.bindings.get(definition);
2302
2319
  if (bound) return bound;
2303
2320
  const value = inline(program, definition, () =>
2304
- compileValue(program, definition.body, { ...frame, scope: new Map() }),
2321
+ compileValue(program, definition.body, { ...frame, scope: new Map(), loop: undefined }),
2305
2322
  );
2306
2323
  const innerName = getName(program, "l");
2307
2324
  shared.names.push({ name: innerName, value });
@@ -2551,12 +2568,19 @@ const compileBound = (program: Program, setExpression: Expression, frame: Frame)
2551
2568
  const table =
2552
2569
  setExpression.kind === "Apply" ? compileTable(program, setExpression, frame) : undefined;
2553
2570
  if (table) return getSetBound(program, table, true);
2571
+ const names: LazyDefinition[] = [];
2554
2572
  const expansion =
2555
- setExpression.kind === "Apply" ? getExpansion(program, setExpression, frame) : undefined;
2573
+ setExpression.kind === "Apply" ? getExpansion(program, setExpression, frame, names) : undefined;
2556
2574
  if (expansion) {
2557
- return inline(program, expansion.definition, () =>
2575
+ const loop = inline(program, expansion.definition, () =>
2558
2576
  compileBound(program, expansion.definition.body, { ...frame, scope: expansion.scope }),
2559
2577
  );
2578
+ return names.length === 0
2579
+ ? loop
2580
+ : {
2581
+ ...loop,
2582
+ header: (name) => `${getDeclarationHeader(program, names)}${loop.header(name)}`,
2583
+ };
2560
2584
  }
2561
2585
  // TLC enumerates a set of records with its fields in TLC's order of names, the last one varying fastest.
2562
2586
  if (setExpression.kind === "RecordSet") {
@@ -2694,7 +2718,101 @@ const compileBound = (program: Program, setExpression: Expression, frame: Frame)
2694
2718
  isBounded: false,
2695
2719
  };
2696
2720
  }
2697
- return getSetBound(program, compileValue(program, setExpression, frame), true);
2721
+ const target = getInvariantLoop(program, setExpression, frame);
2722
+ if (!target) return getSetBound(program, compileValue(program, setExpression, frame), true);
2723
+ const value = compileValue(program, setExpression, {
2724
+ ...frame,
2725
+ scope: getByNameScope(frame.scope, target.outer, new Map()),
2726
+ loop: target.parent,
2727
+ });
2728
+ const name = getName(program, "l");
2729
+ target.names.push({ name, value });
2730
+ return getSetBound(program, { type: value.type, emit: () => getLazyCode(name) }, true);
2731
+ };
2732
+
2733
+ const getInvariantLoop = (program: Program, expression: Expression, frame: Frame) => {
2734
+ if (
2735
+ expression.kind === "FunctionApplication" ||
2736
+ expression.kind === "FieldAccess" ||
2737
+ (expression.kind === "Identifier" && frame.scope.get(expression.name)?.kind !== "Operator") ||
2738
+ frame.isEnumerated ||
2739
+ frame.isInit ||
2740
+ frame.isNext ||
2741
+ frame.isCompiledTwice ||
2742
+ (frame.substitutions?.size ?? 0) > 0
2743
+ ) {
2744
+ return undefined;
2745
+ }
2746
+ let target: Loop | undefined;
2747
+ for (
2748
+ let loop = frame.loop;
2749
+ loop && isLoopInvariant(program, expression, frame.scope, loop.outer, new Set());
2750
+ loop = loop.parent
2751
+ ) {
2752
+ target = loop;
2753
+ }
2754
+ return target;
2755
+ };
2756
+
2757
+ const isLoopInvariant = (
2758
+ program: Program,
2759
+ expression: Expression,
2760
+ scope: TierScope,
2761
+ outer: ReadonlySet<Binding>,
2762
+ visited: Set<Binding>,
2763
+ ): boolean => {
2764
+ const visit = (inner: Expression): boolean => {
2765
+ if (inner.kind === "ExceptAt" || inner.kind === "Subexpression" || inner.kind === "Selection") {
2766
+ return false;
2767
+ }
2768
+ const name = getReferencedName(inner);
2769
+ const binding = name === undefined ? undefined : scope.get(name);
2770
+ if (
2771
+ binding &&
2772
+ !visited.has(binding) &&
2773
+ (binding.kind === "Operator" || (!outer.has(binding) && binding.constant === undefined))
2774
+ ) {
2775
+ visited.add(binding);
2776
+ const source = binding.kind === "Operator" ? binding : binding.source;
2777
+ if (
2778
+ !source ||
2779
+ !isLoopInvariant(program, source.definition.body, source.scope, outer, visited)
2780
+ ) {
2781
+ return false;
2782
+ }
2783
+ }
2784
+ return getChildren(inner).every(visit);
2785
+ };
2786
+ return (
2787
+ visit(expression) &&
2788
+ !isExpressionImpure([expression], program.environment, "reevaluated") &&
2789
+ !isAction(program, expression, scope)
2790
+ );
2791
+ };
2792
+
2793
+ const getByNameScope = (
2794
+ scope: TierScope,
2795
+ outer: ReadonlySet<Binding>,
2796
+ converted: Map<TierScope, TierScope>,
2797
+ ): TierScope => {
2798
+ const known = converted.get(scope);
2799
+ if (known) return known;
2800
+ const result = new Map<string, Binding>();
2801
+ converted.set(scope, result);
2802
+ for (const [name, binding] of scope) {
2803
+ const source = binding.kind === "Operator" ? binding : binding.source;
2804
+ result.set(
2805
+ name,
2806
+ outer.has(binding) || !source || (binding.kind === "Code" && binding.constant !== undefined)
2807
+ ? binding
2808
+ : {
2809
+ kind: "Operator",
2810
+ definition: source.definition,
2811
+ scope: getByNameScope(source.scope, outer, converted),
2812
+ },
2813
+ );
2814
+ }
2815
+ return result;
2698
2816
  };
2699
2817
 
2700
2818
  const getIndexedLoop = (program: Program, name: string, array: string) => {
@@ -2868,9 +2986,10 @@ const compileBounds = (program: Program, bounds: Bound[], frame: Frame, isFirstF
2868
2986
  });
2869
2987
  return bindPattern(program, current, pattern.names, element, loop.element, name);
2870
2988
  }, frame.scope);
2989
+ const loop: Loop = { outer: new Set(frame.scope.values()), names: [], parent: frame.loop };
2871
2990
  const getHeaders = () =>
2872
- (isFirstFastest ? loops.toReversed() : loops).map((loop) => loop.header(loop.name)).join(" ");
2873
- return { scope, loops, getHeaders };
2991
+ `${getDeclarationHeader(program, loop.names)}${(isFirstFastest ? loops.toReversed() : loops).map((inner) => inner.header(inner.name)).join(" ")}`;
2992
+ return { scope, loops, getHeaders, frame: { ...frame, scope, loop } };
2874
2993
  };
2875
2994
 
2876
2995
  const bindPattern = (
@@ -2900,9 +3019,7 @@ const compileQuantifier = (
2900
3019
  frame: Frame,
2901
3020
  ): Compiled => {
2902
3021
  const bounds = compileBounds(program, expression.bounds, frame);
2903
- const body = expectBool(
2904
- compileValue(program, expression.body, { ...frame, scope: bounds.scope }),
2905
- );
3022
+ const body = expectBool(compileValue(program, expression.body, bounds.frame));
2906
3023
  const isForall = expression.kind === "Forall";
2907
3024
  return {
2908
3025
  type: createBool(),
@@ -4928,9 +5045,7 @@ const compileValue = (program: Program, expression: Expression, frame: Frame): C
4928
5045
  [{ pattern: expression.pattern, set: expression.set }],
4929
5046
  frame,
4930
5047
  );
4931
- const predicate = expectBool(
4932
- compileValue(program, expression.body, { ...frame, scope: bounds.scope }),
4933
- );
5048
+ const predicate = expectBool(compileValue(program, expression.body, bounds.frame));
4934
5049
  const stop = isUniformPredicate(expression.pattern, expression.body, program.environment)
4935
5050
  ? " else return H.deopt();"
4936
5051
  : "";
@@ -4967,9 +5082,7 @@ const compileValue = (program: Program, expression: Expression, frame: Frame): C
4967
5082
  case "SetFilter": {
4968
5083
  const bounds = compileBounds(program, [expression.bound], frame);
4969
5084
  const loop = bounds.loops[0];
4970
- const predicate = expectBool(
4971
- compileValue(program, expression.predicate, { ...frame, scope: bounds.scope }),
4972
- );
5085
+ const predicate = expectBool(compileValue(program, expression.predicate, bounds.frame));
4973
5086
  const result = getName(program, "r");
4974
5087
  const stop = isUniformPredicate(
4975
5088
  expression.bound.pattern,
@@ -4989,10 +5102,7 @@ const compileValue = (program: Program, expression: Expression, frame: Frame): C
4989
5102
  }
4990
5103
  case "SetMap": {
4991
5104
  const bounds = compileBounds(program, expression.bounds, frame);
4992
- const element = compileValue(program, expression.expression, {
4993
- ...frame,
4994
- scope: bounds.scope,
4995
- });
5105
+ const element = compileValue(program, expression.expression, bounds.frame);
4996
5106
  const result = getName(program, "r");
4997
5107
  const isBounded = bounds.loops.length === 1 && bounds.loops[0].isBounded;
4998
5108
  const type: SetType = { kind: "Set", element: element.type };
@@ -5760,6 +5870,7 @@ interface Pending {
5760
5870
  scope: TierScope;
5761
5871
  inlining: Definition[];
5762
5872
  variables?: string[];
5873
+ stateFunctions?: StateFunctionBindings[];
5763
5874
  }
5764
5875
 
5765
5876
  type StepMode = "Next" | "Enabled" | "Init";
@@ -5783,6 +5894,7 @@ const getStepFrame = (
5783
5894
  primed,
5784
5895
  variables: item.variables ?? getVariableCodes(program),
5785
5896
  isNext: false,
5897
+ stateFunctions: item.stateFunctions,
5786
5898
  };
5787
5899
 
5788
5900
  // TLC finds an action enabled where its conjuncts hold, whatever variables it leaves unassigned.
@@ -5851,6 +5963,7 @@ const compileStep = (
5851
5963
  scope,
5852
5964
  inlining,
5853
5965
  variables: first.variables,
5966
+ stateFunctions: first.stateFunctions,
5854
5967
  })),
5855
5968
  ...rest,
5856
5969
  ],
@@ -8068,6 +8181,11 @@ const compileSpec = (
8068
8181
  ): CompiledSpec => {
8069
8182
  const unprimed = program.variableTypes.map(() => undefined);
8070
8183
  const init = program.plains.isInitCompiled ? compileInit(program, check, unprimed) : undefined;
8184
+ const nextFunctions: StateFunctionBindings = {
8185
+ variables: getVariableCodes(program),
8186
+ names: [],
8187
+ bindings: new Map(),
8188
+ };
8071
8189
  const next = (actions ?? [{ expression: check.next, scope: check.scope }]).map((action) =>
8072
8190
  compileStep(
8073
8191
  program,
@@ -8076,6 +8194,7 @@ const compileSpec = (
8076
8194
  expression: action.expression,
8077
8195
  scope: getCheckScope(program, action.scope),
8078
8196
  inlining: [],
8197
+ stateFunctions: [nextFunctions],
8079
8198
  },
8080
8199
  ],
8081
8200
  unprimed,
@@ -8419,7 +8538,8 @@ const compileSpec = (
8419
8538
  }
8420
8539
  n = W.start + m;`;
8421
8540
  const initCode = init?.();
8422
- const nextCode = next.map((step, position) => `{ C[0] = ${position}; ${step()} }`).join(" ");
8541
+ const stepCode = next.map((step, position) => `{ C[0] = ${position}; ${step()} }`).join(" ");
8542
+ const nextCode = `${getDeclarations(nextFunctions.names)} ${stepCode}`;
8423
8543
  const invariantCodes = invariants.map(getStatePredicate);
8424
8544
  const constraintCodes = constraints.map(getStatePredicate);
8425
8545
  const liveStep = getName(program, "s");