tla-ts 0.0.3-dev.3c70a97 → 0.0.3-dev.4b28a29

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.3c70a97",
3
+ "version": "0.0.3-dev.4b28a29",
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
@@ -13,6 +13,7 @@ import {
13
13
  getErrorExitCode,
14
14
  TlaConfigError,
15
15
  TlaEvaluationError,
16
+ TlaIncompleteStateError,
16
17
  TlaModuleError,
17
18
  UNEXPECTED_EXCEPTION,
18
19
  } from "./errors";
@@ -47,10 +48,17 @@ import {
47
48
  } from "./successors";
48
49
  import {
49
50
  getActionLabel,
51
+ getActionSignature,
50
52
  getNextActions,
51
53
  getSpecificationValue,
52
54
  type SpecAction,
53
55
  } from "./spec-description";
56
+ import {
57
+ createStateWriter,
58
+ type GraphState,
59
+ type StateDump,
60
+ type StateWriter,
61
+ } from "./state-graph";
54
62
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
55
63
  import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
56
64
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
@@ -60,6 +68,7 @@ import { createCounterExample } from "./tlc-ext";
60
68
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
61
69
  import {
62
70
  combineHash,
71
+ formatState,
63
72
  formatValue,
64
73
  getValueHash,
65
74
  isFunctionValue,
@@ -83,6 +92,8 @@ export interface CheckOptions {
83
92
  workers?: number;
84
93
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
85
94
  livenessCheck?: "default" | "final";
95
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
96
+ dump?: StateDump;
86
97
  }
87
98
 
88
99
  export type CheckStatus =
@@ -436,12 +447,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
436
447
  config.properties.forEach((name) => {
437
448
  const definition = getConfigPredicate("property", name, environment);
438
449
  if (!definition) return;
439
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
450
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
440
451
  const conjunct = item.expression;
441
452
  if (isConstantTrue(item, environment, "property")) return;
442
453
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
443
454
  properties.actionProperties.push({
444
- name,
455
+ name: item.name,
445
456
  box: conjunct.expression,
446
457
  action: conjunct.expression.action,
447
458
  subscript: conjunct.expression.subscript,
@@ -453,12 +464,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
453
464
  conjunct.kind === "Always" &&
454
465
  getLevel(conjunct.expression, item.scope, environment) <= 1
455
466
  ) {
456
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
467
+ // TLC names the invariant []P after P when P is an operator name.
468
+ const expression = conjunct.expression;
469
+ properties.invariants.push({
470
+ name: expression.kind === "Identifier" ? expression.name : item.name,
471
+ expression,
472
+ scope: item.scope,
473
+ });
457
474
  return;
458
475
  }
459
476
  const level = getLevel(conjunct, item.scope, environment);
460
477
  if (level < ACTION_LEVEL) {
461
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
478
+ properties.initialPredicates.push({
479
+ name: item.name,
480
+ expression: conjunct,
481
+ scope: item.scope,
482
+ });
462
483
  return;
463
484
  }
464
485
  if (level === ACTION_LEVEL) {
@@ -518,7 +539,9 @@ const getMembership = (
518
539
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
519
540
  named.flatMap((item) =>
520
541
  getConjuncts(item.expression, environment).map((expression) => {
521
- const variables = getReadVariables(expression, environment);
542
+ // A LET or an argument in the scope can read variables the expression doesn't name.
543
+ const variables =
544
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
522
545
  return {
523
546
  name: item.name,
524
547
  expression,
@@ -765,11 +788,13 @@ export const createSearch = (
765
788
  if (view !== undefined || isFingerprintedLikeTlc) {
766
789
  return BigInt64Array.from(states, getTlcStateFingerprint);
767
790
  }
768
- const indices = getTlcOrder();
769
- const getFingerprint = createTlcFingerprinter();
770
- return BigInt64Array.from(fingerprintStates, (state) =>
771
- getFingerprint(indices.map((index) => state[index])),
791
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
792
+ const fingerprint = createTlcFingerprinter(
793
+ getTlcOrder(),
794
+ new Int32Array(fingerprints.buffer),
772
795
  );
796
+ fingerprintStates.forEach(fingerprint);
797
+ return fingerprints;
773
798
  },
774
799
  getFingerprintState: (state) => {
775
800
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -875,6 +900,18 @@ export const createSearch = (
875
900
  const withNextStateExitCode = (error: unknown) =>
876
901
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
877
902
 
903
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
904
+ // module raised it as an EvalException.
905
+ const toNextStateError = (error: unknown) =>
906
+ error instanceof TlaEvaluationError &&
907
+ !(error instanceof TlaModuleError) &&
908
+ !(error instanceof TlaIncompleteStateError)
909
+ ? setExitCode(
910
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
911
+ getErrorExitCode(error),
912
+ )
913
+ : withNextStateExitCode(error);
914
+
878
915
  const withHeadline = (error: unknown, headline: string) =>
879
916
  error instanceof TlaEvaluationError
880
917
  ? setExitCode(
@@ -883,7 +920,15 @@ const withHeadline = (error: unknown, headline: string) =>
883
920
  )
884
921
  : error;
885
922
 
923
+ // TLC finishes the -dump file whether or not the search finds a violation.
886
924
  export const checkSequentially = (options: CheckOptions): CheckResult => {
925
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
926
+ const result = searchStates(options, stateWriter);
927
+ stateWriter?.close();
928
+ return result;
929
+ };
930
+
931
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
887
932
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
888
933
  const onPrint = options.onPrint ?? console.log;
889
934
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -1017,7 +1062,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1017
1062
  const parents: number[] = [];
1018
1063
  const actions: (string | undefined)[] = [];
1019
1064
  const depths: number[] = [];
1020
- const buckets = new Map<number, number | number[]>();
1065
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1066
+ // and its index plus one side by side, probed by the hash.
1067
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1021
1068
  const canonicalizeState = createCanonicalizer();
1022
1069
 
1023
1070
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1030,11 +1077,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1030
1077
  position: number,
1031
1078
  loopStart: number | undefined,
1032
1079
  ) => {
1033
- const state = steps[position].state;
1034
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
1035
1080
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1036
1081
  runtime.getLevel = () => position + 1;
1037
1082
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1083
+ return evaluateAlias(
1084
+ alias,
1085
+ steps[position].state,
1086
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1087
+ );
1088
+ };
1089
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
1038
1090
  try {
1039
1091
  const body = getConfigDefinition("alias", alias, environment).body;
1040
1092
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1172,19 +1224,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1172
1224
  }
1173
1225
  return true;
1174
1226
  };
1227
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1175
1228
  const findStateIndex = (hash: number, state: Value[]) => {
1176
- const bucket = buckets.get(hash);
1177
- if (bucket === undefined) return -1;
1178
- if (typeof bucket === "number") {
1179
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1229
+ const mask = seen.slots.length - 1;
1230
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1231
+ const entry = seen.slots[slot + 1];
1232
+ if (entry === 0) return -1;
1233
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1234
+ return entry - 1;
1235
+ }
1180
1236
  }
1181
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1237
+ };
1238
+ const insertSeen = (hash: number, entry: number) => {
1239
+ const mask = seen.slots.length - 1;
1240
+ let slot = getSlot(hash);
1241
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1242
+ seen.slots[slot] = hash;
1243
+ seen.slots[slot + 1] = entry;
1182
1244
  };
1183
1245
  const markSeen = (hash: number, index: number) => {
1184
- const bucket = buckets.get(hash);
1185
- if (bucket === undefined) buckets.set(hash, index);
1186
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1187
- else bucket.push(index);
1246
+ seen.size++;
1247
+ if (seen.size * 4 > seen.slots.length) {
1248
+ const slots = seen.slots;
1249
+ seen.slots = new Int32Array(slots.length * 2);
1250
+ seen.shift--;
1251
+ for (let slot = 0; slot < slots.length; slot += 2) {
1252
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1253
+ }
1254
+ }
1255
+ insertSeen(hash, index + 1);
1188
1256
  };
1189
1257
  const countDistinctState = (depth: number) => {
1190
1258
  runtime.distinctStates = states.length + 1;
@@ -1235,6 +1303,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1235
1303
  return current.isExpanding ? depths[current.index] + 1 : 0;
1236
1304
  };
1237
1305
 
1306
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1307
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1308
+ level,
1309
+ getLabel: () =>
1310
+ formatState(
1311
+ config.alias === undefined
1312
+ ? toRecord(state)
1313
+ : evaluateAlias(config.alias, state, undefined),
1314
+ ),
1315
+ getText: () => formatState(toRecord(state)),
1316
+ });
1317
+
1238
1318
  const visitInitialState = (state: Value[]) => {
1239
1319
  canonicalizeState(state);
1240
1320
  runtime.generatedStates++;
@@ -1251,6 +1331,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1251
1331
  countDistinctState(1);
1252
1332
  runtime.queueSize++;
1253
1333
  liveness?.addInitialState(states.length, state);
1334
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1254
1335
  }
1255
1336
  const violated = search.findViolatedInvariant(state);
1256
1337
  if (violated) {
@@ -1271,7 +1352,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1271
1352
  addState(state, fingerprintState, -1, undefined);
1272
1353
  return undefined;
1273
1354
  };
1274
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1355
+ const visitSuccessor = (
1356
+ index: number,
1357
+ successor: Successor,
1358
+ liveSuccessors: LiveSuccessor[],
1359
+ source: GraphState | undefined,
1360
+ action: SpecAction | undefined,
1361
+ ) => {
1275
1362
  const state = states[index];
1276
1363
  runtime.generatedStates++;
1277
1364
  current.candidate = successor.state;
@@ -1285,6 +1372,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1285
1372
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1286
1373
  if (isInModel) search.trackActionPossible(state, successor.state);
1287
1374
  const existing = isInModel ? found : -1;
1375
+ if (source && isInModel) {
1376
+ stateWriter?.writeSuccessor(
1377
+ source,
1378
+ getGraphState(successor.state, depths[index] + 1),
1379
+ existing !== -1,
1380
+ action && { name: action.name, signature: getActionSignature(action) },
1381
+ );
1382
+ }
1288
1383
  if (existing !== -1 && liveness) {
1289
1384
  const stored = states[existing];
1290
1385
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1356,23 +1451,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1356
1451
  }
1357
1452
  return createSuccess();
1358
1453
  }
1454
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1455
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1456
+ const isNamingEdges = Boolean(
1457
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1458
+ );
1459
+ const forEachActionSuccessor = (
1460
+ state: Value[],
1461
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1462
+ ) => {
1463
+ if (!isNamingEdges) {
1464
+ return forEachSuccessor(
1465
+ next,
1466
+ state,
1467
+ environment,
1468
+ (successor) => onSuccessor(successor, undefined),
1469
+ spec.scope,
1470
+ );
1471
+ }
1472
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1473
+ const progress = { isStopped: false };
1474
+ return nextActions.value.reduce((count, action) => {
1475
+ if (progress.isStopped) return count;
1476
+ return (
1477
+ count +
1478
+ forEachSuccessor(
1479
+ action.expression,
1480
+ state,
1481
+ environment,
1482
+ (successor) => {
1483
+ progress.isStopped = onSuccessor(successor, action);
1484
+ return progress.isStopped;
1485
+ },
1486
+ action.scope,
1487
+ )
1488
+ );
1489
+ }, 0);
1490
+ };
1359
1491
  const expandState = (index: number) => {
1360
1492
  const state = states[index];
1361
1493
  const liveSuccessors: LiveSuccessor[] = [];
1362
- const successorCount = forEachSuccessor(
1363
- next,
1364
- state,
1365
- environment,
1366
- (successor) => {
1367
- try {
1368
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1369
- } catch (error) {
1370
- outcome.result = toFailure(error, getTrace(index, successor));
1371
- }
1372
- return outcome.result !== undefined;
1373
- },
1374
- spec.scope,
1375
- );
1494
+ const source = stateWriter && getGraphState(state, depths[index]);
1495
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1496
+ try {
1497
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1498
+ } catch (error) {
1499
+ outcome.result = toFailure(error, getTrace(index, successor));
1500
+ }
1501
+ return outcome.result !== undefined;
1502
+ });
1376
1503
  current.isExpanding = false;
1377
1504
  if (outcome.result) return outcome.result;
1378
1505
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1440,7 +1567,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1440
1567
  try {
1441
1568
  outcome.result = expandState(index);
1442
1569
  } catch (error) {
1443
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1570
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1444
1571
  }
1445
1572
  if (outcome.result) return outcome.result;
1446
1573
  outDegrees[getOutDegreeBucket()]++;
@@ -2,6 +2,8 @@ export interface OptionSpec {
2
2
  flag: string;
3
3
  isRequired?: boolean;
4
4
  isRepeatable?: boolean;
5
+ // How many of the arguments after the flag the option takes, when that depends on them.
6
+ getArity?: (rest: string[]) => number;
5
7
  }
6
8
 
7
9
  export interface ParsedOption {
@@ -29,27 +31,31 @@ export const defineCommand = (usage: string, specs: OptionSpec[]) => {
29
31
  const arities = new Map(
30
32
  specs.map((spec) => {
31
33
  const [name, ...values] = spec.flag.split(" ");
32
- return [name, values.length];
34
+ return [name, spec.getArity ?? (() => values.length)];
33
35
  }),
34
36
  );
35
37
  const parse = (args: string[]): ParsedArgs => {
36
38
  const options: ParsedOption[] = [];
37
39
  const positionals: string[] = [];
38
40
  const unknown: string[] = [];
41
+ const incomplete: ParsedOption[] = [];
39
42
  for (let index = 0; index < args.length; index++) {
40
- const arity = arities.get(args[index]);
41
- if (arity === undefined) {
43
+ const getArity = arities.get(args[index]);
44
+ if (getArity === undefined) {
42
45
  (args[index].startsWith("-") ? unknown : positionals).push(args[index]);
43
46
  continue;
44
47
  }
45
- options.push({ name: args[index], values: args.slice(index + 1, index + 1 + arity) });
48
+ const arity = getArity(args.slice(index + 1));
49
+ const option = { name: args[index], values: args.slice(index + 1, index + 1 + arity) };
50
+ options.push(option);
51
+ if (option.values.length < arity) incomplete.push(option);
46
52
  index += arity;
47
53
  }
48
54
  return {
49
55
  options,
50
56
  positionals,
51
57
  unknown,
52
- incomplete: options.find((option) => option.values.length < (arities.get(option.name) ?? 0)),
58
+ incomplete: incomplete[0],
53
59
  has: (name) => options.some((option) => option.name === name),
54
60
  get: (name) => options.findLast((option) => option.name === name)?.values,
55
61
  };
@@ -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/errors.ts CHANGED
@@ -55,6 +55,15 @@ export class TlaModuleError extends TlaEvaluationError {
55
55
  }
56
56
  }
57
57
 
58
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
59
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
60
+ export class TlaIncompleteStateError extends TlaEvaluationError {
61
+ constructor(message: string) {
62
+ super(message);
63
+ this.name = "TlaEvaluationError";
64
+ }
65
+ }
66
+
58
67
  export interface TlapmReport {
59
68
  failure?: string;
60
69
  exception?: string;
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
  },