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.
package/dist/worker.cjs CHANGED
@@ -6,7 +6,7 @@
6
6
  * This source code is licensed under the MIT license found in the
7
7
  * LICENSE file in the root directory of this source tree.
8
8
  */
9
- const e={success:0,assumptionViolation:10,deadlock:11,safetyViolation:12,livenessViolation:13,assertViolation:14,specEvaluationFailure:75,safetyEvaluationFailure:76,livenessEvaluationFailure:77,specParseError:150,configParseError:151,error:255},t=new Map([...[...Array.from({length:24},(e,t)=>2222+t),2272,2273,2274,2280,2281,...Array.from({length:7},(e,t)=>5001+t)].map(t=>[t,e.configParseError]),[2253,e.livenessEvaluationFailure],[2109,e.specEvaluationFailure],[2115,e.specEvaluationFailure],[2103,e.specEvaluationFailure],[2147,e.specEvaluationFailure],[2111,e.safetyEvaluationFailure],[2146,e.safetyEvaluationFailure],[2107,e.safetyViolation],[2110,e.safetyViolation],[2112,e.livenessViolation],[2113,e.livenessViolation],[2116,e.livenessViolation],[2108,e.livenessViolation],[2114,e.deadlock],[2104,e.assumptionViolation],[2105,e.assumptionViolation],[2404,e.assumptionViolation],[2405,e.assumptionViolation],[2780,e.assumptionViolation],[2132,e.assertViolation],[2171,e.specParseError],[3002,e.specParseError]]),n=n=>t.get(n)??e.error,r=/* @__PURE__ */ new WeakMap,i=(e,t)=>(e instanceof Error&&!r.has(e)&&r.set(e,t),e),a=e=>r.get(e),o=t=>{try{return t()}catch(t){throw i(t,e.error)}},s=e=>{let t=o(e);return t&&{branches:t.branches,solutions:t.solutions,addInitialState:(e,n,r)=>o(()=>t.addInitialState(e,n,r)),addState:(e,n,r,i)=>o(()=>t.addState(e,n,r,i)),storeState:t.storeState,findViolation:()=>o(()=>t.findViolation()),getViolatedProperties:(e,n)=>o(()=>t.getViolatedProperties(e,n))}},c=e=>`TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a ${e}\n: `,l=c(`java.lang.RuntimeException`),u=c(`tlc2.tool.EvalException`),ee=e=>e instanceof RangeError&&e.message===`Maximum call stack size exceeded`||e instanceof SyntaxError&&e.message.endsWith(`: Stack overflow`);var d=class extends Error{constructor(e,t){super(e,{cause:t}),this.name=`TlaError`}},f=class extends d{failure;sany;constructor(e,t,n,r){super(e,t),this.name=`TlaSyntaxError`,this.failure=n,this.sany=r}},p=class extends f{location;parseError;constructor(e,t,n){super(e),this.location=t,this.parseError=n}},te=class extends p{constructor(e,t,n=!0){super(`Cannot find source file for module ${e} imported in module ${t}.`,n?t:void 0)}};const m=(e,t=!1,n,r=[])=>new f(e.map(e=>`${e.location}\n\n${e.message}`).join(`
9
+ const e={success:0,assumptionViolation:10,deadlock:11,safetyViolation:12,livenessViolation:13,assertViolation:14,specEvaluationFailure:75,safetyEvaluationFailure:76,livenessEvaluationFailure:77,specParseError:150,configParseError:151,error:255},t=new Map([...[...Array.from({length:24},(e,t)=>2222+t),2272,2273,2274,2280,2281,...Array.from({length:7},(e,t)=>5001+t)].map(t=>[t,e.configParseError]),[2253,e.livenessEvaluationFailure],[2109,e.specEvaluationFailure],[2115,e.specEvaluationFailure],[2103,e.specEvaluationFailure],[2147,e.specEvaluationFailure],[2111,e.safetyEvaluationFailure],[2146,e.safetyEvaluationFailure],[2107,e.safetyViolation],[2110,e.safetyViolation],[2112,e.livenessViolation],[2113,e.livenessViolation],[2116,e.livenessViolation],[2108,e.livenessViolation],[2114,e.deadlock],[2104,e.assumptionViolation],[2105,e.assumptionViolation],[2404,e.assumptionViolation],[2405,e.assumptionViolation],[2780,e.assumptionViolation],[2132,e.assertViolation],[2171,e.specParseError],[3002,e.specParseError]]),n=n=>t.get(n)??e.error,r=/* @__PURE__ */ new WeakMap,i=(e,t)=>(e instanceof Error&&!r.has(e)&&r.set(e,t),e),a=e=>r.get(e),o=t=>{try{return t()}catch(t){throw i(t,e.error)}},s=e=>{let t=o(e);return t&&{branches:t.branches,solutions:t.solutions,addInitialState:(e,n,r)=>o(()=>t.addInitialState(e,n,r)),addState:(e,n,r,i)=>o(()=>t.addState(e,n,r,i)),storeState:t.storeState,getStateCounts:t.getStateCounts,findViolation:()=>o(()=>t.findViolation()),getViolatedProperties:(e,n)=>o(()=>t.getViolatedProperties(e,n))}},c=e=>`TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a ${e}\n: `,l=c(`java.lang.RuntimeException`),u=c(`tlc2.tool.EvalException`),ee=e=>e instanceof RangeError&&e.message===`Maximum call stack size exceeded`||e instanceof SyntaxError&&e.message.endsWith(`: Stack overflow`);var d=class extends Error{constructor(e,t){super(e,{cause:t}),this.name=`TlaError`}},f=class extends d{failure;sany;constructor(e,t,n,r){super(e,t),this.name=`TlaSyntaxError`,this.failure=n,this.sany=r}},p=class extends f{location;parseError;constructor(e,t,n){super(e),this.location=t,this.parseError=n}},te=class extends p{constructor(e,t,n=!0){super(`Cannot find source file for module ${e} imported in module ${t}.`,n?t:void 0)}};const m=(e,t=!1,n,r=[])=>new f(e.map(e=>`${e.location}\n\n${e.message}`).join(`
10
10
 
11
11
  `),void 0,void 0,{errors:e,warnings:r,isFatal:t,parseError:n}),h=(e,t)=>m([{location:`In module ${t}`,message:`Cannot find source file for module ${e} imported in module ${t}.`}],!0),g=e=>`*** Warnings: ${e.length}\n\n${e.map(e=>`${e.location}\n\n${e.message}\n\n\n`).join(`
12
12
  `)}`,_=e=>`line ${e.start.line}, col ${e.start.column} to line ${e.end.line}, col ${e.end.column} of module ${e.module}`,ne=(e,t)=>m([{location:_(t),message:e}]);var v=class extends d{constructor(e,t){super(e,t),this.name=`TlaConfigError`}},y=class extends d{constructor(e,t){super(e,t),this.name=`TlaEvaluationError`}};const b=`This was a Java StackOverflowError. It was probably the result
package/dist/worker.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * This source code is licensed under the MIT license found in the
7
7
  * LICENSE file in the root directory of this source tree.
8
8
  */
9
- const e={success:0,assumptionViolation:10,deadlock:11,safetyViolation:12,livenessViolation:13,assertViolation:14,specEvaluationFailure:75,safetyEvaluationFailure:76,livenessEvaluationFailure:77,specParseError:150,configParseError:151,error:255},t=new Map([...[...Array.from({length:24},(e,t)=>2222+t),2272,2273,2274,2280,2281,...Array.from({length:7},(e,t)=>5001+t)].map(t=>[t,e.configParseError]),[2253,e.livenessEvaluationFailure],[2109,e.specEvaluationFailure],[2115,e.specEvaluationFailure],[2103,e.specEvaluationFailure],[2147,e.specEvaluationFailure],[2111,e.safetyEvaluationFailure],[2146,e.safetyEvaluationFailure],[2107,e.safetyViolation],[2110,e.safetyViolation],[2112,e.livenessViolation],[2113,e.livenessViolation],[2116,e.livenessViolation],[2108,e.livenessViolation],[2114,e.deadlock],[2104,e.assumptionViolation],[2105,e.assumptionViolation],[2404,e.assumptionViolation],[2405,e.assumptionViolation],[2780,e.assumptionViolation],[2132,e.assertViolation],[2171,e.specParseError],[3002,e.specParseError]]),n=n=>t.get(n)??e.error,r=/* @__PURE__ */ new WeakMap,i=(e,t)=>(e instanceof Error&&!r.has(e)&&r.set(e,t),e),a=e=>r.get(e),o=t=>{try{return t()}catch(t){throw i(t,e.error)}},s=e=>{let t=o(e);return t&&{branches:t.branches,solutions:t.solutions,addInitialState:(e,n,r)=>o(()=>t.addInitialState(e,n,r)),addState:(e,n,r,i)=>o(()=>t.addState(e,n,r,i)),storeState:t.storeState,findViolation:()=>o(()=>t.findViolation()),getViolatedProperties:(e,n)=>o(()=>t.getViolatedProperties(e,n))}},c=e=>`TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a ${e}\n: `,l=c(`java.lang.RuntimeException`),u=c(`tlc2.tool.EvalException`),ee=e=>e instanceof RangeError&&e.message===`Maximum call stack size exceeded`||e instanceof SyntaxError&&e.message.endsWith(`: Stack overflow`);var d=class extends Error{constructor(e,t){super(e,{cause:t}),this.name=`TlaError`}},f=class extends d{failure;sany;constructor(e,t,n,r){super(e,t),this.name=`TlaSyntaxError`,this.failure=n,this.sany=r}},p=class extends f{location;parseError;constructor(e,t,n){super(e),this.location=t,this.parseError=n}},te=class extends p{constructor(e,t,n=!0){super(`Cannot find source file for module ${e} imported in module ${t}.`,n?t:void 0)}};const m=(e,t=!1,n,r=[])=>new f(e.map(e=>`${e.location}\n\n${e.message}`).join(`
9
+ const e={success:0,assumptionViolation:10,deadlock:11,safetyViolation:12,livenessViolation:13,assertViolation:14,specEvaluationFailure:75,safetyEvaluationFailure:76,livenessEvaluationFailure:77,specParseError:150,configParseError:151,error:255},t=new Map([...[...Array.from({length:24},(e,t)=>2222+t),2272,2273,2274,2280,2281,...Array.from({length:7},(e,t)=>5001+t)].map(t=>[t,e.configParseError]),[2253,e.livenessEvaluationFailure],[2109,e.specEvaluationFailure],[2115,e.specEvaluationFailure],[2103,e.specEvaluationFailure],[2147,e.specEvaluationFailure],[2111,e.safetyEvaluationFailure],[2146,e.safetyEvaluationFailure],[2107,e.safetyViolation],[2110,e.safetyViolation],[2112,e.livenessViolation],[2113,e.livenessViolation],[2116,e.livenessViolation],[2108,e.livenessViolation],[2114,e.deadlock],[2104,e.assumptionViolation],[2105,e.assumptionViolation],[2404,e.assumptionViolation],[2405,e.assumptionViolation],[2780,e.assumptionViolation],[2132,e.assertViolation],[2171,e.specParseError],[3002,e.specParseError]]),n=n=>t.get(n)??e.error,r=/* @__PURE__ */ new WeakMap,i=(e,t)=>(e instanceof Error&&!r.has(e)&&r.set(e,t),e),a=e=>r.get(e),o=t=>{try{return t()}catch(t){throw i(t,e.error)}},s=e=>{let t=o(e);return t&&{branches:t.branches,solutions:t.solutions,addInitialState:(e,n,r)=>o(()=>t.addInitialState(e,n,r)),addState:(e,n,r,i)=>o(()=>t.addState(e,n,r,i)),storeState:t.storeState,getStateCounts:t.getStateCounts,findViolation:()=>o(()=>t.findViolation()),getViolatedProperties:(e,n)=>o(()=>t.getViolatedProperties(e,n))}},c=e=>`TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a ${e}\n: `,l=c(`java.lang.RuntimeException`),u=c(`tlc2.tool.EvalException`),ee=e=>e instanceof RangeError&&e.message===`Maximum call stack size exceeded`||e instanceof SyntaxError&&e.message.endsWith(`: Stack overflow`);var d=class extends Error{constructor(e,t){super(e,{cause:t}),this.name=`TlaError`}},f=class extends d{failure;sany;constructor(e,t,n,r){super(e,t),this.name=`TlaSyntaxError`,this.failure=n,this.sany=r}},p=class extends f{location;parseError;constructor(e,t,n){super(e),this.location=t,this.parseError=n}},te=class extends p{constructor(e,t,n=!0){super(`Cannot find source file for module ${e} imported in module ${t}.`,n?t:void 0)}};const m=(e,t=!1,n,r=[])=>new f(e.map(e=>`${e.location}\n\n${e.message}`).join(`
10
10
 
11
11
  `),void 0,void 0,{errors:e,warnings:r,isFatal:t,parseError:n}),h=(e,t)=>m([{location:`In module ${t}`,message:`Cannot find source file for module ${e} imported in module ${t}.`}],!0),g=e=>`*** Warnings: ${e.length}\n\n${e.map(e=>`${e.location}\n\n${e.message}\n\n\n`).join(`
12
12
  `)}`,_=e=>`line ${e.start.line}, col ${e.start.column} to line ${e.end.line}, col ${e.end.column} of module ${e.module}`,ne=(e,t)=>m([{location:_(t),message:e}]);var v=class extends d{constructor(e,t){super(e,t),this.name=`TlaConfigError`}},y=class extends d{constructor(e,t){super(e,t),this.name=`TlaEvaluationError`}};const b=`This was a Java StackOverflowError. It was probably the result
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.10-dev.d618a2d79",
3
+ "version": "0.0.10-dev.f08db3b1f",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/bags.ts CHANGED
@@ -4,7 +4,6 @@ import {
4
4
  defineConstant,
5
5
  defineHigherOrderOperator,
6
6
  defineOperator,
7
- getJavaClassName,
8
7
  getKindString,
9
8
  getOperator,
10
9
  getValue,
@@ -85,34 +84,43 @@ const findCount = (functionValue: FunctionValue, element: Value) => {
85
84
  return position === -1 ? undefined : functionValue.range[position];
86
85
  };
87
86
 
88
- const toCount = (value: Value) => {
87
+ // Deviation from TLC: Bags.java casts a count to IntValue and leaks the ClassCastException, where tla-ts reports the argument as not a bag.
88
+ const toCount = (value: Value, createError: () => TlaModuleError) => {
89
89
  if (typeof value === "number") return value;
90
- const javaClass = `tlc2.value.impl.${getJavaClassName(value)}`;
91
- throw new TlaEvaluationError(
92
- `class ${javaClass} cannot be cast to class tlc2.value.impl.IntValue (${javaClass} and tlc2.value.impl.IntValue are in unnamed module of loader 'app')`,
93
- );
90
+ throw createError();
94
91
  };
95
92
 
96
- const addCounts = (left: Value, right: Value) => {
97
- const sum = toCount(left) + toCount(right);
93
+ const addCounts = (left: Value, right: Value, createError: () => TlaModuleError) => {
94
+ const sum = toCount(left, createError) + toCount(right, createError);
98
95
  if (isOutOfRange(sum)) throw createOverflowError(`${left}+${right}`);
99
96
  return sum;
100
97
  };
101
98
 
102
- // Deviation from TLC: Bags.java subtracts counts as Java ints, which wrap; this overflows like -.
103
- const subtractCounts = (functionValue: FunctionValue, index: number, other: FunctionValue) => {
104
- const count = toCount(functionValue.range[index]);
99
+ // Deviation from TLC: Bags#BagDiff subtracts counts as Java ints that wrap, where tla-ts reports the overflow as - does.
100
+ const subtractCounts = (
101
+ functionValue: FunctionValue,
102
+ index: number,
103
+ other: FunctionValue,
104
+ createErrors: (() => TlaModuleError)[],
105
+ ) => {
106
+ const count = toCount(functionValue.range[index], createErrors[0]);
105
107
  const removed = findCount(other, functionValue.domain[index]);
106
108
  if (removed === undefined) return count;
107
- const difference = count - toCount(removed);
109
+ const difference = count - toCount(removed, createErrors[1]);
108
110
  if (isOutOfRange(difference)) throw createOverflowError(`${count}-${removed}`);
109
111
  return difference;
110
112
  };
111
113
 
112
114
  // BagCup looks up a key of its second bag only among the keys of its first.
113
- const addToBag = (pairs: [Value, Value][], key: Value, count: Value, end = pairs.length) => {
115
+ const addToBag = (
116
+ pairs: [Value, Value][],
117
+ key: Value,
118
+ count: Value,
119
+ createError: () => TlaModuleError,
120
+ end = pairs.length,
121
+ ) => {
114
122
  const existing = pairs.slice(0, end).find((pair) => isEqualLikeTlc(key, pair[0]));
115
- if (existing) existing[1] = addCounts(existing[1], count);
123
+ if (existing) existing[1] = addCounts(existing[1], count, createError);
116
124
  else pairs.push([key, count]);
117
125
  };
118
126
 
@@ -130,11 +138,10 @@ export const createBagsOperators = (builtins: ReadonlyMap<string, Builtin>): Bui
130
138
  defineOperator("BagCardinality", 1, (args) => {
131
139
  const bag = getValue(args, 0, "BagCardinality");
132
140
  const functionValue = getFunction(args, 0, "BagCardinality");
141
+ const createError = () => createWrongValueError("BagCardinality", "a bag", bag);
133
142
  return functionValue.range.reduce<number>((total, count) => {
134
- if (typeof count !== "number" || count <= 0) {
135
- throw createWrongValueError("BagCardinality", "a bag", bag);
136
- }
137
- return addCounts(total, count);
143
+ if (typeof count !== "number" || count <= 0) throw createError();
144
+ return addCounts(total, count, createError);
138
145
  }, 0);
139
146
  }),
140
147
  defineOperator("BagIn", 2, (args) => {
@@ -147,8 +154,10 @@ export const createBagsOperators = (builtins: ReadonlyMap<string, Builtin>): Bui
147
154
  const left = getAddedBag(args, functions, 0);
148
155
  const right = getAddedBag(args, functions, 1);
149
156
  const pairs = getPairs(left);
157
+ const createError = () =>
158
+ createModuleArgumentError("second", "(+)", "bag", getValue(args, 1, "(+)"));
150
159
  right.domain.forEach((key, index) =>
151
- addToBag(pairs, key, right.range[index], left.domain.length),
160
+ addToBag(pairs, key, right.range[index], createError, left.domain.length),
152
161
  );
153
162
  return createFunction(pairs);
154
163
  }),
@@ -159,9 +168,13 @@ export const createBagsOperators = (builtins: ReadonlyMap<string, Builtin>): Bui
159
168
  const right = toFunction(rightValue);
160
169
  if (!left) throw createModuleArgumentError("first", "(-)", "bag", leftValue);
161
170
  if (!right) throw createModuleArgumentError("second", "(-)", "bag", rightValue);
171
+ const createErrors = [
172
+ () => createModuleArgumentError("first", "(-)", "bag", leftValue),
173
+ () => createModuleArgumentError("second", "(-)", "bag", rightValue),
174
+ ];
162
175
  return createFunction(
163
176
  left.domain.flatMap((key, index): [Value, Value][] => {
164
- const count = subtractCounts(left, index, right);
177
+ const count = subtractCounts(left, index, right, createErrors);
165
178
  return count > 0 ? [[key, count]] : [];
166
179
  }),
167
180
  );
@@ -172,20 +185,20 @@ export const createBagsOperators = (builtins: ReadonlyMap<string, Builtin>): Bui
172
185
  createWrongValueError("BagUnion", "a finite enumerable set", set),
173
186
  );
174
187
  if (elements.length < 2) return elements[0] ?? EMPTY_BAG;
188
+ const createUnionError = () =>
189
+ new TlaModuleError(
190
+ `Attempted to apply BagUnion to the following set, whose\nelement is not a bag:\n${formatValue(set)}`,
191
+ );
175
192
  const getBag = (element: Value) => {
176
193
  const functionValue = toFunction(element);
177
- if (!functionValue) {
178
- throw new TlaModuleError(
179
- `Attempted to apply BagUnion to the following set, whose\nelement is not a bag:\n${formatValue(set)}`,
180
- );
181
- }
194
+ if (!functionValue) throw createUnionError();
182
195
  return functionValue;
183
196
  };
184
197
  const pairs = getPairs(getBag(elements[0]));
185
198
  elements.slice(1).forEach((element) => {
186
199
  const functionValue = getBag(element);
187
200
  functionValue.domain.forEach((key, index) =>
188
- addToBag(pairs, key, functionValue.range[index]),
201
+ addToBag(pairs, key, functionValue.range[index], createUnionError),
189
202
  );
190
203
  });
191
204
  return createFunction(pairs);
@@ -197,9 +210,14 @@ export const createBagsOperators = (builtins: ReadonlyMap<string, Builtin>): Bui
197
210
  const right = toFunction(rightValue);
198
211
  if (!left) throw createWrongValueError("\\sqsubseteq", FINITE_FUNCTION, leftValue);
199
212
  if (!right) throw createWrongValueError("\\sqsubseteq", FINITE_FUNCTION, rightValue);
213
+ const createLeftError = () => createWrongValueError("\\sqsubseteq", "a bag", leftValue);
214
+ const createRightError = () => createWrongValueError("\\sqsubseteq", "a bag", rightValue);
200
215
  return left.domain.every((key, index) => {
201
216
  const count = findCount(right, key);
202
- return toCount(left.range[index]) <= (count === undefined ? 0 : toCount(count));
217
+ return (
218
+ toCount(left.range[index], createLeftError) <=
219
+ (count === undefined ? 0 : toCount(count, createRightError))
220
+ );
203
221
  });
204
222
  }),
205
223
  defineHigherOrderOperator("BagOfAll", 2, (args) => {
@@ -210,8 +228,9 @@ export const createBagsOperators = (builtins: ReadonlyMap<string, Builtin>): Bui
210
228
  throw createModuleArgumentError("second", "BagOfAll", "function with a finite domain", value);
211
229
  }
212
230
  const pairs: [Value, Value][] = [];
231
+ const createError = () => createModuleArgumentError("second", "BagOfAll", "bag", value);
213
232
  functionValue.domain.forEach((key, index) =>
214
- addToBag(pairs, operator.call([key]), functionValue.range[index]),
233
+ addToBag(pairs, operator.call([key]), functionValue.range[index], createError),
215
234
  );
216
235
  return createFunction(pairs);
217
236
  }),
package/src/check.ts CHANGED
@@ -206,7 +206,7 @@ export type CheckProgress =
206
206
  branches: number;
207
207
  /** Whether TLC checks the complete state graph. */
208
208
  isComplete: boolean;
209
- /** How many states of the graph each branch has. */
209
+ /** How many states the graphs of all branches have together. */
210
210
  states: number;
211
211
  statistics: SearchStatistics;
212
212
  }
@@ -415,6 +415,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
415
415
  key.startsWith(`${name}${KEY_SEPARATOR}`),
416
416
  ),
417
417
  });
418
+ const getCoverage = () =>
419
+ coverage?.relations.some((relation) => relation.kind === "next")
420
+ ? getCoverageReport(
421
+ coverage,
422
+ environment,
423
+ specification.variableLocations,
424
+ search?.getTlcOrder() ?? [],
425
+ )
426
+ : undefined;
418
427
  const createResult = (
419
428
  status: CheckStatus,
420
429
  violation?: ReportedViolation,
@@ -435,14 +444,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
435
444
  initialStates: computedInitialStates,
436
445
  outDegrees: undefined,
437
446
  fingerprintDistance: undefined,
438
- coverage: coverage?.relations.some((relation) => relation.kind === "next")
439
- ? getCoverageReport(
440
- coverage,
441
- environment,
442
- specification.variableLocations,
443
- search?.getTlcOrder() ?? [],
444
- )
445
- : undefined,
447
+ coverage: getCoverage(),
446
448
  ...(traceSpec !== undefined && { traceSpec }),
447
449
  };
448
450
  };
