tla-ts 0.0.3-dev.b1578d0 → 0.0.3-dev.bffbba3

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.3-dev.b1578d0",
3
+ "version": "0.0.3-dev.bffbba3",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -446,12 +446,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
446
446
  config.properties.forEach((name) => {
447
447
  const definition = getConfigPredicate("property", name, environment);
448
448
  if (!definition) return;
449
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
449
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
450
450
  const conjunct = item.expression;
451
451
  if (isConstantTrue(item, environment, "property")) return;
452
452
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
453
453
  properties.actionProperties.push({
454
- name,
454
+ name: item.name,
455
455
  box: conjunct.expression,
456
456
  action: conjunct.expression.action,
457
457
  subscript: conjunct.expression.subscript,
@@ -463,12 +463,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
463
463
  conjunct.kind === "Always" &&
464
464
  getLevel(conjunct.expression, item.scope, environment) <= 1
465
465
  ) {
466
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
466
+ // TLC names the invariant []P after P when P is an operator name.
467
+ const expression = conjunct.expression;
468
+ properties.invariants.push({
469
+ name: expression.kind === "Identifier" ? expression.name : item.name,
470
+ expression,
471
+ scope: item.scope,
472
+ });
467
473
  return;
468
474
  }
469
475
  const level = getLevel(conjunct, item.scope, environment);
470
476
  if (level < ACTION_LEVEL) {
471
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
477
+ properties.initialPredicates.push({
478
+ name: item.name,
479
+ expression: conjunct,
480
+ scope: item.scope,
481
+ });
472
482
  return;
473
483
  }
474
484
  if (level === ACTION_LEVEL) {
@@ -528,7 +538,9 @@ const getMembership = (
528
538
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
529
539
  named.flatMap((item) =>
530
540
  getConjuncts(item.expression, environment).map((expression) => {
531
- const variables = getReadVariables(expression, environment);
541
+ // A LET or an argument in the scope can read variables the expression doesn't name.
542
+ const variables =
543
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
532
544
  return {
533
545
  name: item.name,
534
546
  expression,
@@ -1035,7 +1047,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1035
1047
  const parents: number[] = [];
1036
1048
  const actions: (string | undefined)[] = [];
1037
1049
  const depths: number[] = [];
1038
- const buckets = new Map<number, number | number[]>();
1050
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1051
+ // and its index plus one side by side, probed by the hash.
1052
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1039
1053
  const canonicalizeState = createCanonicalizer();
1040
1054
 
1041
1055
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1195,19 +1209,35 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1195
1209
  }
1196
1210
  return true;
1197
1211
  };
1212
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1198
1213
  const findStateIndex = (hash: number, state: Value[]) => {
1199
- const bucket = buckets.get(hash);
1200
- if (bucket === undefined) return -1;
1201
- if (typeof bucket === "number") {
1202
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1214
+ const mask = seen.slots.length - 1;
1215
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1216
+ const entry = seen.slots[slot + 1];
1217
+ if (entry === 0) return -1;
1218
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1219
+ return entry - 1;
1220
+ }
1203
1221
  }
1204
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1222
+ };
1223
+ const insertSeen = (hash: number, entry: number) => {
1224
+ const mask = seen.slots.length - 1;
1225
+ let slot = getSlot(hash);
1226
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1227
+ seen.slots[slot] = hash;
1228
+ seen.slots[slot + 1] = entry;
1205
1229
  };
1206
1230
  const markSeen = (hash: number, index: number) => {
1207
- const bucket = buckets.get(hash);
1208
- if (bucket === undefined) buckets.set(hash, index);
1209
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1210
- else bucket.push(index);
1231
+ seen.size++;
1232
+ if (seen.size * 4 > seen.slots.length) {
1233
+ const slots = seen.slots;
1234
+ seen.slots = new Int32Array(slots.length * 2);
1235
+ seen.shift--;
1236
+ for (let slot = 0; slot < slots.length; slot += 2) {
1237
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1238
+ }
1239
+ }
1240
+ insertSeen(hash, index + 1);
1211
1241
  };
1212
1242
  const countDistinctState = (depth: number) => {
1213
1243
  runtime.distinctStates = states.length + 1;
@@ -17,7 +17,8 @@ import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
17
  import {
18
18
  createBigNumberError,
19
19
  createRealNumberError,
20
- isConstantLevel,
20
+ evaluate,
21
+ getDefinition,
21
22
  isTlcInteger,
22
23
  type Builtin,
23
24
  type Environment,
@@ -44,7 +45,7 @@ import {
44
45
  import { createRuntime } from "./runtime";
45
46
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
46
47
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
48
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
48
49
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
49
50
  import {
50
51
  checkInteger,
@@ -212,6 +213,8 @@ export const createEnvironment = (
212
213
  const root = parseModule(options.source);
213
214
  const definitions = new Map<string, Definition>();
214
215
  const parameterized = new Map<string, boolean>();
216
+ // The definition each instance copy came from, and the instance parameters the copy adds.
217
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
218
  const builtins = new Map<string, Builtin>(
216
219
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
220
  );
@@ -379,10 +382,11 @@ export const createEnvironment = (
379
382
  variables: new Set(linked.variables),
380
383
  getDefinition: (key) => definitions.get(key),
381
384
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
385
+ addDefinition: (source, name, create) => {
383
386
  const key = createName(`${name}@${module.name}`);
384
387
  definitions.set(key, create(key));
385
388
  parameterized.set(key, !isParameterFree);
389
+ copySources.set(key, { source, prefix: instance.params.length });
386
390
  return key;
387
391
  },
388
392
  createName,
@@ -544,7 +548,7 @@ export const createEnvironment = (
544
548
  variables: new Set(linked.variables),
545
549
  getDefinition: (key) => definitions.get(key),
546
550
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
551
+ addDefinition: (_source, name, create) => {
548
552
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
553
  const definition = create(key);
550
554
  copies.push(
@@ -872,6 +876,38 @@ export const createEnvironment = (
872
876
  );
873
877
  }
874
878
  });
879
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
880
+ // the module shares.
881
+ const scopedKeys = new Set(
882
+ [...config.constants, ...config.substitutions]
883
+ .filter((item) => item.module !== undefined)
884
+ .flatMap(getScopedKeys),
885
+ );
886
+ const getOverride = (
887
+ key: string,
888
+ prefix: number,
889
+ ): { key: string; prefix: number } | undefined => {
890
+ if (scopedKeys.has(key)) return { key, prefix };
891
+ const copy = copySources.get(key);
892
+ return copy && getOverride(copy.source, prefix + copy.prefix);
893
+ };
894
+ copySources.forEach((copy, key) => {
895
+ const override = getOverride(copy.source, copy.prefix);
896
+ const definition = definitions.get(key);
897
+ if (!override || !definition) return;
898
+ const params = definition.kind === "Operator" ? definition.params : [];
899
+ const alias = createLocalAlias(
900
+ key,
901
+ override.key,
902
+ params,
903
+ params.slice(override.prefix),
904
+ definition.location,
905
+ );
906
+ definitions.set(key, alias);
907
+ linkedRoot.visible.forEach((symbol, name) => {
908
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
909
+ });
910
+ });
875
911
  declaredConstants.forEach((name) => {
876
912
  if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
877
913
  throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
@@ -907,18 +943,41 @@ export const createEnvironment = (
907
943
  getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
944
  };
909
945
  });
946
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
947
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
948
+ // a minimum level as state-level, so the analyzer takes them for variables.
949
+ const analyzer = createLevelAnalyzer({
950
+ constants: new Set(constants.keys()),
951
+ variables: new Set([
952
+ ...variables,
953
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
954
+ ]),
955
+ getDefinition: (name) => getDefinition(name, environment),
956
+ });
957
+ const isEvaluable = (body: Expression) => {
958
+ try {
959
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
960
+ return true;
961
+ } catch (error) {
962
+ if (error instanceof TlaEvaluationError) return false;
963
+ throw error;
964
+ }
965
+ };
910
966
  substitutions.forEach((target, name) => {
911
967
  const definition = definitions.get(target);
912
968
  if (
913
969
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
970
+ definition?.kind === "Operator" &&
971
+ definition.params.length === 0 &&
972
+ analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
973
+ !isEvaluable(definition.body)
916
974
  ) {
917
975
  throw new TlaConfigError(
918
976
  `The configuration file substitutes constant ${name} with non-constant ${target}`,
919
977
  );
920
978
  }
921
979
  });
980
+ runtime.isStarted = true;
922
981
  return {
923
982
  environment,
924
983
  assumptions,
package/src/evaluate.ts CHANGED
@@ -36,11 +36,11 @@ import {
36
36
  getIntervalElements,
37
37
  getSequenceElements,
38
38
  getValueHash,
39
- isEnumerable,
40
39
  isFunctionValue,
41
40
  isOverriddenSet,
42
41
  isSameValue,
43
42
  markLambdaFunction,
43
+ isReducible,
44
44
  isSetValue,
45
45
  MAXIMUM_INTEGER,
46
46
  MINIMUM_INTEGER,
@@ -1027,7 +1027,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1027
1027
 
1028
1028
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1029
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1030
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1031
1031
  const cached = entryEvaluators.get(expression);
1032
1032
  if (cached) return cached;
1033
1033
  const evaluator =
@@ -1420,7 +1420,13 @@ const compileFunctionConstruction = (
1420
1420
  const set = getEvaluator(bound.set, environment);
1421
1421
  return (context) => {
1422
1422
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1423
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1423
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1424
+ // otherwise.
1425
+ const domains =
1426
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1427
+ ? domain.factors
1428
+ : [domain];
1429
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1424
1430
  const functionValue = createLazyFunction(
1425
1431
  domain,
1426
1432
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1514,10 +1520,7 @@ const compileSetComprehension = (
1514
1520
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1515
1521
  "a set filter predicate",
1516
1522
  );
1517
- const isReducible =
1518
- typeof base === "object" &&
1519
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1520
- if (!isReducible) {
1523
+ if (!isReducible(base)) {
1521
1524
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1522
1525
  throw new TlaEvaluationError(
1523
1526
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
package/src/instances.ts CHANGED
@@ -219,7 +219,7 @@ interface Instantiation {
219
219
  variables: Set<string>;
220
220
  getDefinition: (key: string) => Definition | undefined;
221
221
  isParameterized: (key: string) => boolean;
222
- addDefinition: (name: string, create: (key: string) => Definition) => string;
222
+ addDefinition: (source: string, name: string, create: (key: string) => Definition) => string;
223
223
  createName: (name: string) => string;
224
224
  }
225
225
 
@@ -640,7 +640,7 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
640
640
  const instantiation = rewrite.instantiation;
641
641
  const definition = instantiation.getDefinition(key);
642
642
  if (!definition) return key;
643
- return instantiation.addDefinition(definition.name, (copyKey) => {
643
+ return instantiation.addDefinition(key, definition.name, (copyKey) => {
644
644
  rewrite.copies.set(key, copyKey);
645
645
  const rename = createRenamer(rewrite);
646
646
  const mapped = renameParams(
@@ -679,7 +679,7 @@ export const createInstantiation = (instantiation: Instantiation) => {
679
679
  if (copy !== undefined) return copy;
680
680
  const definition = instantiation.getDefinition(key);
681
681
  if (!definition) return key;
682
- return instantiation.addDefinition(definition.name, () =>
682
+ return instantiation.addDefinition(key, definition.name, () =>
683
683
  withInstanceParams(definition, instantiation.params, definition.location),
684
684
  );
685
685
  },
package/src/live-check.ts CHANGED
@@ -2,6 +2,7 @@ import { TlaEvaluationError } from "./errors";
2
2
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
3
  import {
4
4
  evaluateLive,
5
+ TAUTOLOGY_MESSAGE,
5
6
  evaluateOnLasso,
6
7
  toLiveExpression,
7
8
  type ScopedExpression,
@@ -11,6 +12,7 @@ import {
11
12
  createJunction,
12
13
  createUnary,
13
14
  getSolutions,
15
+ getTermKey,
14
16
  isFulfilling,
15
17
  type LiveExpression,
16
18
  type Solution,
@@ -58,26 +60,6 @@ interface Check {
58
60
  errorNode: number | undefined;
59
61
  }
60
62
 
61
- const liveKeys = new WeakMap<LiveExpression, string>();
62
-
63
- const atomCount = { value: 0 };
64
-
65
- // Each solution builds its own junctions over shared atoms, so equal checks get equal keys.
66
- const getLiveKey = (expression: LiveExpression): string => {
67
- const cached = liveKeys.get(expression);
68
- if (cached !== undefined) return cached;
69
- const key =
70
- expression.kind === "Boolean"
71
- ? String(expression.value)
72
- : "body" in expression
73
- ? `${expression.kind}(${getLiveKey(expression.body)})`
74
- : "operands" in expression
75
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
76
- : `${expression.kind}#${atomCount.value++}`;
77
- liveKeys.set(expression, key);
78
- return key;
79
- };
80
-
81
63
  const isSameState = (left: Value[], right: Value[]) =>
82
64
  left.every((value, position) => isSameValue(value, right[position]));
83
65
 
@@ -121,13 +103,13 @@ export const createLivenessChecker = (
121
103
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
122
104
  const solutions = getSolutions(formula);
123
105
  if (solutions.length === 0) {
124
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
106
+ throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
125
107
  }
126
108
  const actionIds = new Map<string, number>();
127
109
  const checks = solutions.map((solution): Check => ({
128
110
  solution,
129
111
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
130
- const key = getLiveKey(predicate);
112
+ const key = getTermKey(predicate);
131
113
  const id = actionIds.get(key) ?? actionIds.size;
132
114
  actionIds.set(key, id);
133
115
  return id;
package/src/liveness.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
2
  import { TlaConfigError, TlaEvaluationError } from "./errors";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  describeLocation,
6
+ describeRange,
5
7
  bindDefinitions,
6
8
  bindOperatorArguments,
7
9
  evaluate,
@@ -36,6 +38,10 @@ export interface ScopedExpression {
36
38
  scope: Scope | undefined;
37
39
  }
38
40
 
41
+ export interface NamedExpression extends ScopedExpression {
42
+ name: string;
43
+ }
44
+
39
45
  export interface TemporalProperty extends ScopedExpression {
40
46
  name: string;
41
47
  }
@@ -144,21 +150,27 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
144
150
  return level;
145
151
  };
146
152
 
153
+ export const TAUTOLOGY_MESSAGE = "Temporal formula is a tautology (its negation is unsatisfiable).";
154
+
155
+ // TLC names each part of a property after the operator it expands, or after the location of the
156
+ // conjunct or quantifier body it splits off.
147
157
  export const expandTemporal = (
148
158
  expression: Expression,
149
159
  scope: Scope | undefined,
150
160
  environment: Environment,
151
- isUnrollingForall: boolean,
161
+ isProperty: boolean,
162
+ name = "",
152
163
  expanding = new Set<Definition>(),
153
- ): ScopedExpression[] => {
164
+ ): NamedExpression[] => {
154
165
  const expand = (
155
166
  child: Expression,
156
167
  childScope: Scope | undefined,
168
+ childName = name,
157
169
  childExpanding = expanding,
158
- ): ScopedExpression[] =>
159
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
170
+ ): NamedExpression[] =>
171
+ expandTemporal(child, childScope, environment, isProperty, childName, childExpanding);
160
172
  if (expression.kind === "And") {
161
- return expression.operands.flatMap((operand) => expand(operand, scope));
173
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
162
174
  }
163
175
  if (expression.kind === "Label") return expand(expression.body, scope);
164
176
  if (expression.kind === "Let") {
@@ -181,33 +193,58 @@ export const expandTemporal = (
181
193
  if (expanding.has(definition)) {
182
194
  throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
183
195
  }
184
- return expand(definition.body, undefined, new Set([...expanding, definition]));
196
+ return expand(
197
+ definition.body,
198
+ undefined,
199
+ expression.name,
200
+ new Set([...expanding, definition]),
201
+ );
185
202
  }
186
203
  }
187
204
  const context = getConstantContext(environment, scope);
188
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
205
+ // A property expands every operator it applies and unrolls every \A over constant sets, but a
206
+ // specification only expands the temporal ones.
207
+ const isExpanded = (child: Expression) =>
208
+ isProperty || getLevel(child, scope, environment) === TEMPORAL_LEVEL;
209
+ if (expression.kind === "Apply" && isExpanded(expression)) {
189
210
  const operator = resolveApplyOperator(expression, context);
190
211
  const definition = isLocallyResolved(expression)
191
212
  ? undefined
192
213
  : getDefinition(expression.operator, environment);
193
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
194
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
214
+ const isExpandable =
215
+ operator?.kind === "Closure" &&
216
+ operator.params.length === expression.args.length &&
217
+ !definition?.isRecursive;
218
+ if (isExpandable) {
219
+ return expand(
220
+ operator.body,
221
+ bindOperatorArguments(operator, expression.args, context),
222
+ expression.operator,
223
+ );
195
224
  }
196
225
  }
197
226
  const isUnrolled =
198
- isUnrollingForall &&
227
+ isProperty &&
199
228
  expression.kind === "Forall" &&
200
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
201
229
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
202
230
  if (isUnrolled) {
203
- const expanded: ScopedExpression[] = [];
231
+ const expanded: NamedExpression[] = [];
232
+ const bindings = { count: 0 };
204
233
  forEachBinding(expression.bounds, context, (boundScope) => {
205
- expanded.push(...expand(expression.body, boundScope));
234
+ bindings.count++;
235
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
206
236
  return false;
207
237
  });
238
+ // TLC rejects a property that quantifies over no elements before it checks anything.
239
+ if (bindings.count === 0) {
240
+ throw setExitCode(
241
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
242
+ EXIT_STATUS.livenessEvaluationFailure,
243
+ );
244
+ }
208
245
  return expanded;
209
246
  }
210
- return [{ expression, scope }];
247
+ return [{ expression, scope, name }];
211
248
  };
212
249
 
213
250
  const bindLetDefinitions = (
package/src/runtime.ts CHANGED
@@ -24,6 +24,7 @@ export interface CheckerRuntime {
24
24
  properties: Map<string, string>;
25
25
  possibleCounts: Map<string, number>;
26
26
  isStopped: boolean;
27
+ isStarted: boolean;
27
28
  checkDeadlock: boolean;
28
29
  startedAt: number;
29
30
  }
@@ -75,6 +76,7 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
75
76
  properties: new Map(),
76
77
  possibleCounts: new Map(),
77
78
  isStopped: false,
79
+ isStarted: false,
78
80
  checkDeadlock,
79
81
  startedAt: Date.now(),
80
82
  };
@@ -40,6 +40,7 @@ import {
40
40
  isEnumerable,
41
41
  isFiniteSet,
42
42
  isFunctionValue,
43
+ isReducible,
43
44
  isSetValue,
44
45
  toFiniteSet,
45
46
  unionSorted,
@@ -47,7 +48,7 @@ import {
47
48
  createEnumeratedSet,
48
49
  EMPTY_SET,
49
50
  isEnumeratedSet,
50
- type IntervalValue,
51
+ type ReducibleSet,
51
52
  type MixedSetValue,
52
53
  type SetOperationValue,
53
54
  type SetValue,
@@ -75,12 +76,6 @@ const unionInTree = (sets: SetValue[], start: number, end: number): SetValue =>
75
76
 
76
77
  const SET_OPERATORS: SetOperationValue["operator"][] = ["\\cup", "\\cap", "\\"];
77
78
 
78
- type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
79
-
80
- const isReducible = (value: Value): value is ReducibleSet =>
81
- typeof value === "object" &&
82
- (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
83
-
84
79
  const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
85
80
 
86
81
  const getReducibleElements = (set: ReducibleSet) =>
package/src/successors.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  type Bound,
5
5
  type Definition,
6
6
  type Expression,
7
+ type QuantifierExpression,
7
8
  } from "./ast";
8
9
  import { getReadVariables } from "./dependencies";
9
10
  import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
@@ -17,6 +18,7 @@ import {
17
18
  bindValue,
18
19
  compileArgumentScope,
19
20
  evaluate,
21
+ getEntryEvaluator,
20
22
  expectBoolean,
21
23
  forEachBinding,
22
24
  getBoundsDomain,
@@ -28,6 +30,7 @@ import {
28
30
  resolveGlobalOperator,
29
31
  type Context,
30
32
  type Environment,
33
+ type Evaluator,
31
34
  type Scope,
32
35
  type State,
33
36
  } from "./evaluate";
@@ -86,8 +89,7 @@ const assign = (partial: State, index: number, value: Value) => {
86
89
  return copy;
87
90
  };
88
91
 
89
- const holds = (expression: Expression, context: Context) => {
90
- const value = evaluate(expression, context);
92
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
91
93
  if (typeof value === "boolean") return value;
92
94
  try {
93
95
  return expectBoolean(value, `the action at ${describeLocation(expression)}`);
@@ -292,12 +294,34 @@ const toConjunct = (
292
294
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
293
295
  };
294
296
 
297
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
298
+ // binding alike, so they can run once for each element of the outermost bound.
299
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
300
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
301
+ const names = expression.bounds.flatMap((bound) =>
302
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
303
+ );
304
+ if (names.length !== expression.bounds.length) return undefined;
305
+ const innerNames = new Set(names.slice(0, -1));
306
+ const operands = expression.body.operands;
307
+ const index = operands.findIndex((operand) => {
308
+ if (getReadVariables(operand, environment) === undefined) return true;
309
+ if (hasBranches(operand, environment, new Set())) return true;
310
+ const readLocals = getReadLocals(operand, NO_NAMES);
311
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
312
+ });
313
+ const count = index === -1 ? operands.length : index;
314
+ if (count === 0) return undefined;
315
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
316
+ };
317
+
295
318
  const compileConjunction = (
296
319
  operands: Expression[],
297
320
  environment: Environment,
298
321
  isInit: boolean,
299
322
  ): Runner => {
300
323
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
324
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
301
325
  const runFrom = (
302
326
  start: number,
303
327
  run: Run,
@@ -320,12 +344,17 @@ const compileConjunction = (
320
344
  const conjunct = conjuncts[index];
321
345
  if (conjunct.kind === "Guard") {
322
346
  context ??= getContext(run, scope, current);
323
- if (!holds(conjunct.expression, context)) return;
347
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
348
+ conjunct.expression,
349
+ environment,
350
+ ));
351
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
324
352
  continue;
325
353
  }
326
354
  if (conjunct.kind === "Assign") {
327
355
  context ??= getContext(run, scope, current);
328
- const value = evaluate(conjunct.value, context);
356
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
357
+ const value = evaluator(context);
329
358
  const assigned = current[conjunct.index];
330
359
  if (assigned === undefined) {
331
360
  current = assign(current, conjunct.index, value);
@@ -734,6 +763,33 @@ const compileAction = (
734
763
  }
735
764
  };
736
765
  }
766
+ const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
767
+ if (hoisted) {
768
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
769
+ return (run, scope, partial, action, isFixed, onComplete) => {
770
+ const context = getContext(run, scope, partial);
771
+ const sets = expression.bounds.map((innerBound) =>
772
+ getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
773
+ );
774
+ if (sets.some((elements) => elements.length === 0)) return;
775
+ const visit = (index: number, boundScope: Scope | undefined): void => {
776
+ if (index < 0) {
777
+ rest(run, boundScope, partial, action, isFixed, onComplete);
778
+ return;
779
+ }
780
+ for (const element of sets[index]) {
781
+ if (run.isStopped) return;
782
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
783
+ if (index === sets.length - 1) {
784
+ const guardContext = getContext(run, elementScope, partial);
785
+ if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
786
+ }
787
+ visit(index - 1, elementScope);
788
+ }
789
+ };
790
+ visit(sets.length - 1, scope);
791
+ };
792
+ }
737
793
  return (run, scope, partial, action, isFixed, onComplete) => {
738
794
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
739
795
  body(run, boundScope, partial, action, isFixed, onComplete);