tla-ts 0.0.3-dev.e927a09 → 0.0.3-dev.e9d8347

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.e927a09",
3
+ "version": "0.0.3-dev.e9d8347",
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,10 +13,11 @@ import {
13
13
  getErrorExitCode,
14
14
  TlaConfigError,
15
15
  TlaEvaluationError,
16
+ TlaIncompleteStateError,
16
17
  TlaModuleError,
17
18
  UNEXPECTED_EXCEPTION,
18
19
  } from "./errors";
19
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
20
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
20
21
  import {
21
22
  describeRange,
22
23
  evaluate,
@@ -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 }];
@@ -436,12 +450,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
436
450
  config.properties.forEach((name) => {
437
451
  const definition = getConfigPredicate("property", name, environment);
438
452
  if (!definition) return;
439
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
453
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
440
454
  const conjunct = item.expression;
441
455
  if (isConstantTrue(item, environment, "property")) return;
442
456
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
443
457
  properties.actionProperties.push({
444
- name,
458
+ name: item.name,
445
459
  box: conjunct.expression,
446
460
  action: conjunct.expression.action,
447
461
  subscript: conjunct.expression.subscript,
@@ -453,12 +467,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
453
467
  conjunct.kind === "Always" &&
454
468
  getLevel(conjunct.expression, item.scope, environment) <= 1
455
469
  ) {
456
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
470
+ // TLC names the invariant []P after P when P is an operator name.
471
+ const expression = conjunct.expression;
472
+ properties.invariants.push({
473
+ name: expression.kind === "Identifier" ? expression.name : item.name,
474
+ expression,
475
+ scope: item.scope,
476
+ });
457
477
  return;
458
478
  }
459
479
  const level = getLevel(conjunct, item.scope, environment);
460
480
  if (level < ACTION_LEVEL) {
461
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
481
+ properties.initialPredicates.push({
482
+ name: item.name,
483
+ expression: conjunct,
484
+ scope: item.scope,
485
+ });
462
486
  return;
463
487
  }
464
488
  if (level === ACTION_LEVEL) {
@@ -518,7 +542,9 @@ const getMembership = (
518
542
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
519
543
  named.flatMap((item) =>
520
544
  getConjuncts(item.expression, environment).map((expression) => {
521
- const variables = getReadVariables(expression, environment);
545
+ // A LET or an argument in the scope can read variables the expression doesn't name.
546
+ const variables =
547
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
522
548
  return {
523
549
  name: item.name,
524
550
  expression,
@@ -765,11 +791,13 @@ export const createSearch = (
765
791
  if (view !== undefined || isFingerprintedLikeTlc) {
766
792
  return BigInt64Array.from(states, getTlcStateFingerprint);
767
793
  }
768
- const indices = getTlcOrder();
769
- const getFingerprint = createTlcFingerprinter();
770
- return BigInt64Array.from(fingerprintStates, (state) =>
771
- getFingerprint(indices.map((index) => state[index])),
794
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
795
+ const fingerprint = createTlcFingerprinter(
796
+ getTlcOrder(),
797
+ new Int32Array(fingerprints.buffer),
772
798
  );
799
+ fingerprintStates.forEach(fingerprint);
800
+ return fingerprints;
773
801
  },
774
802
  getFingerprintState: (state) => {
775
803
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -831,7 +859,10 @@ export const createSearch = (
831
859
  )
832
860
  );
833
861
  } catch (error) {
834
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
862
+ throw withHeadline(
863
+ withNextStateExitCode(error),
864
+ `Evaluating action property ${property.name} failed.`,
865
+ );
835
866
  }
836
867
  }),
837
868
  satisfiesActionConstraints: (state, next) =>
@@ -867,6 +898,23 @@ export const createSearch = (
867
898
  };
868
899
  };
869
900
 
901
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
902
+ // computation of next states. In every other phase, the phase decides the code.
903
+ const withNextStateExitCode = (error: unknown) =>
904
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
905
+
906
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
907
+ // module raised it as an EvalException.
908
+ const toNextStateError = (error: unknown) =>
909
+ error instanceof TlaEvaluationError &&
910
+ !(error instanceof TlaModuleError) &&
911
+ !(error instanceof TlaIncompleteStateError)
912
+ ? setExitCode(
913
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
914
+ getErrorExitCode(error),
915
+ )
916
+ : withNextStateExitCode(error);
917
+
870
918
  const withHeadline = (error: unknown, headline: string) =>
871
919
  error instanceof TlaEvaluationError
872
920
  ? setExitCode(
@@ -875,8 +923,15 @@ const withHeadline = (error: unknown, headline: string) =>
875
923
  )
876
924
  : error;
877
925
 
926
+ // TLC finishes the -dump file whether or not the search finds a violation.
878
927
  export const checkSequentially = (options: CheckOptions): CheckResult => {
879
- setNextStatePhase(false);
928
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
929
+ const result = searchStates(options, stateWriter);
930
+ stateWriter?.close();
931
+ return result;
932
+ };
933
+
934
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
880
935
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
881
936
  const onPrint = options.onPrint ?? console.log;
882
937
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -946,7 +1001,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
946
1001
  });
947
1002
 
948
1003
  const search = createSearch(config, environment, () =>
949
- getTlcVariableOrder(options.source, options.loadModule),
1004
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
950
1005
  );
951
1006
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
952
1007
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1010,7 +1065,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1010
1065
  const parents: number[] = [];
1011
1066
  const actions: (string | undefined)[] = [];
1012
1067
  const depths: number[] = [];
1013
- const buckets = new Map<number, number | number[]>();
1068
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1069
+ // and its index plus one side by side, probed by the hash.
1070
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1014
1071
  const canonicalizeState = createCanonicalizer();
1015
1072
 
1016
1073
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1023,11 +1080,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1023
1080
  position: number,
1024
1081
  loopStart: number | undefined,
1025
1082
  ) => {
1026
- const state = steps[position].state;
1027
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
1028
1083
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1029
1084
  runtime.getLevel = () => position + 1;
1030
1085
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1086
+ return evaluateAlias(
1087
+ alias,
1088
+ steps[position].state,
1089
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1090
+ );
1091
+ };
1092
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
1031
1093
  try {
1032
1094
  const body = getConfigDefinition("alias", alias, environment).body;
1033
1095
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1165,19 +1227,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1165
1227
  }
1166
1228
  return true;
1167
1229
  };
1230
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1168
1231
  const findStateIndex = (hash: number, state: Value[]) => {
1169
- const bucket = buckets.get(hash);
1170
- if (bucket === undefined) return -1;
1171
- if (typeof bucket === "number") {
1172
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1232
+ const mask = seen.slots.length - 1;
1233
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1234
+ const entry = seen.slots[slot + 1];
1235
+ if (entry === 0) return -1;
1236
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1237
+ return entry - 1;
1238
+ }
1173
1239
  }
1174
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1240
+ };
1241
+ const insertSeen = (hash: number, entry: number) => {
1242
+ const mask = seen.slots.length - 1;
1243
+ let slot = getSlot(hash);
1244
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1245
+ seen.slots[slot] = hash;
1246
+ seen.slots[slot + 1] = entry;
1175
1247
  };
1176
1248
  const markSeen = (hash: number, index: number) => {
1177
- const bucket = buckets.get(hash);
1178
- if (bucket === undefined) buckets.set(hash, index);
1179
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1180
- else bucket.push(index);
1249
+ seen.size++;
1250
+ if (seen.size * 4 > seen.slots.length) {
1251
+ const slots = seen.slots;
1252
+ seen.slots = new Int32Array(slots.length * 2);
1253
+ seen.shift--;
1254
+ for (let slot = 0; slot < slots.length; slot += 2) {
1255
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1256
+ }
1257
+ }
1258
+ insertSeen(hash, index + 1);
1181
1259
  };
1182
1260
  const countDistinctState = (depth: number) => {
1183
1261
  runtime.distinctStates = states.length + 1;
@@ -1228,6 +1306,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1228
1306
  return current.isExpanding ? depths[current.index] + 1 : 0;
1229
1307
  };
1230
1308
 
1309
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1310
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1311
+ level,
1312
+ getLabel: () =>
1313
+ formatState(
1314
+ config.alias === undefined
1315
+ ? toRecord(state)
1316
+ : evaluateAlias(config.alias, state, undefined),
1317
+ ),
1318
+ getText: () => formatState(toRecord(state)),
1319
+ });
1320
+
1231
1321
  const visitInitialState = (state: Value[]) => {
1232
1322
  canonicalizeState(state);
1233
1323
  runtime.generatedStates++;
@@ -1244,6 +1334,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1244
1334
  countDistinctState(1);
1245
1335
  runtime.queueSize++;
1246
1336
  liveness?.addInitialState(states.length, state);
1337
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1247
1338
  }
