tla-ts 0.0.4-dev.5f6a4bf → 0.0.4-dev.a0009b7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.4-dev.5f6a4bf",
3
+ "version": "0.0.4-dev.a0009b7",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/evaluate.ts CHANGED
@@ -21,7 +21,7 @@ import type { CheckerRuntime } from "./runtime";
21
21
  import { getReadVariables } from "./dependencies";
22
22
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
23
23
  import { prettyPrint } from "./pretty-print";
24
- import { isEnabled } from "./successors";
24
+ import { getReadLocals, isEnabled } from "./successors";
25
25
  import {
26
26
  applyFunction,
27
27
  describeMissingArgument,
@@ -578,15 +578,19 @@ interface LazyFunction {
578
578
  scope: Scope | undefined;
579
579
  }
580
580
 
581
- const lazyFunctions = new WeakMap<LazyFunctionValue, LazyFunction>();
581
+ // The function keeps its parameters, body and scope itself, since a WeakMap entry for each
582
+ // short-lived function makes every garbage collection slower.
583
+ interface KeptLazyFunctionValue extends LazyFunctionValue {
584
+ lambda: LazyFunction;
585
+ }
582
586
 
583
- const keepLambda = (lambda: LazyFunction) => {
584
- lazyFunctions.set(lambda.value, lambda);
585
- return lambda.value;
586
- };
587
+ const isKeptLazyFunction = (value: Value): value is KeptLazyFunctionValue =>
588
+ typeof value === "object" && value.kind === "LazyFunction" && "lambda" in value;
589
+
590
+ const keepLambda = (lambda: LazyFunction) => Object.assign(lambda.value, { lambda });
587
591
 
588
592
  export const getLazyFunction = (value: Value) =>
589
- typeof value === "object" && value.kind === "LazyFunction" ? lazyFunctions.get(value) : undefined;
593
+ isKeptLazyFunction(value) ? value.lambda : undefined;
590
594
 
591
595
  // Tool.getFcnContext: the scope of a lazy function's body for the arguments of an application. It
592
596
  // ignores arguments beyond the parameters.
@@ -1375,9 +1379,14 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1375
1379
  getReadVariables(expression, environment) !== undefined &&
1376
1380
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1377
1381
 
1378
- // How to rebuild a set filter TLC evaluates lazily so that its predicate runs in another
1382
+ // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1379
1383
  // environment.
1380
- const filteredSetRebinders = new WeakMap<FilteredSetValue, (environment: Environment) => Value>();
1384
+ interface RebindableFilteredSet extends FilteredSetValue {
1385
+ rebind: (environment: Environment) => Value;
1386
+ }
1387
+
1388
+ const isRebindableFilteredSet = (value: Value): value is RebindableFilteredSet =>
1389
+ typeof value === "object" && value.kind === "FilteredSet" && "rebind" in value;
1381
1390
 
1382
1391
  // TLC's CallStackTool rebinds the lazy values its evaluations return, so their later evaluation
1383
1392
  // records its call stack too.
@@ -1398,11 +1407,7 @@ const traceEvaluator =
1398
1407
  setTrace.callStack = callStack;
1399
1408
  try {
1400
1409
  const computed = evaluator(context);
1401
- const rebind =
1402
- typeof computed === "object" && computed.kind === "FilteredSet"
1403
- ? filteredSetRebinders.get(computed)
1404
- : undefined;
1405
- const value = rebind ? rebind(environment) : computed;
1410
+ const value = isRebindableFilteredSet(computed) ? computed.rebind(environment) : computed;
1406
1411
  callStack.values.set(expression, value);
1407
1412
  if (typeof value === "object" && value.kind !== "FilteredSet" && isSourced(expression)) {
1408
1413
  callStack.sources.set(value, expression);
@@ -1680,52 +1685,180 @@ export const compileArgumentScope = (
1680
1685
  };
1681
1686
 
1682
1687
  interface MemoizedCall {
1688
+ sources: (Expression | undefined)[];
1683
1689
  args: Value[];
1684
1690
  value: Value;
1685
1691
  }
1686
1692
 
1687
1693
  const MEMOIZED_CALL_LIMIT = 1 << 16;
1688
1694
 
1689
- const callMemos = new WeakMap<Closure, { calls: Map<number, MemoizedCall[]>; size: number }>();
1695
+ // A call site that finds fewer than half its calls in a state's memo after this many new ones
1696
+ // stops paying for the lookups.
1697
+ const MEMOIZED_TRIAL_CALLS = 1 << 10;
1698
+
1699
+ interface CallMemo {
1700
+ calls: Map<number, MemoizedCall[]>;
1701
+ size: number;
1702
+ state: Context["state"];
1703
+ }
1704
+
1705
+ interface CallMemos {
1706
+ constant: CallMemo;
1707
+ state: CallMemo;
1708
+ }
1709
+
1710
+ const createCallMemo = (): CallMemo => ({ calls: new Map(), size: 0, state: undefined });
1690
1711
 
1691
- const getCallMemo = (closure: Closure) => {
1712
+ const callMemos = new WeakMap<Closure, CallMemos>();
1713
+
1714
+ const getCallMemos = (closure: Closure) => {
1692
1715
  const cached = callMemos.get(closure);
1693
1716
  if (cached) return cached;
1694
- const memo = { calls: new Map<number, MemoizedCall[]>(), size: 0 };
1695
- callMemos.set(closure, memo);
1696
- return memo;
1717
+ const memos = { constant: createCallMemo(), state: createCallMemo() };
1718
+ callMemos.set(closure, memos);
1719
+ return memos;
1697
1720
  };
1698
1721
 
1699
- const getArgumentValues = (scope: Scope | undefined, arity: number) => {
1700
- const values: Value[] = [];
1701
- for (let current = scope; values.length < arity; current = current?.parent) {
1702
- if (current?.binding.kind !== "Value") return undefined;
1703
- values.push(current.binding.value);
1722
+ const readsExceptAt = (expression: Expression): boolean =>
1723
+ expression.kind === "ExceptAt" || getChildren(expression).some(readsExceptAt);
1724
+
1725
+ // The locals an argument expression reads, when the state and their values decide its value. An @
1726
+ // reads the value its EXCEPT binds.
1727
+ const argumentLocals = new WeakMap<Expression, string[] | false>();
1728
+
1729
+ const getArgumentLocals = (expression: Expression, environment: Environment) => {
1730
+ const cached = argumentLocals.get(expression);
1731
+ if (cached !== undefined) return cached;
1732
+ const locals =
1733
+ getReadVariables(expression, environment) !== undefined &&
1734
+ getReadLocals(expression, NO_BOUND_NAMES);
1735
+ const unique = locals && [
1736
+ ...new Set(readsExceptAt(expression) ? [...locals, EXCEPT_AT] : locals),
1737
+ ];
1738
+ argumentLocals.set(expression, unique ?? false);
1739
+ return unique ?? false;
1740
+ };
1741
+
1742
+ // Hashing a lazy set or function would enumerate it, which TLC does only when it has to.
1743
+ const isEagerValue = (value: Value) =>
1744
+ typeof value !== "object" ||
1745
+ value.kind === "ModelValue" ||
1746
+ value.kind === "Set" ||
1747
+ value.kind === "Function" ||
1748
+ value.kind === "Interval";
1749
+
1750
+ // The key of the call being looked up, copied into the memo only when the call is new. Counts
1751
+ // mark its ends, since shortening an array is slow.
1752
+ const callKey = {
1753
+ sources: [] as (Expression | undefined)[],
1754
+ sourceCount: 0,
1755
+ args: [] as Value[],
1756
+ argCount: 0,
1757
+ hash: 0,
1758
+ isStateKeyed: false,
1759
+ };
1760
+
1761
+ // A model value's rank tells it apart without hashing its name.
1762
+ const getKeyHash = (value: Value) =>
1763
+ typeof value === "object" && value.kind === "ModelValue" ? value.rank : getValueHash(value);
1764
+
1765
+ const pushKeyValue = (value: Value) => {
1766
+ if (!isEagerValue(value)) return false;
1767
+ callKey.sources[callKey.sourceCount++] = undefined;
1768
+ callKey.args[callKey.argCount++] = value;
1769
+ callKey.hash = combineHash(callKey.hash, getKeyHash(value));
1770
+ return true;
1771
+ };
1772
+
1773
+ // An argument TLC has not evaluated yet stands for its expression and the values of the locals it
1774
+ // reads, so a call keeps the laziness of its arguments.
1775
+ const pushKeyExpression = (
1776
+ expression: Expression,
1777
+ locals: string[] | false,
1778
+ scope: Scope | undefined,
1779
+ ) => {
1780
+ if (!locals) return false;
1781
+ callKey.sources[callKey.sourceCount++] = expression;
1782
+ callKey.isStateKeyed = true;
1783
+ for (let index = 0; index < locals.length; index++) {
1784
+ const local = lookupScope(scope, locals[index]);
1785
+ if (local?.kind !== "Value" || !isEagerValue(local.value)) return false;
1786
+ callKey.args[callKey.argCount++] = local.value;
1787
+ callKey.hash = combineHash(callKey.hash, getKeyHash(local.value));
1704
1788
  }
1705
- return values;
1789
+ return true;
1706
1790
  };
1707
1791
 
1708
- const isSameArguments = (left: Value[], right: Value[]) =>
1709
- left.every((value, index) => isSameValue(value, right[index]));
1792
+ // Each argument adds to the key what compileArgumentBinder would bind its parameter to.
1793
+ const compileArgumentKey = (
1794
+ argument: Expression,
1795
+ environment: Environment,
1796
+ ): ((context: Context) => boolean) => {
1797
+ const isLiteral =
1798
+ argument.kind === "String" || (argument.kind === "Number" && isTlcInteger(argument.value));
1799
+ if (isLiteral) return () => pushKeyValue(argument.value);
1800
+ if (argument.kind === "Identifier") {
1801
+ const global = isLocallyResolved(argument)
1802
+ ? undefined
1803
+ : findGlobalName(argument.name, environment);
1804
+ if (global?.kind === "Value") return () => pushKeyValue(global.value);
1805
+ if (global === undefined) {
1806
+ return (context) => {
1807
+ const binding = lookupScope(context.scope, argument.name);
1808
+ if (binding?.kind === "Value") return pushKeyValue(binding.value);
1809
+ if (binding?.kind !== "Thunk" || binding.state !== context.state) return false;
1810
+ return pushKeyExpression(
1811
+ binding.expression,
1812
+ getArgumentLocals(binding.expression, environment),
1813
+ binding.scope,
1814
+ );
1815
+ };
1816
+ }
1817
+ }
1818
+ const locals = getArgumentLocals(argument, environment);
1819
+ return (context) => pushKeyExpression(argument, locals, context.scope);
1820
+ };
1821
+
1822
+ const isKnownCall = (call: MemoizedCall) => {
1823
+ if (call.args.length !== callKey.argCount || call.sources.length !== callKey.sourceCount) {
1824
+ return false;
1825
+ }
1826
+ for (let index = 0; index < callKey.sourceCount; index++) {
1827
+ if (call.sources[index] !== callKey.sources[index]) return false;
1828
+ }
1829
+ for (let index = 0; index < callKey.argCount; index++) {
1830
+ if (!isSameValue(call.args[index], callKey.args[index])) return false;
1831
+ }
1832
+ return true;
1833
+ };
1834
+
1835
+ const findCall = (bucket: MemoizedCall[] | undefined) => {
1836
+ if (bucket === undefined) return undefined;
1837
+ for (let index = 0; index < bucket.length; index++) {
1838
+ if (isKnownCall(bucket[index])) return bucket[index];
1839
+ }
1840
+ return undefined;
1841
+ };
1710
1842
 
1711
- // A constant-level operator without side effects yields the same value for the same arguments,
1712
- // so its calls with evaluated arguments share one result.
1713
- const isMemoizable = (expression: Expression & { kind: "Apply" }, environment: Environment) => {
1843
+ // An operator without side effects yields the same value for the same arguments, a state-level one
1844
+ // in the same state, so its calls share one result.
1845
+ const getMemoizedLevel = (expression: Expression & { kind: "Apply" }, environment: Environment) => {
1714
1846
  const definition = getDefinition(expression.operator, environment);
1715
- return (
1847
+ const isMemoizable =
1716
1848
  definition?.kind === "Operator" &&
1717
1849
  definition.params.length > 0 &&
1718
1850
  definition.params.every((param) => param.arity === 0) &&
1719
- isConstantLevel(definition, environment) &&
1720
- !isImpureDefinition(definition, environment)
1721
- );
1851
+ !isImpureDefinition(definition, environment);
1852
+ if (!isMemoizable) return undefined;
1853
+ if (isConstantLevel(definition, environment)) return "constant";
1854
+ return isStatePure(definition, environment) ? "state" : undefined;
1722
1855
  };
1723
1856
 
1724
1857
  const compileClosureCall = (
1725
1858
  closure: Closure,
1726
1859
  args: Expression[],
1727
1860
  environment: Environment,
1728
- isMemoized: boolean,
1861
+ memoizedLevel: "constant" | "state" | undefined,
1729
1862
  ): Evaluator => {
1730
1863
  const bindArguments = compileArgumentScope(closure, args, environment);
1731
1864
  const compiled = { body: undefined as Evaluator | undefined };
@@ -1739,23 +1872,49 @@ const compileClosureCall = (
1739
1872
  isKeepLazy: context.isKeepLazy,
1740
1873
  });
1741
1874
  };
1742
- if (!isMemoized) return (context) => evaluateBody(bindArguments(context), context);
1743
- const memo = getCallMemo(closure);
1875
+ if (!memoizedLevel || args.length !== closure.params.length) {
1876
+ return (context) => evaluateBody(bindArguments(context), context);
1877
+ }
1878
+ const memos = getCallMemos(closure);
1879
+ const keys = args.map((arg) => compileArgumentKey(arg, environment));
1880
+ const usage = { hits: 0, misses: 0 };
1744
1881
  return (context) => {
1745
- const scope = bindArguments(context);
1746
- const values = getArgumentValues(scope, args.length);
1747
1882
  // A call TLC evaluates with EvalControl.KeepLazy builds what a memoized one wouldn't.
1748
- if (!values || context.isKeepLazy) return evaluateBody(scope, context);
1749
- let hash = values.length;
1750
- for (const value of values) hash = combineHash(hash, getValueHash(value));
1883
+ if (context.isKeepLazy) return evaluateBody(bindArguments(context), context);
1884
+ callKey.sourceCount = 0;
1885
+ callKey.argCount = 0;
1886
+ callKey.hash = args.length;
1887
+ callKey.isStateKeyed = false;
1888
+ for (let index = 0; index < keys.length; index++) {
1889
+ if (!keys[index](context)) return evaluateBody(bindArguments(context), context);
1890
+ }
1891
+ const isStateKeyed = memoizedLevel === "state" || callKey.isStateKeyed;
1892
+ if (isStateKeyed && usage.misses > MEMOIZED_TRIAL_CALLS && usage.hits < usage.misses) {
1893
+ return evaluateBody(bindArguments(context), context);
1894
+ }
1895
+ const memo = isStateKeyed ? memos.state : memos.constant;
1896
+ if (isStateKeyed && memo.state !== context.state) {
1897
+ memo.state = context.state;
1898
+ memo.calls.clear();
1899
+ memo.size = 0;
1900
+ }
1901
+ // A small integer key keeps the Map from boxing it.
1902
+ const hash = callKey.hash & 0x3fffffff;
1751
1903
  const bucket = memo.calls.get(hash);
1752
- const known = bucket?.find((call) => isSameArguments(call.args, values));
1753
- if (known) return known.value;
1754
- const value = evaluateBody(scope, context);
1904
+ const known = findCall(bucket);
1905
+ if (known) {
1906
+ if (isStateKeyed) usage.hits++;
1907
+ return known.value;
1908
+ }
1909
+ if (isStateKeyed) usage.misses++;
1910
+ const sources = callKey.sources.slice(0, callKey.sourceCount);
1911
+ const keyArgs = callKey.args.slice(0, callKey.argCount);
1912
+ const value = evaluateBody(bindArguments(context), context);
1755
1913
  if (memo.size < MEMOIZED_CALL_LIMIT) {
1756
1914
  memo.size++;
1757
- if (bucket) bucket.push({ args: values, value });
1758
- else memo.calls.set(hash, [{ args: values, value }]);
1915
+ const call = { sources, args: keyArgs, value };
1916
+ if (bucket) bucket.push(call);
1917
+ else memo.calls.set(hash, [call]);
1759
1918
  }
1760
1919
  return value;
1761
1920
  };
@@ -1783,8 +1942,10 @@ const compileApply = (
1783
1942
  : resolveGlobalOperator(expression.operator, environment);
1784
1943
  if (global?.kind === "Closure") {
1785
1944
  // The replay records the evaluation of each call, which TLC repeats.
1786
- const isMemoized = !environment.callStack && isMemoizable(expression, environment);
1787
- return compileClosureCall(global, args, environment, isMemoized);
1945
+ const memoizedLevel = environment.callStack
1946
+ ? undefined
1947
+ : getMemoizedLevel(expression, environment);
1948
+ return compileClosureCall(global, args, environment, memoizedLevel);
1788
1949
  }
1789
1950
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1790
1951
  const operand = getEvaluator(args[0], environment);
@@ -2069,22 +2230,18 @@ const compileSetComprehension = (
2069
2230
  base: Value,
2070
2231
  context: Context,
2071
2232
  evaluator: Evaluator,
2072
- ): FilteredSetValue => {
2073
- const filtered: FilteredSetValue = {
2074
- kind: "FilteredSet",
2075
- base,
2076
- test: createTest(evaluator, context),
2077
- source,
2078
- };
2079
- filteredSetRebinders.set(filtered, (tracing) =>
2233
+ ): RebindableFilteredSet => ({
2234
+ kind: "FilteredSet",
2235
+ base,
2236
+ test: createTest(evaluator, context),
2237
+ source,
2238
+ rebind: (tracing) =>
2080
2239
  createFiltered(
2081
2240
  base,
2082
2241
  { ...context, environment: tracing },
2083
2242
  getEvaluator(expression.predicate, tracing),
2084
2243
  ),
2085
- );
2086
- return filtered;
2087
- };
2244
+ });
2088
2245
  return (context) => {
2089
2246
  const base = set(context);
2090
2247
  // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
package/src/live-check.ts CHANGED
@@ -83,6 +83,7 @@ interface Check {
83
83
  firstNodes: Pool<Int32Array>;
84
84
  lastNodes: Pool<Int32Array>;
85
85
  nextSiblings: number[];
86
+ nodeIds: NodeTable;
86
87
  isDone: boolean[];
87
88
  errorNode: number | undefined;
88
89
  }
@@ -140,6 +141,26 @@ const writeToPool = <Data extends Int32Array | Uint8Array>(
140
141
 
141
142
  const NO_NODE = -1;
142
143
 
144
+ // A Map holds at most 2^24 entries, so each tableau node of a state finds its node in an
145
+ // open-addressing table of (state plus one, tableau node, node) triples.
146
+ interface NodeTable {
147
+ slots: Int32Array;
148
+ size: number;
149
+ shift: number;
150
+ }
151
+
152
+ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
153
+ const mask = table.slots.length / 3 - 1;
154
+ const hash = Math.imul(Math.imul(state, 0x9e3779b1) ^ tableauNode, 0x85ebca6b) >>> table.shift;
155
+ for (let index = hash; ; index = (index + 1) & mask) {
156
+ const slot = index * 3;
157
+ const stored = table.slots[slot];
158
+ if (stored === 0 || (stored === state + 1 && table.slots[slot + 1] === tableauNode)) {
159
+ return slot;
160
+ }
161
+ }
162
+ };
163
+
143
164
  const createNodes = (length: number) => new Int32Array(length).fill(NO_NODE);
144
165
 
145
166
  const UNWRITTEN = -1;
@@ -227,6 +248,7 @@ export const createLivenessChecker = (
227
248
  firstNodes: createPool(createNodes),
228
249
  lastNodes: createPool(createNodes),
229
250
  nextSiblings: [],
251
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
230
252
  isDone: [],
231
253
  errorNode: undefined,
232
254
  }));
@@ -322,12 +344,29 @@ export const createLivenessChecker = (
322
344
  model.infinitelyOftenActions.length === 0,
323
345
  );
324
346
 
325
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
326
- check.solution.tableau
327
- ? getStateNodes(check, state).find((node) => check.nodeTableaux[node] === tableauNode)
328
- : state;
347
+ const getNodeId = (check: Check, state: number, tableauNode: number) => {
348
+ if (!check.solution.tableau) return state;
349
+ const slots = check.nodeIds.slots;
350
+ const slot = getNodeSlot(check.nodeIds, state, tableauNode);
351
+ return slots[slot] === 0 ? undefined : slots[slot + 2];
352
+ };
329
353
  const recordNode = (check: Check, state: number, tableauNode: number) => {
330
354
  const node = pushNode(check, state, tableauNode);
355
+ const table = check.nodeIds;
356
+ if (++table.size * 2 > table.slots.length / 3) {
357
+ const old = table.slots;
358
+ table.slots = new Int32Array(old.length * 2);
359
+ table.shift--;
360
+ for (let slot = 0; slot < old.length; slot += 3) {
361
+ if (old[slot] !== 0) {
362
+ table.slots.set(
363
+ old.subarray(slot, slot + 3),
364
+ getNodeSlot(table, old[slot] - 1, old[slot + 1]),
365
+ );
366
+ }
367
+ }
368
+ }
369
+ table.slots.set([state + 1, tableauNode, node], getNodeSlot(table, state, tableauNode));
331
370
  const last = check.lastNodes.data[state] ?? NO_NODE;
332
371
  if (last === NO_NODE) writeToPool(check.firstNodes, state, [node]);
333
372
  else check.nextSiblings[last] = node;
package/src/successors.ts CHANGED
@@ -265,7 +265,7 @@ const NO_NAMES: ReadonlySet<string> = new Set();
265
265
 
266
266
  // The local names an expression reads from enclosing scopes, or undefined when it applies a local
267
267
  // operator, whose body may assign variables.
268
- const getReadLocals = (
268
+ export const getReadLocals = (
269
269
  expression: Expression,
270
270
  bound: ReadonlySet<string>,
271
271
  ): string[] | undefined => {