@@ -466,7 +468,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
466
468
  : getFingerprintDistance(runtime.distinctStates, runtime.generatedStates, (visit) =>
467
469
  visit(
468
470
  search
469
- ? search.getStoredFingerprints(states, fingerprintStates)
471
+ ? search.getStoredFingerprints(
472
+ exploredStates.length === 0 ? states : states.concat(exploredStates),
473
+ exploredStates.length === 0
474
+ ? fingerprintStates
475
+ : fingerprintStates.concat(exploredFingerprintStates),
476
+ )
470
477
  : BigInt64Array.from(states, runtime.getFingerprint),
471
478
  ),
472
479
  ),
@@ -479,6 +486,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
479
486
  () => created.order.getDeclarationOrder("variable"),
480
487
  options.onProgress,
481
488
  specification.moduleOperators,
489
+ specification.runtimeInvariants,
482
490
  );
483
491
  const findViolatedAssumption = () =>
484
492
  findAssumptionViolation(specification.assumptions, environment);
@@ -555,12 +563,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
555
563
  const getFingerprintState = search.getFingerprintState;
556
564
  // Tool's constructor splits the next-state relation into actions before TLC checks anything.
557
565
  const nextActions = getDescription().actions;
558
- runtime.getSuccessorAction = (state, next) =>
559
- nextActions.find((action) =>
560
- getSuccessors(action.expression, state, environment, action.scope).some((successor) =>
561
- successor.state.every((value, index) => isSameValue(value, next[index])),
562
- ),
563
- );
564
566
  const addCoverageRelations = (kind: "init" | "next", actions: SpecAction[]) =>
