tla-ts 0.0.10-dev.d618a2d79 → 0.0.10-dev.f08db3b1f

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.
@@ -3,14 +3,9 @@ import { EXIT_STATUS, setExitCode } from "../exit-codes";
3
3
  import { parseModule } from "../parser";
4
4
  import { generateSanySpecification } from "../sany/generator";
5
5
  import { checkModuleLevels } from "../sany/levels";
6
- import {
7
- VARIABLE_DECL_KIND,
8
- type ModuleNode,
9
- type OpDefNode,
10
- type SymbolNode,
11
- } from "../sany/nodes";
6
+ import type { ModuleNode, OpDefNode, SymbolNode } from "../sany/nodes";
12
7
  import type { TlcVersion } from "../tlc/version";
13
- import type { RuntimeInvariant } from "./tlc-arguments";
8
+ import type { RuntimeInvariantTemplate } from "./tlc-arguments";
14
9
 
15
10
  const CONSTANT_LEVEL = 0;
16
11
  const TEMPORAL_LEVEL = 3;
@@ -31,21 +26,20 @@ const createParsingFailure = (detail: string) =>
31
26
  EXIT_STATUS.specParseError,
32
27
  );
33
28
 
34
- const getDebuggerExpressionLevel = (
35
- root: string,
29
+ const checkDebuggerExpression = (
30
+ source: string,
31
+ moduleName: string,
36
32
  name: string,
37
33
  expression: string,
38
34
  loadModule: (name: string) => string | undefined,
39
35
  version: TlcVersion,
40
36
  ) => {
41
- const moduleName = name.replace("__DebuggerExpr__", "__DebuggerModule__");
42
- const text = `---- MODULE ${moduleName} ----\nEXTENDS ${root}\n\n${name} == ${expression}\n====`;
43
37
  const createFailure = (message: string) =>
44
38
  createParsingFailure(
45
39
  `Unknown location\n\n${message} while parsing breakpoint expression "${expression}"`,
46
40
  );
47
41
  try {
48
- parseModule(text);
42
+ parseModule(source);
49
43
  } catch (error) {
50
44
  if (!(error instanceof TlaSyntaxError)) throw error;
51
45
  throw createParsingFailure(`Syntax error while parsing breakpoint expression "${expression}"`);
@@ -54,7 +48,7 @@ const getDebuggerExpressionLevel = (
54
48
  let isLevelCorrect = false;
55
49
  const specification = (() => {
56
50
  try {
57
- return generateSanySpecification(text, loadModule, {
51
+ return generateSanySpecification(source, loadModule, {
58
52
  version,
59
53
  onModule: (module, messages) => {
60
54
  const isCorrect = () => messages.every((message) => message.isWarning);
@@ -81,56 +75,26 @@ const getDebuggerExpressionLevel = (
81
75
  `Unknown location\n\nDebug expressions must be action-level or below; actual level: ${level} (Temporal)`,
82
76
  );
83
77
  }
84
- return level;
85
78
  };
86
79
 
87
- // Deviation from TLC: TLC puts a generated operator in a module that extends the root module.
88
- export const addRuntimeInvariants = (
80
+ export const getRuntimeInvariants = (
89
81
  source: string,
90
82
  root: ModuleNode,
91
- invariants: RuntimeInvariant[],
83
+ invariants: RuntimeInvariantTemplate[],
92
84
  loadModule: (name: string) => string | undefined,
93
85
  version: TlcVersion,
94
86
  ) => {
95
- const stamp = Date.now();
96
- const named = invariants.map((invariant, index) => ({
97
- expression: invariant.expression,
98
- name: findDefinition(root, invariant.expression)
99
- ? invariant.expression
100
- : `__DebuggerExpr__${stamp + index}`,
101
- }));
102
- const names = named.map((invariant) => invariant.name);
103
- const generated = named.filter((invariant) => invariant.name !== invariant.expression);
104
- if (generated.length === 0) return { names, source };
105
87
  const loadDependency = (name: string) => (name === root.name ? source : loadModule(name));
106
- const variable = root.context.symbols.find(
107
- (symbol) => symbol.kind === "OpDecl" && symbol.declKind === VARIABLE_DECL_KIND,
108
- );
109
- const definitions = generated.map((invariant) => {
110
- const head = `${invariant.name} == `;
111
- const level = getDebuggerExpressionLevel(
112
- root.name,
113
- invariant.name,
114
- invariant.expression,
115
- loadDependency,
116
- version,
117
- );
118
- // HACK: TLC checks a constant-level -inv in every state, so an unused LET makes it depend on one.
119
- return level === CONSTANT_LEVEL && variable
120
- ? `${invariant.name} ==\nLET ${invariant.name}State == ${variable.name} IN\n${" ".repeat(head.length)}${invariant.expression}`
121
- : `${head}${invariant.expression}`;
88
+ // Deviation from TLC: TLC reads the clock for each name, which no fixed output can match; one reading plus an index keeps the names apart.
89
+ const stamp = Date.now();
90
+ return invariants.map((invariant, index) => {
91
+ if (findDefinition(root, invariant.expression)) {
92
+ return { name: invariant.expression, module: undefined, source: undefined };
93
+ }
94
+ const module = `__DebuggerModule__${stamp + index}`;
95
+ const name = `__DebuggerExpr__${stamp + index}`;
96
+ const text = `---- MODULE ${module} ----\nEXTENDS ${root.name}\n\n${name} == ${invariant.expression}\n====`;
97
+ checkDebuggerExpression(text, module, name, invariant.expression, loadDependency, version);
98
+ return { name, module, source: text };
122
99
  });
123
- const lines = source.split("\n");
124
- const end = (parseModule(source).location.range?.end.line ?? lines.length) - 1;
125
- const terminator = lines[end].search(/={4,}/);
126
- return {
127
- names,
128
- source: [
129
- ...lines.slice(0, end),
130
- lines[end].slice(0, terminator),
131
- ...definitions,
132
- lines[end].slice(terminator),
133
- ...lines.slice(end + 1),
134
- ].join("\n"),
135
- };
136
100
  };
@@ -35,11 +35,11 @@ export interface TlcArguments {
35
35
  suppressedCodes: number[];
36
36
  errorCodes: number[];
37
37
  userFile: string | undefined;
38
- invariants: RuntimeInvariant[];
38
+ invariants: RuntimeInvariantTemplate[];
39
39
  moduleOperators: ModuleOperator[];
40
40
  }
41
41
 
42
- export interface RuntimeInvariant {
42
+ export interface RuntimeInvariantTemplate {
43
43
  modules: string[];
44
44
  expression: string;
45
45
  }
@@ -320,11 +320,10 @@ export const printCheckProgress = (
320
320
  timing.livenessStartTime = Date.now();
321
321
  if (progress.isComplete) printProgress(printer, progress.statistics);
322
322
  const branches = progress.branches > 1 ? `${progress.branches} branches of ` : "";
323
- const states = progress.branches * progress.states;
324
323
  print(
325
324
  MESSAGE_CODE.checkingTemporal,
326
325
  MESSAGE_LEVEL.none,
327
- `Checking ${branches}temporal properties for the ${progress.isComplete ? "complete" : "current"} state space with ${states} total distinct states at (${formatTlcDate(new Date())})`,
326
+ `Checking ${branches}temporal properties for the ${progress.isComplete ? "complete" : "current"} state space with ${progress.states} total distinct states at (${formatTlcDate(new Date())})`,
328
327
  );
329
328
  return;
330
329
  }
package/src/cli/tlc.ts CHANGED
@@ -29,7 +29,7 @@ import { EXIT_STATUS } from "../exit-codes";
29
29
  import { check } from "../parallel";
30
30
  import { extractModule, parseModule } from "../parser";
31
31
  import { simulate } from "../simulate";
32
- import type { StandardInput } from "../search";
32
+ import type { CliSettings } from "../search";
33
33
  import type { StateDump } from "../state-graph";
34
34
  import {
35
35
  getSanyStandardModules,
@@ -49,7 +49,7 @@ import {
49
49
  type MessagePrinter,
50
50
  zeroPad,
51
51
  } from "../tlc/messages";
52
- import { addRuntimeInvariants } from "./runtime-invariants";
52
+ import { getRuntimeInvariants } from "./runtime-invariants";
53
53
  import { parseTlcArguments, type TlcArguments } from "./tlc-arguments";
54
54
  import {
55
55
  getClassPath,
@@ -378,15 +378,14 @@ const checkSpec = async (
378
378
  }
379
379
  const userFile = args.userFile;
380
380
  const standardModules = getSanyStandardModules(version);
381
- const invariants = addRuntimeInvariants(
381
+ const runtimeInvariants = getRuntimeInvariants(
382
382
  source,
383
383
  specification.root,
384
384
  args.invariants,
385
385
  (name) => loadModule(name) ?? standardModules.get(name) ?? extractModule(source, name),
386
386
  version,
387
387
  );
388
- config.invariants.push(...invariants.names);
389
- const options: CheckOptions & StandardInput = {
388
+ const options: CheckOptions & CliSettings = {
390
389
  workers: args.workers,
391
390
  livenessCheck:
392
391
  livenessCheck === "off"
@@ -410,11 +409,17 @@ const checkSpec = async (
410
409
  version,
411
410
  onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
412
411
  onPrint: userFile === undefined ? undefined : (text) => appendFileSync(userFile, `${text}\n`),
413
- source: invariants.source,
412
+ source,
414
413
  config,
415
414
  onPause: () => readSync(0, Buffer.alloc(1)),
416
415
  readLine: readStandardInputLine,
417
- loadModule,
416
+ runtimeInvariants: runtimeInvariants.map((invariant) => ({
417
+ name: invariant.name,
418
+ module: invariant.module,
419
+ })),
420
+ loadModule: (name) =>
421
+ runtimeInvariants.find((invariant) => invariant.module === name)?.source ??
422
+ loadModule(name),
418
423
  loadClass: (name) => {
419
424
  const classPath = getClassPath(directory, name);
420
425
  return existsSync(classPath) ? readFileSync(classPath) : undefined;
@@ -586,7 +591,7 @@ export const checkSpecs = async (args: string[], java: JavaProperties) => {
586
591
  exitCodes.push(
587
592
  await reportErrors(async () => {
588
593
  const specPath = path.endsWith(".ts") ? await writeTypeScriptSpec(path) : path;
589
- // Deviation from TLC: TLC checks one spec, so tla-ts names each of several it checks.
594
+ // An extension: TLC refuses more than one spec, and tla-ts checks each one under its name.
590
595
  if (paths.length > 1) {
591
596
  console.log(`Checking ${basename(specPath)} with ${basename(specPath, ".tla")}.cfg`);
592
597
  }
package/src/dfid.ts CHANGED
@@ -15,7 +15,7 @@ import { EXIT_STATUS, getMessageExitStatus, withLivenessExitCode } from "./exit-
15
15
  import { createLivenessChecker } from "./liveness-checker";
16
16
  import { getIncompleteSuccessorMessage, prepareSearch, reportAssumptionViolation } from "./search";
17
17
  import type { SpecAction } from "./spec-description";
18
- import { forEachInitialState, forEachSuccessor } from "./successors";
18
+ import { forEachInitialState, forEachSuccessor, getSuccessors } from "./successors";
19
19
  import {
20
20
  formatNestedMessage,
21
21
  formatTlcDate,
@@ -28,7 +28,7 @@ import {
28
28
  import { getTlcFingerprint } from "./tlc/fingerprint";
29
29
  import { replaySuccessors } from "./tlc/replay";
30
30
  import { getOptimisticProbability, getActualProbability } from "./tlc/summary";
31
- import { createModelValue, formatState, getSetBound, type Value } from "./values";
31
+ import { createModelValue, formatState, getSetBound, isSameValue, type Value } from "./values";
32
32
 
33
33
  export interface DepthFirstOptions extends CheckOptions {
34
34
  maxDepth: number;
@@ -165,6 +165,13 @@ export const checkDepthFirst = (options: DepthFirstOptions): number => {
165
165
  if (assumptionStatus !== undefined) return assumptionStatus;
166
166
 
167
167
  const nextActions = prepared.getDescription().actions;
168
+ // Deviation from TLC: TLCExt#pickSuccessor casts the DFID checker to ModelChecker and fails, so tla-ts asks as model checking does.
169
+ runtime.getSuccessorAction = (state, next) =>
170
+ nextActions.find((action) =>
171
+ getSuccessors(action.expression, state, environment, action.scope).some((successor) =>
172
+ successor.state.every((value, index) => isSameValue(value, next[index])),
173
+ ),
174
+ );
168
175
  const statuses = new Map<bigint, number>();
169
176
  const fingerprintSet = { level: 1, leveled: 0, buckets: INITIAL_BUCKETS };
170
177
  const setStatus = (fingerprint: bigint, status: number) => {
@@ -100,6 +100,13 @@ interface EnvironmentOptions {
100
100
  version?: TlcVersion;
101
101
  moduleOperators?: ModuleOperator[];
102
102
  readLine?: () => string | undefined;
103
+ runtimeInvariants?: RuntimeInvariant[];
104
+ }
105
+
106
+ export interface RuntimeInvariant {
107
+ name: string;
108
+ /** Undefined when the invariant names a definition of the root module. */
109
+ module: string | undefined;
103
110
  }
104
111
 
105
112
  export interface ResolvedModuleOperator extends ModuleOperator {
@@ -114,6 +121,7 @@ export interface Specification {
114
121
  startupDefinitions: Definition[];
115
122
  javaOverrides: JavaOverride[];
116
123
  moduleOperators: ResolvedModuleOperator[];
124
+ runtimeInvariants: RuntimeInvariant[];
117
125
  rootName: string;
118
126
  }
119
127
 
@@ -1031,6 +1039,15 @@ export const createEnvironment = (
1031
1039
  );
1032
1040
  linkOrder.push(...linkOrder.splice(linkOrder.indexOf(linkedRoot), 1));
1033
1041
  if (warnings.length > 0 && !options.isSanyReported) options.print(formatSanyWarnings(warnings));
1042
+ const runtimeInvariants = options.runtimeInvariants ?? [];
1043
+ runtimeInvariants.forEach((invariant) => {
1044
+ if (invariant.module === undefined) return;
1045
+ linkedModules.set(root.name, linkedRoot);
1046
+ const linked = getLinkedModule(invariant.module, root.name);
1047
+ linkOrder.splice(linkOrder.indexOf(linked), 1);
1048
+ const definition = definitions.get(linked.visible.get(invariant.name)?.key ?? invariant.name);
1049
+ if (definition) definitions.set(invariant.name, definition);
1050
+ });
1034
1051
  linkedRoot.visible.forEach((symbol, name) => {
1035
1052
  const definition = definitions.get(symbol.key);
1036
1053
  if (definition && symbol.key !== name) definitions.set(name, definition);
@@ -1171,6 +1188,7 @@ export const createEnvironment = (
1171
1188
  ),
1172
1189
  javaOverrides: linkOrder.flatMap((linked) => javaOverrides.get(linked.module.name) ?? []),
1173
1190
  moduleOperators,
1191
+ runtimeInvariants,
1174
1192
  rootName: root.name,
1175
1193
  };
1176
1194
  };
package/src/evaluate.ts CHANGED
@@ -615,12 +615,16 @@ export const bindLazyArguments = (
615
615
  typeof value.domain === "object" && value.domain.kind === "ProductSet"
616
616
  ? value.domain.factors
617
617
  : [];
618
- // Deviation from TLC: FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores a longer one.
618
+ if (elements === undefined) {
619
+ throw new TlaEvaluationError(
620
+ `Attempted to apply a function to an argument not in its domain.\n${describeRange(expression.function)}`,
621
+ );
622
+ }
623
+ // Deviation from TLC: Tool#getFcnContext indexes past an argument tuple shorter than the bounds and ignores a longer one.
619
624
  const createListError = () =>
620
625
  new TlaEvaluationError(
621
626
  `In applying the function\n${prettyPrint(formatValue(value))},\nthe argument list is:\n${prettyPrint(formatValue(argument))}\nwhich does not match its formal parameter.\n`,
622
627
  );
623
- if (elements === undefined) throw createListError();
624
628
  bounds.forEach((bound, index) => {
625
629
  if (index >= elements.length) throw createListError();
626
630
  const element = elements[index];
@@ -1177,7 +1181,9 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1177
1181
  }
1178
1182
  const builtin = context.environment.builtins.get(name);
1179
1183
  if (builtin?.arity === 0) return builtin.evaluate([], context);
1180
- throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
1184
+ throw new TlaEvaluationError(
1185
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1186
+ );
1181
1187
  };
1182
1188
 
1183
1189
  export const getReevaluatedDefinitions = (
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,