tla-ts 0.0.3-dev.e946acb → 0.0.3-dev.fb38eba

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/run-cli.ts CHANGED
@@ -19,12 +19,14 @@ import {
19
19
  TlaError,
20
20
  TlaEvaluationError,
21
21
  TlaProofError,
22
+ TlaSyntaxError,
22
23
  } from "./errors";
23
24
  import { EXIT_STATUS } from "./exit-codes";
24
25
  import type { LineRange } from "./obligation-generate";
25
26
  import { getAtPrefix, getLocusText } from "./obligation-expression";
26
27
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
27
28
  import { check } from "./parallel";
29
+ import { parseModule } from "./parser";
28
30
  import { prettyPrint } from "./pretty-print";
29
31
  import {
30
32
  formatProbability,
@@ -113,6 +115,11 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
113
115
  });
114
116
  };
115
117
 
118
+ const getTemporalHeadline = (names: string[]) =>
119
+ names.length === 1
120
+ ? `Error: Temporal property ${names[0]} was violated.\n`
121
+ : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
122
+
116
123
  const printResult = (result: CheckResult) => {
117
124
  if (result.failure) {
118
125
  console.log(`Error: ${result.failure.message}`);
@@ -140,10 +147,10 @@ const printResult = (result: CheckResult) => {
140
147
  "invariant-violation": isInitial
141
148
  ? `Error: Invariant ${name} is violated by the initial state:`
142
149
  : `Error: Invariant ${name} is violated.`,
143
- "property-violation": `Error: Property ${name} is violated.`,
150
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
144
151
  "liveness-violation":
145
152
  loopStart !== undefined
146
- ? `Error: Temporal property ${name} was violated.\n`
153
+ ? getTemporalHeadline(violation.properties ?? [name])
147
154
  : isInitial
148
155
  ? `Error: Property ${name} is violated by the initial state:`
149
156
  : `Error: Action property ${name} is violated.`,
@@ -152,6 +159,8 @@ const printResult = (result: CheckResult) => {
152
159
  if (violation.counts) console.log(violation.counts);
153
160
  console.log(headline);
154
161
  if (isInitial) printState(violation.trace[0].state);
162
+ else if (result.status === "property-violation")
163
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
155
164
  else if (loopStart === undefined) printTrace(violation.trace);
156
165
  else {
157
166
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -191,6 +200,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
191
200
  console.error(`Cannot find the specification file ${specPath}`);
192
201
  return EXIT_STATUS.configParseError;
193
202
  }
203
+ const source = readFileSync(specPath, "utf8");
204
+ const fileName = basename(specPath, ".tla");
205
+ const moduleName = parseModule(source).name;
206
+ if (moduleName !== fileName) {
207
+ throw new TlaSyntaxError(
208
+ `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
209
+ );
210
+ }
194
211
  const configPath =
195
212
  args.get("-config")?.[0] ??
196
213
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -220,7 +237,7 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
220
237
  workers: getWorkerCount(args.get("-workers")),
221
238
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
222
239
  seed: BigInt(seed),
223
- source: readFileSync(specPath, "utf8"),
240
+ source,
224
241
  config,
225
242
  onPause: () => readSync(0, Buffer.alloc(1)),
226
243
  loadModule: (name) => {
package/src/runtime.ts CHANGED
@@ -6,7 +6,7 @@ export interface CheckerRuntime {
6
6
  getBehavior: (state: Value[]) => Value[][];
7
7
  getSpecification: () => Value;
8
8
  counterExample: Value | undefined;
9
- setLivenessSource: (index: number) => void;
9
+ setLivenessSource: (index: number | undefined) => void;
10
10
  getCurrentState: () => Value[] | undefined;
11
11
  getFingerprint: (state: Value[]) => bigint;
12
12
  getRandom: () => JavaRandom;
@@ -1,4 +1,10 @@
1
- import type { Definition, Expression, SourceLocation, SourceRange } from "./ast";
1
+ import {
2
+ isLocallyResolved,
3
+ type Definition,
4
+ type Expression,
5
+ type SourceLocation,
6
+ type SourceRange,
7
+ } from "./ast";
2
8
  import type { ModelConfig } from "./config";
3
9
  import type { InstanceAction } from "./environment";
4
10
  import { TlaError } from "./errors";
@@ -10,7 +16,6 @@ import {
10
16
  formatRange,
11
17
  getDefinition,
12
18
  isConstantLevel,
13
- isLocallyResolved,
14
19
  lookupScope,
15
20
  resolveGlobalOperator,
16
21
  type Closure,
@@ -1,15 +1,15 @@
1
- import type {
2
- Bound,
3
- Definition,
4
- Expression,
5
- Instance,
6
- Module,
7
- OperatorParam,
8
- Selector,
9
- SourceLocation,
1
+ import {
2
+ getChildren,
3
+ type Bound,
4
+ type Definition,
5
+ type Expression,
6
+ type Instance,
7
+ type Module,
8
+ type OperatorParam,
9
+ type Selector,
10
+ type SourceLocation,
10
11
  } from "./ast";
11
12
  import { TlaSyntaxError } from "./errors";
12
- import { getChildren } from "./evaluate";
13
13
  import { getSourceName, mapChildren, mapDefinition } from "./instances";
14
14
  import { getArity, getBoundNames, getPatternNames, LOCAL_RESOLUTION } from "./resolve";
15
15
 
package/src/successors.ts CHANGED
@@ -1,9 +1,16 @@
1
- import type { Bound, Definition, Expression } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type Definition,
6
+ type Expression,
7
+ } from "./ast";
2
8
  import { getReadVariables } from "./dependencies";
3
- import { TlaEvaluationError } from "./errors";
9
+ import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
4
10
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
5
11
  import {
6
12
  describeLocation,
13
+ describeRange,
7
14
  bindArgument,
8
15
  bindDefinitions,
9
16
  bindOperatorArguments,
@@ -13,14 +20,12 @@ import {
13
20
  expectBoolean,
14
21
  forEachBinding,
15
22
  getBoundsDomain,
16
- getChildren,
17
23
  getDefinition,
18
24
  getEnumeratedElements,
19
25
  getReevaluatedDefinitions,
20
26
  lookupScope,
21
27
  resolveApplyOperator,
22
28
  resolveGlobalOperator,
23
- isLocallyResolved,
24
29
  type Context,
25
30
  type Environment,
26
31
  type Scope,
@@ -804,7 +809,9 @@ const compileAction = (
804
809
  );
805
810
  const body = arm?.body ?? other;
806
811
  if (!body)
807
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
812
+ throw new TlaEvaluationError(
813
+ `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
814
+ );
808
815
  body(run, scope, partial, action, isFixed, onComplete);
809
816
  };
810
817
  }
@@ -913,18 +920,19 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
913
920
  );
914
921
  }
915
922
  const environment = context.environment;
916
- const found = { value: false };
923
+ const run: Run = { environment, isInit: false, current: state, isStopped: false };
924
+ // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
917
925
  getRunner(expression, environment, false)(
918
- { environment, isInit: false, current: state, isStopped: false },
926
+ run,
919
927
  context.scope,
920
928
  getEmptyState(environment),
921
929
  undefined,
922
930
  false,
923
931
  () => {
924
- found.value = true;
932
+ run.isStopped = true;
925
933
  },
926
934
  );
927
- return found.value;
935
+ return run.isStopped;
928
936
  };