565
567
  actions.map((action): CoveredAction => ({
566
568
  ...action,
@@ -610,6 +612,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
610
612
  );
611
613
  return successors;
612
614
  };
615
+ // TLC generates the successors of each action again, which its coverage counts.
616
+ const findSuccessorAction = (state: Value[], isMatch: (successor: Successor) => boolean) =>
617
+ coverage
618
+ ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
619
+ : nextActions.find((item) =>
620
+ getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
621
+ );
622
+ runtime.getSuccessorAction = (state, next) =>
623
+ findSuccessorAction(state, (successor) =>
624
+ successor.state.every((value, index) => isSameValue(value, next[index])),
625
+ );
613
626
  const rejectIncompleteInitialState = (partial: (Value | undefined)[]) => {
614
627
  throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
615
628
  };
@@ -628,8 +641,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
628
641
  return (state: Value[], callStack: CallStack | undefined) => {
629
642
  fingerprintReplayed(state, getFingerprintState(state), callStack);
630
643
  const fingerprintState = getFingerprintState(state);
644
+ const hash = getStateHash(fingerprintState);
631
645
  const isSeen =
632
- findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1 ||
646
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
647
+ isExplored(hash, fingerprintState) ||
633
648
  replayed.some((seen) => isSameState(seen, fingerprintState));
634
649
  if (isSeen) return false;
635
650
  replayed.push(fingerprintState);
@@ -716,28 +731,38 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
716
731
  if (spec.next === undefined) return successors;
717
732
  const livenessSource = current.livenessSource;
718
733
  current.livenessSource = source;
734
+ const addSuccessor = (successor: Value[]) => {
735
+ canonicalizeState(successor);
736
+ const isInModel =
737
+ search.satisfiesConstraints(successor, state) &&
738
+ search.satisfiesActionConstraints(state, successor);
739
+ if (!isInModel) return;
740
+ const fingerprintState = getFingerprintState(successor);
741
+ const hash = getStateHash(fingerprintState);
742
+ const index = findStateIndex(seenStates, hash, fingerprintState);
743
+ successors.push({
744
+ index: index === -1 ? getPendingIndex(hash, fingerprintState) : index,
745
+ state: successor,
746
+ });
747
+ };
719
748
  try {
720
- forEachSuccessor(
721
- spec.next,
722
- state,
723
- environment,
724
- (successor) => {
725
- canonicalizeState(successor.state);
726
- const isInModel =
727
- search.satisfiesConstraints(successor.state, state) &&
728
- search.satisfiesActionConstraints(state, successor.state);
729
- if (!isInModel) return false;
730
- const fingerprintState = getFingerprintState(successor.state);
731
- const hash = getStateHash(fingerprintState);
732
- const index = findStateIndex(seenStates, hash, fingerprintState);
733
- successors.push({
734
- index: index === -1 ? getPendingIndex(hash, fingerprintState) : index,
735
- state: successor.state,
736
- });
737
- return false;
738
- },
739
- spec.scope,
740
- );
749
+ // TLC's coverage counts the successors of each action the graph generates again.
750
+ if (coverage) {
751
+ coverageActions.forEach((action) =>
752
+ walkCoveredSuccessors(action, state, addSuccessor),
753
+ );
754
+ } else {
755
+ forEachSuccessor(
756
+ spec.next,
757
+ state,
758
+ environment,
759
+ (successor) => {
760
+ addSuccessor(successor.state);
761
+ return false;
762
+ },
763
+ spec.scope,
764
+ );
765
+ }
741
766
  } finally {
742
767
  current.livenessSource = livenessSource;
743
768
  }
@@ -756,6 +781,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
756
781
  const actions: (string | undefined)[] = [];
757
782
  const depths: number[] = [];
758
783
  const seenStates = createStateTable(fingerprintStates);
784
+ const exploredStates: Value[][] = [];
785
+ const exploredFingerprintStates: Value[][] = [];
786
+ let exploredTable: StateTable | undefined;
787
+ const isExplored = (hash: number, fingerprintState: Value[]) =>
788
+ exploredTable !== undefined && findStateIndex(exploredTable, hash, fingerprintState) !== -1;
759
789
  const pendingFingerprintStates: Value[][] = [];
760
790
  let pendingStates: StateTable | undefined;
761
791
  const getPendingIndex = (hash: number, fingerprintState: Value[]) => {
@@ -868,7 +898,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
868
898
  };
869
899
  let unstoredFingerprint: Value[] | undefined;
870
900
  const countDistinctState = (depth: number) => {
871
- runtime.distinctStates = states.length + 1;
901
+ runtime.distinctStates = states.length + exploredStates.length + 1;
872
902
  searchDepth = Math.max(searchDepth, depth);
873
903
  runtime.diameter = Math.max(runtime.diameter, depth);
874
904
  };
@@ -909,18 +939,27 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
909
939
  tracedSteps,
910
940
  captureOutput,
911
941
  getInitialStates: getSpecInitialStates,
912
- findSuccessorAction: (state, isMatch) =>
913
- coverage
914
- ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
915
- : nextActions.find((item) =>
916
- getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
917
- ),
942
+ findSuccessorAction,
918
943
  });