1248
1339
  const violated = search.findViolatedInvariant(state);
1249
1340
  if (violated) {
@@ -1264,7 +1355,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1264
1355
  addState(state, fingerprintState, -1, undefined);
1265
1356
  return undefined;
1266
1357
  };
1267
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1358
+ const visitSuccessor = (
1359
+ index: number,
1360
+ successor: Successor,
1361
+ liveSuccessors: LiveSuccessor[],
1362
+ source: GraphState | undefined,
1363
+ action: SpecAction | undefined,
1364
+ ) => {
1268
1365
  const state = states[index];
1269
1366
  runtime.generatedStates++;
1270
1367
  current.candidate = successor.state;
@@ -1278,6 +1375,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1278
1375
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1279
1376
  if (isInModel) search.trackActionPossible(state, successor.state);
1280
1377
  const existing = isInModel ? found : -1;
1378
+ if (source && isInModel) {
1379
+ stateWriter?.writeSuccessor(
1380
+ source,
1381
+ getGraphState(successor.state, depths[index] + 1),
1382
+ existing !== -1,
1383
+ action && { name: action.name, signature: getActionSignature(action) },
1384
+ );
1385
+ }
1281
1386
  if (existing !== -1 && liveness) {
1282
1387
  const stored = states[existing];
1283
1388
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1349,23 +1454,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1349
1454
  }
1350
1455
  return createSuccess();
1351
1456
  }