929
937
 
930
938
  export const forEachInitialState = (
package/src/symmetry.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  isEnumerable,
10
10
  isFunctionValue,
11
11
  isModelValue,
12
+ isSameValue,
12
13
  isSetValue,
13
14
  toFiniteFunction,
14
15
  toFiniteSet,
@@ -163,7 +164,10 @@ const permuteValue = (value: Value, permutation: Permutation): Value => {
163
164
  if (size === 0 || size > CACHED_SIZE_LIMIT) return computePermutedValue(value, permutation);
164
165
  const cached = permutation.cache.get(value);
165
166
  if (cached !== undefined) return cached;
166
- const permuted = computePermutedValue(value, permutation);
167
+ const computed = computePermutedValue(value, permutation);
168
+ // A permutation often maps a value to an equal one. Keeping the original lets the comparison
169
+ // with the smallest state so far stop at identity.
170
+ const permuted = computed !== value && isSameValue(computed, value) ? value : computed;
167
171
  if (permutation.cacheSize >= permutation.cacheLimit) {
168
172
  permutation.cache = new WeakMap();
169
173
  permutation.cacheSize = 0;
@@ -184,7 +188,15 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
184
188
  const domain = permuteElements(functionValue.domain, permutation);
185
189
  const range = permuteElements(functionValue.range, permutation) ?? functionValue.range;
186
190
  if (domain) {
187
- return createFunction(domain.map((key, index): [Value, Value] => [key, range[index]]));
191
+ const permuted = createFunction(
192
+ domain.map((key, index): [Value, Value] => [key, range[index]]),
193
+ );
194
+ // A permutation often maps the domain to itself, such as a function over the symmetric set.
195
+ // Sharing the original domain array lets comparisons with other images skip the domain.
196
+ const isSameDomain = permuted.domain.every(
197
+ (key, index) => key === functionValue.domain[index],
198
+ );
199
+ return isSameDomain ? createSortedFunction(functionValue.domain, permuted.range) : permuted;
188
200
  }
189
201
  return range === functionValue.range
190
202
  ? functionValue
package/src/tlc-ext.ts CHANGED
@@ -10,16 +10,8 @@ import {
10
10
  } from "./builtins";
11
11
  import { TlaEvaluationError, TlaModuleError, TlaUnsupportedError } from "./errors";
12
12
  import { getTlcFingerprint } from "./tlc-random";
13
- import {
14
- evaluate,
15
- expectBoolean,
16
- getChildren,
17
- getDefinition,
18
- isLocallyResolved,
19
- type Builtin,
20
- type Environment,
21
- } from "./evaluate";
22
- import type { Definition, Expression } from "./ast";
13
+ import { evaluate, expectBoolean, getDefinition, type Builtin, type Environment } from "./evaluate";
14
+ import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
23
15
  import type { TraceStep } from "./check";
24
16
  import {
25
17
  getNamedRegisters,
@@ -111,15 +103,35 @@ const getRegister = (runtime: CheckerRuntime, key: Value) => {
111
103
  return undefined;
112
104
  };
113
105
 
114
- const setRegister = (runtime: CheckerRuntime, key: Value, value: Value) => {
106
+ // TLC's TLCSet. TLCExt's TLCGetAndSet is a TLA+ definition that calls it.
107
+ export const setTlcValue = (
108
+ runtime: CheckerRuntime,
109
+ print: (text: string) => void,
110
+ key: Value,
111
+ value: Value,
112
+ ) => {
115
113
  if (typeof key === "number" && key >= 0) {
116
114
  runtime.registers.set(key, value);
117
115
  return;
118
116
  }
117
+ if (key === "exit") {
118
+ if (value === true) runtime.isStopped = true;
119
+ return;
120
+ }
121
+ if (key === "pause") {
122
+ if (value !== true) return;
123
+ print("Press enter to resume model checking.");
124
+ runtime.pause();
125
+ return;
126
+ }
119
127
  if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
120
128
  runtime.namedRegisters.set(key, value);
121
129
  return;
122
130
  }
131
+ if (typeof key === "string" && key.startsWith("-D")) {
132
+ runtime.properties.set(key.slice(2), formatValue(value));
133
+ return;
134
+ }
123
135
  throw new TlaModuleError(
124
136
  `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
125
137
  );
@@ -203,7 +215,12 @@ export const createTlcExtOperators = (
203
215
  const key = getValue(args, 0, "TLCGetAndSet");
204
216
  const previous = getRegister(runtime, key) ?? getValue(args, 3, "TLCGetAndSet");
205
217
  const update = getOperator(args, 1, "TLCGetAndSet");
206
- setRegister(runtime, key, update.call([previous, getValue(args, 2, "TLCGetAndSet")]));
218
+ setTlcValue(
219
+ runtime,
220
+ print,
221
+ key,
222
+ update.call([previous, getValue(args, 2, "TLCGetAndSet")]),
223
+ );
207
224
  return previous;
208
225
  }),
209
226
  isStateLevel: true,
package/src/tlc-module.ts CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  getValue,
16
16
  } from "./builtins";
17
17
  import { getNamedRegisters, NAMED_REGISTER_PREFIX, type CheckerRuntime } from "./runtime";
18
- import { createActionRecord } from "./tlc-ext";
18
+ import { createActionRecord, setTlcValue } from "./tlc-ext";
19
19
  import { getRandomElement } from "./tlc-random";
20
20
  import {
21
21
  ANY_SET,
@@ -203,33 +203,8 @@ export const createTlcOperators = (
203
203
  }),
204
204
  defineStateOperator("TLCSet", 2, (args) => {
205
205
  const key = getValue(args, 0, "TLCSet");
206
- const value = getValue(args, 1, "TLCSet");
207
- if (typeof key === "number" && key >= 0) {
208
- runtime.registers.set(key, value);
209
- return true;
210
- }
211
- if (key === "exit") {
212
- if (value === true) runtime.isStopped = true;
213
- return true;
214
- }
215
- if (key === "pause") {
216
- if (value === true) {
217
- print("Press enter to resume model checking.");
218
- runtime.pause();
219
- }
220
- return true;
221
- }
222
- if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
223
- runtime.namedRegisters.set(key, value);
224
- return true;
225
- }
226
- if (typeof key === "string" && key.startsWith("-D")) {
227
- runtime.properties.set(key.slice(2), formatValue(value));
228
- return true;
229
- }
230
- throw new TlaModuleError(
231
- `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
232
- );
206
+ setTlcValue(runtime, print, key, getValue(args, 1, "TLCSet"));
207
+ return true;
233
208
  }),
234
209
  defineConstant("Any", ANY_SET),
235
210
  defineOperator("RandomElement", 1, (args) =>
package/src/tlc-order.ts CHANGED
@@ -184,9 +184,18 @@ const isAdjacent = (left: Token, right: Token | undefined) =>
184
184
  right.line === left.line &&
185
185
  right.column === left.column + left.text.length;
186
186
 
187
+ const STRING_ESCAPES: Record<string, string> = {
188
+ "\\": "\\\\",
189
+ '"': '\\"',
190
+ "\n": "\\n",
191
+ "\t": "\\t",
192
+ "\r": "\\r",
193
+ "\f": "\\f",
194
+ };
195
+
187
196
  // The texts SANY interns while parsing, in order. SANY reads a proof step label such as <1>2 and
188
- // a module header such as ---- MODULE as one token, and interns a string literal's contents only
189
- // during semantic analysis.
197
+ // a module header such as ---- MODULE as one token. It interns a string literal as written, quotes
198
+ // included, and interns the literal's contents only during semantic analysis.
190
199
  const getParsedTexts = (tokens: Token[]) => {
191
200
  const texts: string[] = [];
192
201
  for (let index = 0; index < tokens.length; index++) {
@@ -202,7 +211,12 @@ const getParsedTexts = (tokens: Token[]) => {
202
211
  continue;
203
212
  }
204
213
  const isHeader = token.text === "MODULE" && tokens[index - 1]?.kind === "Separator";
205
- if (token.kind !== "String" && !isHeader) texts.push(token.text);
214
+ if (isHeader) continue;
215
+ texts.push(
216
+ token.kind === "String"
217
+ ? `"${token.text.replace(/[\\"\n\t\r\f]/g, (character) => STRING_ESCAPES[character])}"`
218
+ : token.text,
219
+ );
206
220
  }
207
221
  return texts;
208
222
  };