tla-ts 0.0.3-dev.3c70a97 → 0.0.3-dev.45d0f50

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.45d0f50",
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,12 +48,19 @@ 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
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
63
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
56
64
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
57
65
  import { createCanonicalizer } from "./canonical";
58
66
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -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 =
@@ -266,8 +277,11 @@ const getInvariants = (names: string[], environment: Environment) => {
266
277
  levels.params.size === 0
267
278
  ? ""
268
279
  : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
269
- throw new TlaConfigError(
270
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
280
+ throw setExitCode(
281
+ new TlaConfigError(
282
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
283
+ ),
284
+ EXIT_STATUS.safetyEvaluationFailure,
271
285
  );
272
286
  }
273
287
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -365,8 +379,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
365
379
  conjunct.kind === "Always" &&
366
380
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
367
381
  ) {
368
- throw new TlaConfigError(
369
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
382
+ throw setExitCode(
383
+ new TlaConfigError(
384
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
385
+ ),
386
+ EXIT_STATUS.error,
370
387
  );
371
388
  }
372
389
  const level = getLevel(conjunct, item.scope, environment);
@@ -436,12 +453,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
436
453
  config.properties.forEach((name) => {
437
454
  const definition = getConfigPredicate("property", name, environment);
438
455
  if (!definition) return;
439
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
456
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
440
457
  const conjunct = item.expression;
441
458
  if (isConstantTrue(item, environment, "property")) return;
442
459
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
443
460
  properties.actionProperties.push({
444
- name,
461
+ name: item.name,
445
462
  box: conjunct.expression,
446
463
  action: conjunct.expression.action,
447
464
  subscript: conjunct.expression.subscript,
@@ -453,12 +470,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
453
470
  conjunct.kind === "Always" &&
454
471
  getLevel(conjunct.expression, item.scope, environment) <= 1
455
472
  ) {
456
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
473
+ // TLC names the invariant []P after P when P is an operator name.
474
+ const expression = conjunct.expression;
475
+ properties.invariants.push({
476
+ name: expression.kind === "Identifier" ? expression.name : item.name,
477
+ expression,
478
+ scope: item.scope,
479
+ });
457
480
  return;
458
481
  }
459
482
  const level = getLevel(conjunct, item.scope, environment);
460
483
  if (level < ACTION_LEVEL) {
461
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
484
+ properties.initialPredicates.push({
485
+ name: item.name,
486
+ expression: conjunct,
487
+ scope: item.scope,
488
+ });
462
489
  return;
463
490
  }
464
491
  if (level === ACTION_LEVEL) {
@@ -518,7 +545,9 @@ const getMembership = (
518
545
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
519
546
  named.flatMap((item) =>
520
547
  getConjuncts(item.expression, environment).map((expression) => {
521
- const variables = getReadVariables(expression, environment);
548
+ // A LET or an argument in the scope can read variables the expression doesn't name.
549
+ const variables =
550
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
522
551
  return {
523
552
  name: item.name,
524
553
  expression,
@@ -765,11 +794,13 @@ export const createSearch = (
765
794
  if (view !== undefined || isFingerprintedLikeTlc) {
766
795
  return BigInt64Array.from(states, getTlcStateFingerprint);
767
796
  }
768
- const indices = getTlcOrder();
769
- const getFingerprint = createTlcFingerprinter();
770
- return BigInt64Array.from(fingerprintStates, (state) =>
771
- getFingerprint(indices.map((index) => state[index])),
797
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
798
+ const fingerprint = createTlcFingerprinter(
799
+ getTlcOrder(),
800
+ new Int32Array(fingerprints.buffer),
772
801
  );
802
+ fingerprintStates.forEach(fingerprint);
803
+ return fingerprints;
773
804
  },
774
805
  getFingerprintState: (state) => {
775
806
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -875,6 +906,18 @@ export const createSearch = (
875
906
  const withNextStateExitCode = (error: unknown) =>
876
907
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
877
908
 
909
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
910
+ // module raised it as an EvalException.
911
+ const toNextStateError = (error: unknown) =>
912
+ error instanceof TlaEvaluationError &&
913
+ !(error instanceof TlaModuleError) &&
914
+ !(error instanceof TlaIncompleteStateError)
915
+ ? setExitCode(
916
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
917
+ getErrorExitCode(error),
918
+ )
919
+ : withNextStateExitCode(error);
920
+
878
921
  const withHeadline = (error: unknown, headline: string) =>
879
922
  error instanceof TlaEvaluationError
880
923
  ? setExitCode(
@@ -883,7 +926,15 @@ const withHeadline = (error: unknown, headline: string) =>
883
926
  )
884
927
  : error;
885
928
 
929
+ // TLC finishes the -dump file whether or not the search finds a violation.
886
930
  export const checkSequentially = (options: CheckOptions): CheckResult => {
931
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
932
+ const result = searchStates(options, stateWriter);
933
+ stateWriter?.close();
934
+ return result;
935
+ };
936
+
937
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
887
938
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
888
939
  const onPrint = options.onPrint ?? console.log;
889
940
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -953,7 +1004,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
953
1004
  });
954
1005
 
955
1006
  const search = createSearch(config, environment, () =>
956
- getTlcVariableOrder(options.source, options.loadModule),
1007
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
957
1008
  );
958
1009
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
959
1010
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1017,7 +1068,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1017
1068
  const parents: number[] = [];
1018
1069
  const actions: (string | undefined)[] = [];
1019
1070
  const depths: number[] = [];
1020
- const buckets = new Map<number, number | number[]>();
1071
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1072
+ // and its index plus one side by side, probed by the hash.
1073
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1021
1074
  const canonicalizeState = createCanonicalizer();
1022
1075
 
1023
1076
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1030,11 +1083,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1030
1083
  position: number,
1031
1084
  loopStart: number | undefined,
1032
1085
  ) => {
1033
- const state = steps[position].state;
1034
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
1035
1086
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1036
1087
  runtime.getLevel = () => position + 1;
1037
1088
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1089
+ return evaluateAlias(
1090
+ alias,
1091
+ steps[position].state,
1092
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1093
+ );
1094
+ };
1095
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
1038
1096
  try {
1039
1097
  const body = getConfigDefinition("alias", alias, environment).body;
1040
1098
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1172,19 +1230,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1172
1230
  }
1173
1231
  return true;
1174
1232
  };
1233
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1175
1234
  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;
1235
+ const mask = seen.slots.length - 1;
1236
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1237
+ const entry = seen.slots[slot + 1];
1238
+ if (entry === 0) return -1;
1239
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1240
+ return entry - 1;
1241
+ }
1180
1242
  }
1181
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1243
+ };
1244
+ const insertSeen = (hash: number, entry: number) => {
1245
+ const mask = seen.slots.length - 1;
1246
+ let slot = getSlot(hash);
1247
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1248
+ seen.slots[slot] = hash;
1249
+ seen.slots[slot + 1] = entry;
1182
1250
  };
1183
1251
  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);
1252
+ seen.size++;
1253
+ if (seen.size * 4 > seen.slots.length) {
1254
+ const slots = seen.slots;
1255
+ seen.slots = new Int32Array(slots.length * 2);
1256
+ seen.shift--;
1257
+ for (let slot = 0; slot < slots.length; slot += 2) {
1258
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1259
+ }
1260
+ }
1261
+ insertSeen(hash, index + 1);
1188
1262
  };
1189
1263
  const countDistinctState = (depth: number) => {
1190
1264
  runtime.distinctStates = states.length + 1;
@@ -1235,6 +1309,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1235
1309
  return current.isExpanding ? depths[current.index] + 1 : 0;
1236
1310
  };
1237
1311
 
1312
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1313
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1314
+ level,
1315
+ getLabel: () =>
1316
+ formatState(
1317
+ config.alias === undefined
1318
+ ? toRecord(state)
1319
+ : evaluateAlias(config.alias, state, undefined),
1320
+ ),
1321
+ getText: () => formatState(toRecord(state)),
1322
+ });
1323
+
1238
1324
  const visitInitialState = (state: Value[]) => {
1239
1325
  canonicalizeState(state);
1240
1326
  runtime.generatedStates++;
@@ -1251,6 +1337,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1251
1337
  countDistinctState(1);
1252
1338
  runtime.queueSize++;
1253
1339
  liveness?.addInitialState(states.length, state);
1340
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1254
1341
  }
1255
1342
  const violated = search.findViolatedInvariant(state);
1256
1343
  if (violated) {
@@ -1271,7 +1358,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1271
1358
  addState(state, fingerprintState, -1, undefined);
1272
1359
  return undefined;
1273
1360
  };
1274
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1361
+ const visitSuccessor = (
1362
+ index: number,
1363
+ successor: Successor,
1364
+ liveSuccessors: LiveSuccessor[],
1365
+ source: GraphState | undefined,
1366
+ action: SpecAction | undefined,
1367
+ ) => {
1275
1368
  const state = states[index];
1276
1369
  runtime.generatedStates++;
1277
1370
  current.candidate = successor.state;
@@ -1285,6 +1378,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1285
1378
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1286
1379
  if (isInModel) search.trackActionPossible(state, successor.state);
1287
1380
  const existing = isInModel ? found : -1;
1381
+ if (source && isInModel) {
1382
+ stateWriter?.writeSuccessor(
1383
+ source,
1384
+ getGraphState(successor.state, depths[index] + 1),
1385
+ existing !== -1,
1386
+ action && { name: action.name, signature: getActionSignature(action) },
1387
+ );
1388
+ }
1288
1389
  if (existing !== -1 && liveness) {
1289
1390
  const stored = states[existing];
1290
1391
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1356,23 +1457,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1356
1457
  }
1357
1458
  return createSuccess();
1358
1459
  }
1460
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1461
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1462
+ const isNamingEdges = Boolean(
1463
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1464
+ );
1465
+ const forEachActionSuccessor = (
1466
+ state: Value[],
1467
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1468
+ ) => {
1469
+ if (!isNamingEdges) {
1470
+ return forEachSuccessor(
1471
+ next,
1472
+ state,
1473
+ environment,
1474
+ (successor) => onSuccessor(successor, undefined),
1475
+ spec.scope,
1476
+ );
1477
+ }
1478
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1479
+ const progress = { isStopped: false };
1480
+ return nextActions.value.reduce((count, action) => {
1481
+ if (progress.isStopped) return count;
1482
+ return (
1483
+ count +
1484
+ forEachSuccessor(
1485
+ action.expression,
1486
+ state,
1487
+ environment,
1488
+ (successor) => {
1489
+ progress.isStopped = onSuccessor(successor, action);
1490
+ return progress.isStopped;
1491
+ },
1492
+ action.scope,
1493
+ )
1494
+ );
1495
+ }, 0);
1496
+ };
1359
1497
  const expandState = (index: number) => {
1360
1498
  const state = states[index];
1361
1499
  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
- );
1500
+ const source = stateWriter && getGraphState(state, depths[index]);
1501
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1502
+ try {
1503
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1504
+ } catch (error) {
1505
+ outcome.result = toFailure(error, getTrace(index, successor));
1506
+ }
1507
+ return outcome.result !== undefined;
1508
+ });
1376
1509
  current.isExpanding = false;
