tla-ts 0.0.10-dev.99796fe03 → 0.0.10-dev.c92e6a4ea

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/src/exit-codes.ts CHANGED
@@ -82,6 +82,7 @@ export const withLivenessExitCode = (
82
82
  addState: (index, state, successors, tracing) =>
83
83
  withErrorExitCode(() => checker.addState(index, state, successors, tracing)),
84
84
  storeState: checker.storeState,
85
+ getStateCounts: checker.getStateCounts,
85
86
  findViolation: () => withErrorExitCode(() => checker.findViolation()),
86
87
  getViolatedProperties: (path, cycleStart) =>
87
88
  withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
@@ -46,6 +46,7 @@ export interface LivenessChecker {
46
46
  tracing?: Environment,
47
47
  ) => number[] | undefined;
48
48
  storeState: (pending: number, index: number) => void;
49
+ getStateCounts: () => number[];
49
50
  findViolation: () => Lasso | undefined;
50
51
  getViolatedProperties: (path: Value[][], cycleStart: number) => string[];
51
52
  }
@@ -60,6 +61,8 @@ export interface LiveGraph<State> {
60
61
  successors: LiveSuccessor<State>[],
61
62
  ) => number[] | undefined;
62
63
  storeState: (pending: number, index: number) => void;
64
+ // How many states the graph of each branch has, which TLC counts as the fingerprints of its nodes.
65
+ getStateCounts: () => number[];
63
66
  findViolation: () => Lasso | undefined;
64
67
  }
65
68
 
@@ -116,6 +119,7 @@ interface BehaviorGraph<State> {
116
119
  nextSiblings: number[];
117
120
  nodeIds: NodeTable;
118
121
  isDone: boolean[];
122
+ stateCount: number;
119
123
  errorNode: number | undefined;
120
124
  }
121
125
 
@@ -369,6 +373,7 @@ export const createLivenessChecker = (
369
373
  addState: (index, state, successors, replay) =>
370
374
  traceWith(replay, () => graph.addState(index, state, successors)),
371
375
  storeState: graph.storeState,
376
+ getStateCounts: graph.getStateCounts,
372
377
  findViolation: graph.findViolation,
373
378
  getViolatedProperties: (path, cycleStart) => [
374
379
  ...new Set(
@@ -508,6 +513,7 @@ export const createLiveGraph = <State>(
508
513
  nextSiblings: [],
509
514
  nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
510
515
  isDone: [],
516
+ stateCount: 0,
511
517
  errorNode: undefined,
512
518
  }));
513
519
  const checkState = (
@@ -631,8 +637,17 @@ export const createLiveGraph = <State>(
631
637
  writeToPool(behavior.lastNodes, state, [node]);
632
638
  return node;
633
639
  };
634
- const recordNode = (behavior: BehaviorGraph<State>, state: number, tableauNode: number) =>
635
- linkNode(behavior, state, tableauNode, pushNode(behavior, state, tableauNode));
640
+ // TLC's table of tableau nodes has a state once the search expands it or it has a node.
641
+ const hasState = (behavior: BehaviorGraph<State>, state: number) =>
642
+ state < 0
643
+ ? behavior.checks.nodes.some(
644
+ (_checks, tableauNode) => getNodeId(behavior, state, tableauNode) !== undefined,
645
+ )
646
+ : behavior.isDone[state] === true || (behavior.firstNodes.data[state] ?? NO_NODE) !== NO_NODE;
647
+ const recordNode = (behavior: BehaviorGraph<State>, state: number, tableauNode: number) => {
648
+ if (!hasState(behavior, state)) behavior.stateCount++;
649
+ return linkNode(behavior, state, tableauNode, pushNode(behavior, state, tableauNode));
650
+ };
636
651
  // The action results of the edge to each target are at its position in actions.
637
652
  const writeNode = (
638
653
  behavior: BehaviorGraph<State>,
@@ -799,6 +814,7 @@ export const createLiveGraph = <State>(
799
814
  }
800
815
  }
801
816
  });
817
+ if (!hasState(behavior, index)) behavior.stateCount++;
802
818
  behavior.isDone[index] = true;
803
819
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
804
820
  for (const node of getStateNodes(behavior, index)) {
@@ -848,6 +864,7 @@ export const createLiveGraph = <State>(
848
864
  successors.push(successor.index);
849
865
  actions.push(position);
850
866
  });
867
+ if (!isWritten(behavior, index)) behavior.stateCount++;
851
868
  writeNode(behavior, index, successors, actionResults, actions, stateResults);
852
869
  };
853
870
 