919
944
  const getPath = (index: number): Value[][] =>
920
945
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
946
+ // TLC adds a successor's fingerprint to its set before it checks the invariants of the successor.
921
947
  runtime.isSeen = (state) => {
922
948
  const fingerprintState = getFingerprintState(state);
923
- return findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1;
949
+ const hash = getStateHash(fingerprintState);
950
+ return (
951
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
952
+ isExplored(hash, fingerprintState) ||
953
+ (unstoredFingerprint !== undefined && isSameState(unstoredFingerprint, fingerprintState))
954
+ );
955
+ };
956
+ runtime.markExplored = (state) => {
957
+ const fingerprintState = getFingerprintState(state);
958
+ exploredTable ??= createStateTable(exploredFingerprintStates);
959
+ markSeenState(exploredTable, getStateHash(fingerprintState), exploredStates.length);
960
+ exploredStates.push(state);
961
+ exploredFingerprintStates.push(fingerprintState);
962
+ runtime.distinctStates++;
924
963
  };
925
964
  runtime.getBehavior = (state) => {
926
965
  const index = state === current.candidate ? -1 : states.indexOf(state);
@@ -1025,7 +1064,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1025
1064
  fingerprintModelState(fingerprintState);
1026
1065
  successor.state.forEach(markFingerprinted);
1027
1066
  }