1457
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1458
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1459
+ const isNamingEdges = Boolean(
1460
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1461
+ );
1462
+ const forEachActionSuccessor = (
1463
+ state: Value[],
1464
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1465
+ ) => {
1466
+ if (!isNamingEdges) {
1467
+ return forEachSuccessor(
1468
+ next,
1469
+ state,
1470
+ environment,
1471
+ (successor) => onSuccessor(successor, undefined),
1472
+ spec.scope,
1473
+ );
1474
+ }
1475
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1476
+ const progress = { isStopped: false };
1477
+ return nextActions.value.reduce((count, action) => {
1478
+ if (progress.isStopped) return count;
1479
+ return (
1480
+ count +
1481
+ forEachSuccessor(
1482
+ action.expression,
1483
+ state,
1484
+ environment,
1485
+ (successor) => {
1486
+ progress.isStopped = onSuccessor(successor, action);
1487
+ return progress.isStopped;
1488
+ },
1489
+ action.scope,
1490
+ )
1491
+ );
1492
+ }, 0);
1493
+ };
1352
1494
  const expandState = (index: number) => {
1353
1495
  const state = states[index];
1354
1496
  const liveSuccessors: LiveSuccessor[] = [];
1355
- const successorCount = forEachSuccessor(
1356
- next,
1357
- state,
1358
- environment,
1359
- (successor) => {
1360
- try {
1361
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1362
- } catch (error) {
1363
- outcome.result = toFailure(error, getTrace(index, successor));
1364
- }
1365
- return outcome.result !== undefined;
1366
- },
1367
- spec.scope,
1368
- );
1497
+ const source = stateWriter && getGraphState(state, depths[index]);
1498
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1499
+ try {
1500
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1501
+ } catch (error) {
1502
+ outcome.result = toFailure(error, getTrace(index, successor));
1503
+ }
1504
+ return outcome.result !== undefined;
1505
+ });
1369
1506
  current.isExpanding = false;
1370
1507
  if (outcome.result) return outcome.result;
1371
1508
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1425,7 +1562,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1425
1562
  periodic.time += performance.now() - now;
1426
1563
  return lasso;
1427
1564
  };
1428
- setNextStatePhase(true);
1429
1565
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1430
1566
  current.index = index;
1431
1567
  current.candidate = undefined;
@@ -1434,7 +1570,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1434
1570
  try {
1435
1571
  outcome.result = expandState(index);
1436
1572
  } catch (error) {
1437
- outcome.result = toFailure(error, getStateTrace(index));
1573
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1438
1574
  }
1439
1575
  if (outcome.result) return outcome.result;
1440
1576
  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,