@@ -1183,6 +1200,7 @@ export const createLiveGraph = <State>(
1183
1200
  }
1184
1201
  }
1185
1202
  },
1203
+ getStateCounts: () => behaviors.map((behavior) => behavior.stateCount),
1186
1204
  findViolation: () => {
1187
1205
  for (const behavior of behaviors) {
1188
1206
  for (const model of behavior.solution.models) {
@@ -41,8 +41,14 @@ const runWorker = (start: StartMessage, parent: Port) => {
41
41
  );
42
42
  const specification = created.specification;
43
43
  const environment = specification.environment;
44
- const search = createSearch(start.config, environment, specification.variableLocations, () =>
45
- created.order.getDeclarationOrder("variable"),
44
+ const search = createSearch(
45
+ start.config,
46
+ environment,
47
+ specification.variableLocations,
48
+ () => created.order.getDeclarationOrder("variable"),
49
+ undefined,
50
+ [],
51
+ specification.runtimeInvariants,
46
52
  );
47
53
  const nextAction = search?.spec.next;
48
54
  if (!search || nextAction === undefined)
package/src/parallel.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  } from "./check";
9
9
  import { parseConfig, type ModelConfig } from "./config";
10
10
  import { TlaEvaluationError } from "./errors";
11
+ import type { RuntimeInvariant } from "./environment";
11
12
  import { isImpure } from "./evaluate";
12
13
  import {
13
14
  createSharedFingerprints,
@@ -43,6 +44,7 @@ export interface StartMessage extends Pick<
43
44
  > {
44
45
  type: "start";
45
46
  config: ModelConfig;
47
+ runtimeInvariants: RuntimeInvariant[];
46
48
  modules: [string, string | undefined][];
47
49
  classes: [string, Uint8Array | undefined][];
48
50
  index: number;
@@ -146,6 +148,8 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
146
148
  specification.variableLocations,
147
149
  () => created.order.getDeclarationOrder("variable"),
148
150
  report,
151
+ [],
152
+ specification.runtimeInvariants,
149
153
  );
150
154
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
151
155
  if (
@@ -273,6 +277,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
273
277
  type: "start",
274
278
  source: options.source,
275
279
  config,
280
+ runtimeInvariants: specification.runtimeInvariants,
276
281
  modules: [...modules],
277
282
  classes: [...classes],
278
283
  index,
package/src/runtime.ts CHANGED
@@ -26,6 +26,7 @@ export interface CheckerRuntime {
26
26
  version: TlcVersion;
27
27
  seed: bigint;
28
28
  isSeen: (state: Value[]) => boolean;
29
+ markExplored: ((state: Value[]) => void) | undefined;
29
30
  getSuccessorAction: (state: Value[], next: Value[]) => SpecAction | undefined;
30
31
  toRecord: (state: Value[]) => Record<string, Value>;
31
32
  generatedStates: number;
@@ -55,6 +56,7 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
55
56
  counterExample: undefined,
56
57
  deferred: undefined,
57
58
  isSeen: () => false,
59
+ markExplored: undefined,
58
60
  getSuccessorAction: () => undefined,
59
61
  toRecord: () => ({}),
60
62
  setLivenessSource: () => {},
package/src/search.ts CHANGED
@@ -28,7 +28,11 @@ import {
28
28
  isExpressionImpure,
29
29
  isImpureDefinition,
30
30
  } from "./dependencies";
31
- import { createEnvironment, type ResolvedModuleOperator } from "./environment";
31
+ import {
32
+ createEnvironment,
33
+ type ResolvedModuleOperator,
34
+ type RuntimeInvariant,
35
+ } from "./environment";
32
36
  import {
33
37
  isStackOverflow,
34
38
  TlaConfigError,
@@ -95,8 +99,9 @@ import {
95
99
  type Value,
96
100
  } from "./values";
97
101
 
98
- export interface StandardInput {
102
+ export interface CliSettings {
99
103
  readLine?: () => string | undefined;
104
+ runtimeInvariants?: RuntimeInvariant[];
100
105
  }
101
106
 
102
107
  interface EnvironmentSettings
@@ -121,7 +126,7 @@ interface EnvironmentSettings
121
126
  | "isLazyValueExpanded"
122
127
  | "isViewPrinted"
123
128
  >,
124
- StandardInput {}
129
+ CliSettings {}
125
130
 
126
131
  interface NamedExpression {
127
132
  name: string;
@@ -860,7 +865,12 @@ export const createCheckEnvironment = (
860
865
  isStringOrderFrozen = false,
861
866
  ) => {
862
867
  const order = createTlcOrder(options.source, options.loadModule);
863
- setStringOrder(order.getStringOrder(config));
868
+ setStringOrder(
869
+ order.getStringOrder(
870
+ config,
871
+ (options.runtimeInvariants ?? []).flatMap((invariant) => invariant.module ?? []),
872
+ ),
873
+ );
864
874
  setValueOptions(options);
865
875
  setFingerprintPolynomial(options.fingerprintPolynomial ?? 0);
866
876
  if (isStringOrderFrozen) freezeStringOrder();
@@ -883,6 +893,7 @@ export const createCheckEnvironment = (
883
893
  version: options.version,
884
894
  moduleOperators: options.moduleOperators,
885
895
  readLine: options.readLine,
896
+ runtimeInvariants: options.runtimeInvariants,
886
897
  });
887
898
  return { order, specification };
888
899
  };
@@ -908,6 +919,7 @@ export const prepareSearch = (options: CheckOptions) => {
908
919
  () => created.order.getDeclarationOrder("variable"),
909
920
  options.onProgress,
910
921
  specification.moduleOperators,
922
+ specification.runtimeInvariants,
911
923
  );
912
924
  return { config, specification, environment, search, getDescription };
913
925
  };
@@ -948,6 +960,7 @@ export const createSearch = (
948
960
  getVariableOrder: () => string[],
949
961
  onProgress?: CheckOptions["onProgress"],
950
962
  moduleOperators: ResolvedModuleOperator[] = [],
963
+ runtimeInvariants: RuntimeInvariant[] = [],
951
964
  ): Search | undefined => {
952
965
  const getModuleOperators = (kind: ResolvedModuleOperator["kind"]) =>
953
966
  moduleOperators
@@ -976,12 +989,12 @@ export const createSearch = (
976
989
  text: `Implied-temporal checking is a tautology.\nThe temporal formula ${live} at ${formatRange(liveRange)} equals\nthe fairness constraints of the behavior specification ${specName} at ${formatRange(specRange)}.\nTherefore, checking whether ${specName} => ${live} using TLC will never result in a violation of ${live}.`,
977
990
  });
978
991
  }
979
- const invariants = getStateChecks([...configInvariants, ...properties.invariants], environment);
980
- const invariantPredicates = [
981
- ...new Map(invariants.map((invariant) => [invariant.predicate, invariant])).values(),
982
- ];
992
+ const checkedInvariants = getStateChecks(
993
+ [...configInvariants, ...properties.invariants],
994
+ environment,
995
+ );
983
996
  const isCheckingBehaviors =
984
- invariants.length > 0 ||
997
+ checkedInvariants.length > 0 ||
985
998
  properties.actionProperties.length > 0 ||
986
999
  properties.liveness.length > 0;
987
1000
  if (
@@ -999,6 +1012,22 @@ export const createSearch = (
999
1012
  if (spec.next === undefined && isCheckingBehaviors) {
1000
1013
  throw new TlaConfigError("The configuration file did not specify the next state predicate.");
1001
1014
  }
1015
+ const runtimeChecks = getStateChecks(
1016
+ runtimeInvariants.map((invariant) => {
1017
+ const definition = getDefinition(invariant.name, environment);
1018
+ return {
1019
+ name: invariant.name,
1020
+ expression:
1021
+ definition?.kind === "Operator" ? definition.body : createIdentifier(invariant.name),
1022
+ scope: undefined,
1023
+ };
1024
+ }),
1025
+ environment,
1026
+ );
1027
+ const invariants = [...checkedInvariants, ...runtimeChecks];
1028
+ const invariantPredicates = [
1029
+ ...new Map(invariants.map((invariant) => [invariant.predicate, invariant])).values(),
1030
+ ];
1002
1031
  const namedConstraints = getNamedExpressions(
1003
1032
  "constraint",
1004
1033
  [...config.constraints, ...getModuleOperators("constraint").map((operator) => operator.name)],
@@ -1298,8 +1327,8 @@ export const createSearch = (
1298
1327
  return view === undefined ? representative : [getViewValue(view.expression, representative)];
1299
1328
  },
1300
1329
  findViolatedInvariant: (state, parent) => {
1301
- if (isCoveredHeld(coveredInvariants, state)) return undefined;
1302
- const violated = invariants.find((invariant) => isViolated(invariant, state, parent));
1330
+ const checked = isCoveredHeld(coveredInvariants, state) ? runtimeChecks : invariants;
1331
+ const violated = checked.find((invariant) => isViolated(invariant, state, parent));
1303
1332
  if (violated) violatingStates.add(state);
1304
1333
  return violated;
1305
1334
  },
package/src/tlc/order.ts CHANGED
@@ -444,7 +444,11 @@ const createContexts = (getParsed: ModuleSet) => {
444
444
  };
445
445
  };
446
446
 
447
- const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] => {
447
+ const getStringOrder = (
448
+ getParsed: ModuleSet,
449
+ config: ModelConfig,
450
+ runtimeModules: string[],
451
+ ): string[] => {
448
452
  const order = new Set<string>();
449
453
  const intern = (text: string) => {
450
454
  order.add(text);
@@ -541,12 +545,19 @@ const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] =>
541
545
  });
542
546
  };
543
547
  analyze(undefined);
548
+ runtimeModules.forEach((name) => {
549
+ const tokens = getUnitTokens(name);
550
+ getParsedTexts(tokens).forEach(intern);
551
+ tokens.forEach((token) => {
552
+ if (token.kind === "String") intern(token.text);
553
+ });
554
+ });
544
555
  TLC_RUNTIME_STRINGS.forEach(intern);
545
556
  return [...order];
546
557
  };
547
558
 
548
559
  export interface TlcOrder {
549
- getStringOrder: (config: ModelConfig) => string[];
560
+ getStringOrder: (config: ModelConfig, runtimeModules: string[]) => string[];
550
561
  getDeclarationOrder: (kind: "variable" | "constant") => string[];
551
562
  createDefinitionOrder: () => (name: string | undefined) => string[];
552
563
  parseModule: (source: string) => Module;
@@ -558,7 +569,7 @@ export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrd
558
569
  let contexts: ReturnType<typeof createContexts> | undefined;
559
570
  const getContexts = () => (contexts ??= createContexts(getParsed));
560
571
  return {
561
- getStringOrder: (config) => getStringOrder(getParsed, config),
572
+ getStringOrder: (config, runtimeModules) => getStringOrder(getParsed, config, runtimeModules),
562
573
  getDeclarationOrder: (kind) =>
563
574
  getContexts()
564
575
  .getContext(undefined)
@@ -263,10 +263,13 @@ export const createTlcExtOperators = (
263
263
  defineOperator("TLCNoOp", 1, (args) => getValue(args, 0, "TLCNoOp")),
264
264
  {
265
265
  ...defineLazyOperator("PickSuccessor", 1, (args, context) => {
266
- // Deviation from TLC: TLCExt#pickSuccessor fingerprints a partial successor and fails, where TLCExt.tla promises TRUE.
267
266
  const next = context?.next ?? (context?.environment.variables ?? []).map(() => undefined);
268
- if (!isCompleteState(next)) return true;
269
- if (context?.next && runtime.isSeen(next)) return true;
267
+ // A simulation remembers no states, so TLC evaluates the guard before it looks at the successor.
268
+ if (runtime.getSimulationValue === undefined) {
269
+ // Deviation from TLC: TLCExt#pickSuccessor fingerprints a partial successor and fails, where TLCExt.tla promises TRUE.
270
+ if (!isCompleteState(next)) return true;
271
+ if (context?.next && runtime.isSeen(next)) return true;
272
+ }
270
273
  const guard = getOperator(args, 0, "PickSuccessor");
271
274
  const isPicked = guard.call([]);
272
275
  if (typeof isPicked !== "boolean") {
@@ -274,7 +277,13 @@ export const createTlcExtOperators = (
274
277
  `In evaluating TLCExt!PickSuccessor, a non-boolean expression (${getKindString(isPicked)}) was used as the condition of an IF.\n${guard.expression ? describeNode(guard.expression) : ""}`,
275
278
  );
276
279
  }
277
- if (isPicked || !context?.next || !context.state || !isCompleteState(context.state)) {
280
+ if (
281
+ isPicked ||
282
+ !context?.next ||
283
+ !isCompleteState(next) ||
284
+ !context.state ||
285
+ !isCompleteState(context.state)
286
+ ) {
278
287
  return true;
279
288
  }
280
289
  const state = context.state;
@@ -303,9 +312,13 @@ export const createTlcExtOperators = (
303
312
  } else if (answer[0] === "d") {
304
313
  printOverride(formatState(runtime.toRecord(next), runtime.toRecord(state)));
305
314
  } else if (answer[0] === "e") {
315
+ if (runtime.markExplored) {
316
+ runtime.markExplored(next);
317
+ return true;
318
+ }
306
319
  if (runtime.getSimulationValue === undefined) {
307
320
  throw new TlaUnsupportedError(
308
- "tla-ts can't mark a state explored while it checks a model.",
321
+ "tla-ts can't mark a state explored while it searches depth first.",
309
322
  );
310
323
  }
311
324
  printOverride(