1028
- return { fingerprintState, hash, isInModel, existing: isInModel ? foundIndex : -1 };
1067
+ const existing = isInModel ? foundIndex : -1;
1068
+ return {
1069
+ fingerprintState,
1070
+ hash,
1071
+ isInModel,
1072
+ existing,
1073
+ isSeen: existing !== -1 || (isInModel && isExplored(hash, fingerprintState)),
1074
+ };
1029
1075
  };
1030
1076
  const visitSuccessor = (
1031
1077
  index: number,
@@ -1044,7 +1090,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1044
1090
  stateWriter?.writeSuccessor(
1045
1091
  source,
1046
1092
  getGraphState(successor.state, depths[index] + 1),
1047
- found.existing !== -1,
1093
+ found.isSeen,
1048
1094
  action && getGraphAction(action),
1049
1095
  );
1050
1096
  }
@@ -1066,7 +1112,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1066
1112
  const isStored = stored.every((value, position) => value === successor.state[position]);
1067
1113
  liveSuccessors.push({ index: found.existing, state: isStored ? stored : successor.state });
1068
1114
  }
1069
- const isNew = found.isInModel && found.existing === -1;
1115
+ if (found.isSeen && found.existing === -1 && liveness) {
1116
+ liveSuccessors.push({
1117
+ index: getPendingIndex(found.hash, found.fingerprintState),
1118
+ state: successor.state,
1119
+ });
1120
+ }
1121
+ const isNew = found.isInModel && !found.isSeen;
1070
1122
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1071
1123
  unstoredFingerprint = isNew ? found.fingerprintState : undefined;
