tla-ts 0.0.3-dev.9c2dda8 → 0.0.3-dev.a57ca4f

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/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,
@@ -39,11 +39,17 @@ const formatCalendarVersion = (date: Date) =>
39
39
  const getRegisterFunction = <Key extends Value>(registers: Map<Key, Value>) =>
40
40
  createFunction([...registers].map(([key, value]): [Value, Value] => [key, createTuple([value])]));
41
41
 
42
+ // TLC creates its model checker after it processes the spec, so these are undefined before then.
43
+ const CHECKER_KEYS = new Set(["diameter", "generated", "distinct", "queue", "stats", "config"]);
44
+
42
45
  const getRuntimeValue = (
43
46
  runtime: CheckerRuntime,
44
47
  key: string,
45
48
  state: (Value | undefined)[] | undefined,
46
49
  ) => {
50
+ if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
51
+ throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
52
+ }
47
53
  const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
48
54
  switch (key) {
49
55
  case "level":
@@ -203,33 +209,8 @@ export const createTlcOperators = (
203
209
  }),
204
210
  defineStateOperator("TLCSet", 2, (args) => {
205
211
  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
- );
212
+ setTlcValue(runtime, print, key, getValue(args, 1, "TLCSet"));
213
+ return true;
233
214
  }),
234
215
  defineConstant("Any", ANY_SET),
235
216
  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
  };
package/src/values.ts CHANGED
@@ -137,6 +137,13 @@ export const isSetValue = (value: Value) =>
137
137
  value.kind !== "Function" &&
138
138
  value.kind !== "LazyFunction";
139
139
 
140
+ export type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
141
+
142
+ // TLC reduces a set enumeration or an interval eagerly, and keeps every other set lazy.
143
+ export const isReducible = (value: Value): value is ReducibleSet =>
144
+ typeof value === "object" &&
145
+ (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
146
+
140
147
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
141
148
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
142
149
 
@@ -1069,13 +1076,16 @@ const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(
1069
1076
  const formatUnion = (value: UnionValue, isStrict = false) =>
1070
1077
  `UNION(${formatValue(value.base, isStrict)})`;
1071
1078
 
1072
- const getUnionSets = (value: UnionValue) => {
1079
+ const getUnionSets = (
1080
+ value: UnionValue,
1081
+ getElements = (set: Value) => toFiniteSet(set).elements,
1082
+ ) => {
1073
1083
  if (!isTlcEnumerable(value.base)) {
1074
1084
  throw new TlaEvaluationError(
1075
1085
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1076
1086
  );
1077
1087
  }
1078
- return toFiniteSet(value.base).elements;
1088
+ return getElements(value.base);
1079
1089
  };
1080
1090
 
1081
1091
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1111,7 +1121,7 @@ export const isEnumerable = (value: Value): boolean => {
1111
1121
  case "ProductSet":
1112
1122
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1113
1123
  case "Union":
1114
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1124
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1115
1125
  case "SetOperation":
1116
1126
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1117
1127
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1345,8 +1355,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1345
1355
  // so an element that two of them share comes up once for each.
1346
1356
  export const getStreamedElements = (value: Value): Value[] => {
1347
1357
  if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
1358
+ // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1359
+ // its elements twice.
1348
1360
  if (value.kind === "Union") {
1349
- return getUnionSets(value).flatMap((set, index) =>
1361
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1350
1362
  getStreamedElements(getUnionSet(set, index, value)),
1351
1363
  );
1352
1364
  }
@@ -2101,8 +2113,11 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2101
2113
  return `[${parameters} |-> <expression ${source.body}>]`;
2102
2114
  }
2103
2115
  const functionValue = toFiniteFunction(value);
2116
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2117
+ const formatRange = (inner: Value) =>
2118
+ formatValue(inner, isStrict, isNormalized && value.kind === "Function");
2104
2119
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2105
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2120
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2106
2121
  }
2107
2122
  if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2108
2123
  const isSorted =
@@ -2110,9 +2125,20 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2110
2125
  const pairs = isSorted
2111
2126
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2112
2127
  : getWrittenPairs(functionValue);
2113
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2128
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2114
2129
  }
2115
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2130
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2116
2131
  }
2117
2132
  }
2118
2133
  };
2134
+
2135
+ // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2136
+ export const formatState = (state: Record<string, Value>) => {
2137
+ const entries = Object.entries(state);
2138
+ return entries
2139
+ .map(
2140
+ ([name, value]) =>
2141
+ `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2142
+ )
2143
+ .join("");
2144
+ };