1377
1510
  if (outcome.result) return outcome.result;
1378
1511
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1440,7 +1573,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1440
1573
  try {
1441
1574
  outcome.result = expandState(index);
1442
1575
  } catch (error) {
1443
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1576
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1444
1577
  }
1445
1578
  if (outcome.result) return outcome.result;
1446
1579
  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
  };
package/src/codegen.ts CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  getSubsetOperator,
11
11
  getEvaluator,
12
12
  getFieldError,
13
+ getNonFunctionError,
14
+ getNonRecordError,
13
15
  isClosedConstant,
14
16
  isTlcInteger,
15
17
  isValueArgument,
@@ -250,12 +252,13 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
250
252
  case "FunctionApplication": {
251
253
  keepLazy(expression.function);
252
254
  const functionCode = generate(expression.function);
255
+ const describeNonFunction = addReference(generator, getNonFunctionError(expression));
253
256
  if (expression.args.length === 1)
254
- return `apply(${functionCode}, ${generate(expression.args[0])})`;
255
- return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
257
+ return `apply(${functionCode}, ${generate(expression.args[0])}, undefined, ${describeNonFunction})`;
258
+ return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]), undefined, ${describeNonFunction})`;
256
259
  }
257
260
  case "FieldAccess":
258
- return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
261
+ return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))}, ${addReference(generator, getNonRecordError(expression))})`;
259
262
  case "Record": {
260
263
  const fields = getSortedFields(expression.fields);
261
264
  if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
@@ -12,12 +12,13 @@ import {
12
12
  import { BUNDLED_MODULES } from "./bundled-modules";
13
13
  import type { ConfigValue, ModelConfig } from "./config";
14
14
  import type { FileSystem } from "./json";
15
- import { TlaConfigError, TlaEvaluationError, TlaSyntaxError } from "./errors";
15
+ import { TlaConfigError, TlaEvaluationError, TlaModuleError, TlaSyntaxError } from "./errors";
16
16
  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,8 +45,9 @@ 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";
50
+ import { getTlcDeclarationOrder } from "./tlc-order";
49
51
  import {
50
52
  checkInteger,
51
53
  createModelValue,
@@ -212,6 +214,8 @@ export const createEnvironment = (
212
214
  const root = parseModule(options.source);
213
215
  const definitions = new Map<string, Definition>();
214
216
  const parameterized = new Map<string, boolean>();
217
+ // The definition each instance copy came from, and the instance parameters the copy adds.
218
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
219
  const builtins = new Map<string, Builtin>(
216
220
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
221
  );
@@ -379,10 +383,11 @@ export const createEnvironment = (
379
383
  variables: new Set(linked.variables),
380
384
  getDefinition: (key) => definitions.get(key),
381
385
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
386
+ addDefinition: (source, name, create) => {
383
387
  const key = createName(`${name}@${module.name}`);
384
388
  definitions.set(key, create(key));
385
389
  parameterized.set(key, !isParameterFree);
390
+ copySources.set(key, { source, prefix: instance.params.length });
386
391
  return key;
387
392
  },
388
393
  createName,
@@ -544,7 +549,7 @@ export const createEnvironment = (
544
549
  variables: new Set(linked.variables),
545
550
  getDefinition: (key) => definitions.get(key),
546
551
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
552
+ addDefinition: (_source, name, create) => {
548
553
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
554
  const definition = create(key);
550
555
  copies.push(
@@ -872,11 +877,51 @@ export const createEnvironment = (
872
877
  );
873
878
  }
874
879
  });
875
- declaredConstants.forEach((name) => {
876
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
877
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
878
- }
880
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
881
+ // the module shares.
882
+ const scopedKeys = new Set(
883
+ [...config.constants, ...config.substitutions]
884
+ .filter((item) => item.module !== undefined)
885
+ .flatMap(getScopedKeys),
886
+ );
887
+ const getOverride = (
888
+ key: string,
889
+ prefix: number,
890
+ ): { key: string; prefix: number } | undefined => {
891
+ if (scopedKeys.has(key)) return { key, prefix };
892
+ const copy = copySources.get(key);
893
+ return copy && getOverride(copy.source, prefix + copy.prefix);
894
+ };
895
+ copySources.forEach((copy, key) => {
896
+ const override = getOverride(copy.source, copy.prefix);
897
+ const definition = definitions.get(key);
898
+ if (!override || !definition) return;
899
+ const params = definition.kind === "Operator" ? definition.params : [];
900
+ const alias = createLocalAlias(
901
+ key,
902
+ override.key,
903
+ params,
904
+ params.slice(override.prefix),
905
+ definition.location,
906
+ );
907
+ definitions.set(key, alias);
908
+ linkedRoot.visible.forEach((symbol, name) => {
909
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
910
+ });
879
911
  });
912
+ const unassigned = declaredConstants.filter(
913
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
914
+ );
915
+ if (unassigned.length > 0) {
916
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
917
+ const name =
918
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
919
+ unassigned.includes(constant),
920
+ ) ?? unassigned[0];
921
+ throw new TlaConfigError(
922
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
923
+ );
924
+ }
880
925
 
881
926
  const environment: Environment = {
882
927
  runtime,
@@ -907,18 +952,43 @@ export const createEnvironment = (
907
952
  getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
953
  };
909
954
  });
955
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
956
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
957
+ // a minimum level as state-level, so the analyzer takes them for variables.
958
+ const analyzer = createLevelAnalyzer({
959
+ constants: new Set(constants.keys()),
960
+ variables: new Set([
961
+ ...variables,
962
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
963
+ ]),
964
+ getDefinition: (name) => getDefinition(name, environment),
965
+ });
966
+ const getEvaluationError = (body: Expression) => {
967
+ try {
968
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
969
+ return undefined;
970
+ } catch (error) {
971
+ if (error instanceof TlaEvaluationError) return error;
972
+ throw error;
973
+ }
974
+ };
910
975
  substitutions.forEach((target, name) => {
911
976
  const definition = definitions.get(target);
912
- if (
977
+ const error =
913
978
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
916
- ) {
979
+ definition?.kind === "Operator" &&
980
+ definition.params.length === 0 &&
981
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
982
+ ? getEvaluationError(definition.body)
983
+ : undefined;
984
+ // TLC adds the reason unless a standard module's Java code failed.
985
+ if (error) {
917
986
  throw new TlaConfigError(
918
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
987
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
919
988
  );
920
989
  }
921
990
  });
991
+ runtime.isStarted = true;
922
992
  return {
923
993
  environment,
924
994
  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;