1072
1124
  if (isNew) {
@@ -1074,7 +1126,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1074
1126
  newStateCount++;
1075
1127
  if (coverage) coverage.secondary[coveredNode]++;
1076
1128
  }
1077
- if (found.existing === -1) {
1129
+ if (!found.isSeen) {
1078
1130
  try {
1079
1131
  const violated = search.findViolatedInvariant(successor.state, state);
1080
1132
  const violation = violated && { name: violated.name, ...traces.getTrace(index, successor) };
@@ -1156,7 +1208,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1156
1208
  kind: "liveness-started",
1157
1209
  branches: liveness.branches,
1158
1210
  isComplete: true,
1159
- states: typed.distinctStates,
1211
+ // The tier stores and expands every successor, so the graph of each branch has every state.
1212
+ states: liveness.branches * typed.distinctStates,
1160
1213
  statistics,
1161
1214
  });
1162
1215
  options.onProgress?.({ kind: "liveness-finished" });
@@ -1413,6 +1466,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1413
1466
  return {
1414
1467
  ...result,
1415
1468
  violation: appendTraceOutput(result.violation, live.lines),
1469
+ // TLC adds the state to the behavior graph before it reports the coverage.
1470
+ coverage: getCoverage(),
1416
1471
  ...(live.result && { liveCallStack: live.result }),
1417
1472
  };
1418
1473
  }
@@ -1544,24 +1599,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1544
1599
  const startedAt = performance.now();
1545
1600
  const periodic = {
1546
1601
  at: startedAt + PERIODIC_START,
1547
- size: 1,
1602
+ // The size of each branch's graph when TLC last checked it, which starts at 1.
1603
+ sizes: liveness?.getStateCounts().map(() => 1) ?? [],
1548
1604
  time: 0,
1549
1605
  coverageCount: Math.trunc(options.coverage ?? 0),
1550
1606
  };
1551
- const findPeriodicViolation = (expanded: number) => {
1607
+ // TLC counts the states of the graphs of all branches, which can differ.
1608
+ const getGraphStates = (checker: LivenessChecker) =>
1609
+ checker.getStateCounts().reduce((sum, count) => sum + count, 0);
1610
+ const findPeriodicViolation = (checker: LivenessChecker) => {
1552
1611
  const now = performance.now();
1553
- const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1612
+ const counts = checker.getStateCounts();
1613
+ const isGrown = counts.some(
1614
+ (count, branch) =>
1615
+ (count - periodic.sizes[branch]) / periodic.sizes[branch] > LIVENESS_GROWTH,
1616
+ );
1554
1617
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1555
- periodic.size = expanded;
1556
- if (!liveness) return undefined;
1618
+ periodic.sizes = counts;
1557
1619
  options.onProgress?.({
1558
1620
  kind: "liveness-started",
1559
- branches: liveness.branches,
1621
+ branches: checker.branches,
1560
1622
  isComplete: false,
1561
- states: expanded,
1623
+ states: getGraphStates(checker),
1562
1624
  statistics: createResult("success"),
1563
1625
  });
1564
- const lasso = liveness.findViolation();
1626
+ const lasso = checker.findViolation();
1565
1627
  if (!lasso) options.onProgress?.({ kind: "liveness-finished" });
1566
1628
  periodic.time += performance.now() - now;
1567
1629
  return lasso;
@@ -1687,7 +1749,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1687
1749
  newStateCount = 0;
1688
1750
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1689
1751
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1690
- const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1752
+ const lasso = isPeriodic && liveness ? findPeriodicViolation(liveness) : undefined;
1691
1753
  if (liveness && lasso) return reportLasso(liveness, lasso);
1692
1754
  const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1693
1755
  periodic.coverageCount = isCoverageDue
@@ -1709,7 +1771,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1709
1771
  kind: "liveness-started",
1710
1772
  branches: finalLiveness.branches,
1711
1773
  isComplete: true,
1712
- states: runtime.distinctStates,
1774
+ // The tier that found the lasso stored and expanded every successor, so each graph has every state.
1775
+ states: typedLasso
1776
+ ? finalLiveness.branches * runtime.distinctStates
1777
+ : getGraphStates(finalLiveness),
1713
1778
  statistics: createResult("success"),
1714
1779
  });
1715
1780
  }