tla-ts 0.0.1 → 0.0.3-dev.19c763f

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.
Files changed (74) hide show
  1. package/README.md +98 -39
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +225 -30
  4. package/dist/index.d.ts +225 -30
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +21 -1
  11. package/dist/run-cli.js +21 -1
  12. package/dist/transfer.cjs +400 -39
  13. package/dist/transfer.js +400 -39
  14. package/package.json +6 -2
  15. package/src/ast.ts +213 -6
  16. package/src/bags.ts +161 -71
  17. package/src/builtins.ts +203 -23
  18. package/src/bundled-modules.ts +63 -32
  19. package/src/check.ts +1086 -244
  20. package/src/cli-options.ts +64 -0
  21. package/src/codegen.ts +58 -34
  22. package/src/config.ts +39 -11
  23. package/src/dependencies.ts +2 -2
  24. package/src/environment.ts +557 -153
  25. package/src/errors.ts +66 -1
  26. package/src/evaluate.ts +547 -255
  27. package/src/exit-codes.ts +53 -0
  28. package/src/fingerprints.ts +48 -13
  29. package/src/index.ts +9 -4
  30. package/src/instances.ts +235 -79
  31. package/src/java-overrides.ts +241 -0
  32. package/src/json.ts +153 -72
  33. package/src/levels.ts +850 -0
  34. package/src/lexer.ts +108 -29
  35. package/src/live-check.ts +710 -0
  36. package/src/liveness.ts +37 -599
  37. package/src/obligation-action.ts +384 -0
  38. package/src/obligation-anon.ts +575 -0
  39. package/src/obligation-deref.ts +637 -0
  40. package/src/obligation-expression.ts +1060 -0
  41. package/src/obligation-format.ts +406 -0
  42. package/src/obligation-generate.ts +1074 -0
  43. package/src/obligation-levels.ts +329 -0
  44. package/src/obligation-module.ts +1042 -0
  45. package/src/obligation-printer.ts +889 -0
  46. package/src/obligation-proof.ts +76 -0
  47. package/src/obligation-source.ts +1084 -0
  48. package/src/obligation-tuples.ts +184 -0
  49. package/src/obligations.ts +316 -0
  50. package/src/parallel-worker.ts +186 -201
  51. package/src/parallel.ts +179 -84
  52. package/src/parser.ts +970 -206
  53. package/src/pretty-print.ts +259 -0
  54. package/src/randomization.ts +24 -113
  55. package/src/resolve.ts +483 -51
  56. package/src/run-cli.ts +473 -62
  57. package/src/runtime.ts +65 -28
  58. package/src/spec-description.ts +521 -0
  59. package/src/standard-levels.ts +105 -0
  60. package/src/standard-modules.ts +223 -92
  61. package/src/state-graph.ts +157 -0
  62. package/src/subexpressions.ts +31 -45
  63. package/src/substitution-levels.ts +184 -0
  64. package/src/successors.ts +276 -53
  65. package/src/symmetry.ts +79 -23
  66. package/src/tableau.ts +43 -37
  67. package/src/tlc-ext.ts +148 -44
  68. package/src/tlc-module.ts +71 -66
  69. package/src/tlc-modules.ts +1022 -0
  70. package/src/tlc-order.ts +511 -0
  71. package/src/tlc-random.ts +411 -0
  72. package/src/tlc-summary.ts +109 -0
  73. package/src/transfer.ts +26 -5
  74. package/src/values.ts +1245 -176
@@ -0,0 +1,64 @@
1
+ export interface OptionSpec {
2
+ flag: string;
3
+ isRequired?: boolean;
4
+ isRepeatable?: boolean;
5
+ // How many of the arguments after the flag the option takes, when that depends on them.
6
+ getArity?: (rest: string[]) => number;
7
+ }
8
+
9
+ export interface ParsedOption {
10
+ name: string;
11
+ values: string[];
12
+ }
13
+
14
+ export interface ParsedArgs {
15
+ options: ParsedOption[];
16
+ positionals: string[];
17
+ unknown: string[];
18
+ incomplete: ParsedOption | undefined;
19
+ has: (name: string) => boolean;
20
+ get: (name: string) => string[] | undefined;
21
+ }
22
+
23
+ const formatOption = (spec: OptionSpec) => {
24
+ const text = spec.isRequired ? spec.flag : `[${spec.flag}]`;
25
+ return spec.isRepeatable ? `${text}...` : text;
26
+ };
27
+
28
+ // Each <name> in a flag such as "--toolbox <start> <end>" is one value the option takes, and
29
+ // {options} in the usage stands for the options.
30
+ export const defineCommand = (usage: string, specs: OptionSpec[]) => {
31
+ const arities = new Map(
32
+ specs.map((spec) => {
33
+ const [name, ...values] = spec.flag.split(" ");
34
+ return [name, spec.getArity ?? (() => values.length)];
35
+ }),
36
+ );
37
+ const parse = (args: string[]): ParsedArgs => {
38
+ const options: ParsedOption[] = [];
39
+ const positionals: string[] = [];
40
+ const unknown: string[] = [];
41
+ const incomplete: ParsedOption[] = [];
42
+ for (let index = 0; index < args.length; index++) {
43
+ const getArity = arities.get(args[index]);
44
+ if (getArity === undefined) {
45
+ (args[index].startsWith("-") ? unknown : positionals).push(args[index]);
46
+ continue;
47
+ }
48
+ const arity = getArity(args.slice(index + 1));
49
+ const option = { name: args[index], values: args.slice(index + 1, index + 1 + arity) };
50
+ options.push(option);
51
+ if (option.values.length < arity) incomplete.push(option);
52
+ index += arity;
53
+ }
54
+ return {
55
+ options,
56
+ positionals,
57
+ unknown,
58
+ incomplete: incomplete[0],
59
+ has: (name) => options.some((option) => option.name === name),
60
+ get: (name) => options.findLast((option) => option.name === name)?.values,
61
+ };
62
+ };
63
+ return { usage: usage.replace("{options}", specs.map(formatOption).join(" ")), parse };
64
+ };
package/src/codegen.ts CHANGED
@@ -1,26 +1,35 @@
1
- import type { Expression } from "./ast";
2
- import { TlaEvaluationError } from "./errors";
1
+ import { getChildren, isLocallyResolved, type Expression } from "./ast";
3
2
  import {
4
3
  bindValue,
5
4
  expectBoolean,
6
5
  findGlobalName,
7
- getChildren,
8
6
  getEnumeratedElements,
7
+ getConditionError,
8
+ getConjunctError,
9
+ getDomainOperator,
10
+ getSubsetOperator,
9
11
  getEvaluator,
12
+ getFieldError,
10
13
  isClosedConstant,
11
- isLocallyResolved,
14
+ isTlcInteger,
12
15
  isValueArgument,
13
16
  isWorthCaching,
17
+ keepLazy,
14
18
  resolveGlobalOperator,
19
+ createPrimeOutsideActionError,
20
+ createUnassignedError,
21
+ getSortedFields,
22
+ hasDuplicateFields,
15
23
  type Context,
16
24
  type Environment,
17
25
  type Evaluator,
18
26
  } from "./evaluate";
19
27
  import {
20
28
  applyFunction,
21
- createSet,
29
+ createEnumeratedSet,
22
30
  createSortedFunction,
23
31
  createTuple,
32
+ createWrittenRecord,
24
33
  valuesEqual,
25
34
  type Value,
26
35
  } from "./values";
@@ -56,26 +65,28 @@ const GENERATED_KINDS = new Set([
56
65
  "Exists",
57
66
  ]);
58
67
 
59
- const describeLocation = (expression: Expression) =>
60
- `line ${expression.location.line}, column ${expression.location.column}`;
61
-
62
68
  const createRuntime = () => ({
63
69
  bool: expectBoolean,
70
+ condition: (value: Value, expression: Expression) => {
71
+ if (typeof value !== "boolean") throw getConditionError(expression, value);
72
+ return value;
73
+ },
74
+ conjunct: (value: Value, expression: Expression & { kind: "And" | "Or" }, index: number) => {
75
+ if (typeof value !== "boolean") throw getConjunctError(expression, index, value);
76
+ return value;
77
+ },
64
78
  apply: applyFunction,
65
79
  tuple: createTuple,
66
- set: createSet,
80
+ set: createEnumeratedSet,
67
81
  record: createSortedFunction,
82
+ writtenRecord: createWrittenRecord,
68
83
  equal: valuesEqual,
69
84
  enumerate: getEnumeratedElements,
70
85
  unassigned: (name: string, expression: Expression): never => {
71
- throw new TlaEvaluationError(
72
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
73
- );
86
+ throw createUnassignedError(name, expression);
74
87
  },
75
88
  primeOutsideAction: (expression: Expression): never => {
76
- throw new TlaEvaluationError(
77
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
78
- );
89
+ throw createPrimeOutsideActionError(expression);
79
90
  },
80
91
  prime: (context: Context): Context => ({
81
92
  environment: context.environment,
@@ -103,7 +114,7 @@ const addReference = (generator: Generator, value: unknown) => {
103
114
 
104
115
  const createLocal = (generator: Generator) => `local${generator.counter++}`;
105
116
 
106
- const getFreeNames = (expression: Expression, names = new Set<string>()): Set<string> => {
117
+ const getFreeNames = (expression: Expression, names = new Set<string>()) => {
107
118
  if (expression.kind === "Identifier") names.add(expression.name);
108
119
  if (expression.kind === "Apply") names.add(expression.operator);
109
120
  getChildren(expression).forEach((child) => getFreeNames(child, names));
@@ -131,7 +142,7 @@ const generateQuantifier = (
131
142
  const description = JSON.stringify(isForall ? "the body of \\A" : "the body of \\E");
132
143
  const name = `quantifier${generator.counter++}`;
133
144
  const outer = [...frame.locals.values()];
134
- const inner: Frame = {
145
+ const inner = {
135
146
  context: "context",
136
147
  state: "state",
137
148
  next: "next",
@@ -174,6 +185,15 @@ const generateApply = (
174
185
  if (isLocallyResolved(expression)) return generateDelegate(generator, expression, frame);
175
186
  const builtin = resolveGlobalOperator(expression.operator, generator.environment);
176
187
  if (builtin?.kind !== "Builtin") return generateDelegate(generator, expression, frame);
188
+ if (builtin.name === "DOMAIN") {
189
+ const domain = addReference(generator, getDomainOperator(expression));
190
+ return `${domain}(${generateExpression(generator, args[0], frame)})`;
191
+ }
192
+ if (builtin.name === "TLCEval") return generateDelegate(generator, expression, frame);
193
+ if (builtin.name === "\\subseteq" && args.length === 2) {
194
+ const subset = addReference(generator, getSubsetOperator(expression, builtin));
195
+ return `${subset}(${generateExpression(generator, args[0], frame)}, ${generateExpression(generator, args[1], frame)})`;
196
+ }
177
197
  const environment = generator.environment;
178
198
  if (builtin.evaluateUnary && args.length === 1 && isValueArgument(args[0], environment)) {
179
199
  const operation = addReference(generator, builtin.evaluateUnary);
@@ -198,7 +218,7 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
198
218
  }
199
219
  switch (expression.kind) {
200
220
  case "Number":
201
- if (Number.isInteger(expression.value) && Math.abs(expression.value) <= 2147483647) {
221
+ if (isTlcInteger(expression.value)) {
202
222
  return String(expression.value);
203
223
  }
204
224
  return generateDelegate(generator, expression, frame);
@@ -219,32 +239,36 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
219
239
  }
220
240
  case "Apply":
221
241
  return generateApply(generator, expression, frame);
222
- case "And":
223
- return `(${expression.operands.map((operand) => `bool(${generate(operand)}, "a conjunct")`).join(" && ")})`;
242
+ case "And": {
243
+ const node = addReference(generator, expression);
244
+ return `(${expression.operands.map((operand, index) => `conjunct(${generate(operand)}, ${node}, ${index})`).join(" && ")})`;
245
+ }
224
246
  case "Or":
225
247
  return `(${expression.operands.map((operand) => `bool(${generate(operand)}, "a disjunct")`).join(" || ")})`;
226
248
  case "If":
227
- return `(bool(${generate(expression.condition)}, "an IF condition") ? ${generate(expression.consequent)} : ${generate(expression.alternative)})`;
249
+ return `(condition(${generate(expression.condition)}, ${addReference(generator, expression)}) ? ${generate(expression.consequent)} : ${generate(expression.alternative)})`;
228
250
  case "FunctionApplication": {
229
- const fn = generate(expression.function);
230
- if (expression.args.length === 1) return `apply(${fn}, ${generate(expression.args[0])})`;
231
- return `apply(${fn}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
251
+ keepLazy(expression.function);
252
+ const functionCode = generate(expression.function);
253
+ if (expression.args.length === 1)
254
+ return `apply(${functionCode}, ${generate(expression.args[0])})`;
255
+ return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
232
256
  }
233
257
  case "FieldAccess":
234
- return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)})`;
258
+ return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
235
259
  case "Record": {
236
- const fields = [...expression.fields].sort((left, right) =>
237
- left.name < right.name ? -1 : 1,
238
- );
239
- const hasDuplicates = fields.some(
240
- (field, index) => index > 0 && fields[index - 1].name === field.name,
241
- );
242
- if (hasDuplicates) return generateDelegate(generator, expression, frame);
260
+ const fields = getSortedFields(expression.fields);
261
+ if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
243
262
  const names = addReference(
244
263
  generator,
245
264
  fields.map((field) => field.name),
246
265
  );
247
- return `record(${names}, [${fields.map((field) => generate(field.value)).join(", ")}])`;
266
+ const values = `[${fields.map((field) => generate(field.value)).join(", ")}]`;
267
+ const writtenNames = expression.fields.map((field) => field.name);
268
+ if (writtenNames.every((name, index) => name === fields[index].name)) {
269
+ return `record(${names}, ${values})`;
270
+ }
271
+ return `writtenRecord(${names}, ${values}, ${addReference(generator, writtenNames)})`;
248
272
  }
249
273
  case "Tuple":
250
274
  return `tuple([${expression.elements.map((element) => generate(element)).join(", ")}])`;
@@ -253,7 +277,7 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
253
277
  case "Prime": {
254
278
  const node = addReference(generator, expression);
255
279
  if (frame.isPrimed) return `primeOutsideAction(${node})`;
256
- const primed: Frame = {
280
+ const primed = {
257
281
  context: `(primed ??= prime(${frame.context}))`,
258
282
  state: frame.next,
259
283
  next: "undefined",
package/src/config.ts CHANGED
@@ -34,8 +34,11 @@ export interface ModelConfig {
34
34
  checkDeadlock: boolean;
35
35
  symmetry: string | undefined;
36
36
  view: string | undefined;
37
+ alias: string | undefined;
37
38
  postconditions: string[];
38
39
  possible: string[];
40
+ periodic: string | undefined;
41
+ rlReward: string | undefined;
39
42
  }
40
43
 
41
44
  interface ConfigToken {
@@ -65,11 +68,13 @@ const KEYWORDS = new Set([
65
68
  "POSTCONDITION",
66
69
  "POSTCONDITIONS",
67
70
  "_POSSIBLE",
71
+ "_PERIODIC",
72
+ "_RL_REWARD",
68
73
  ]);
69
74
 
70
75
  const SYMBOLS = ["<-", "<<", ">>", "=", "{", "}", ",", "[", "]", "(", ")"];
71
76
 
72
- const tokenizeConfig = (source: string): ConfigToken[] => {
77
+ const tokenizeConfig = (source: string) => {
73
78
  const tokens: ConfigToken[] = [];
74
79
  const cursor = { index: 0, line: 1 };
75
80
  while (cursor.index < source.length) {
@@ -92,7 +97,7 @@ const tokenizeConfig = (source: string): ConfigToken[] => {
92
97
  cursor.index += end + 2;
93
98
  continue;
94
99
  }
95
- const number = /^-?\d+(?![A-Za-z_])/.exec(rest)?.[0];
100
+ const number = /^\d+(?![A-Za-z_])/.exec(rest)?.[0];
96
101
  if (number) {
97
102
  tokens.push({ kind: "Number", text: number, line: cursor.line });
98
103
  cursor.index += number.length;
@@ -106,7 +111,7 @@ const tokenizeConfig = (source: string): ConfigToken[] => {
106
111
  }
107
112
  const string = /^"((?:[^"\\]|\\.)*)"/.exec(rest);
108
113
  if (string) {
109
- tokens.push({ kind: "String", text: JSON.parse(`"${string[1]}"`), line: cursor.line });
114
+ tokens.push({ kind: "String", text: string[1], line: cursor.line });
110
115
  cursor.index += string[0].length;
111
116
  continue;
112
117
  }
@@ -144,10 +149,14 @@ export const parseConfig = (source: string): ModelConfig => {
144
149
  checkDeadlock: true,
145
150
  symmetry: undefined,
146
151
  view: undefined,
152
+ alias: undefined,
147
153
  postconditions: [],
148
154
  possible: [],
155
+ periodic: undefined,
156
+ rlReward: undefined,
149
157
  };
150
158
 
159
+ const deadlock = { isSet: false };
151
160
  const peek = () => tokens[cursor.index];
152
161
  const advance = () => tokens[cursor.index++];
153
162
  const isKeyword = (token: ConfigToken) => token.kind === "Word" && KEYWORDS.has(token.text);
@@ -168,13 +177,22 @@ export const parseConfig = (source: string): ModelConfig => {
168
177
  }
169
178
  return token.text;
170
179
  };
180
+ const isNameAhead = () => peek().kind === "Word" && !isKeyword(peek());
171
181
  const parseNames = () => {
172
182
  const names: string[] = [];
173
- while (peek().kind === "Word" && !isKeyword(peek())) names.push(advance().text);
183
+ while (isNameAhead()) names.push(advance().text);
174
184
  return names;
175
185
  };
176
186
  const setSingle = (
177
- key: "init" | "next" | "specification" | "symmetry" | "view",
187
+ key:
188
+ | "init"
189
+ | "next"
190
+ | "specification"
191
+ | "symmetry"
192
+ | "view"
193
+ | "alias"
194
+ | "periodic"
195
+ | "rlReward",
178
196
  keyword: string,
179
197
  ) => {
180
198
  if (config[key] !== undefined) throw new TlaConfigError(`The keyword ${keyword} appears twice`);
@@ -189,11 +207,12 @@ export const parseConfig = (source: string): ModelConfig => {
189
207
  return { kind: "Boolean", value: token.text === "TRUE" };
190
208
  if (token.text === "{") {
191
209
  const elements: ConfigValue[] = [];
192
- while (peek().text !== "}") {
210
+ if (peek().text !== "}") elements.push(parseValue());
211
+ while (peek().text === ",") {
212
+ advance();
193
213
  elements.push(parseValue());
194
- if (peek().text !== "}") expect(",");
195
214
  }
196
- advance();
215
+ expect("}");
197
216
  return { kind: "Set", elements };
198
217
  }
199
218
  if (token.kind === "Word" && !isKeyword(token)) return { kind: "ModelValue", name: token.text };
@@ -211,7 +230,7 @@ export const parseConfig = (source: string): ModelConfig => {
211
230
  };
212
231
 
213
232
  const parseConstants = () => {
214
- while (peek().kind === "Word" && !isKeyword(peek())) {
233
+ while (isNameAhead()) {
215
234
  const name = advance().text;
216
235
  if (peek().text === "(") {
217
236
  advance();
@@ -222,7 +241,8 @@ export const parseConfig = (source: string): ModelConfig => {
222
241
  }
223
242
  advance();
224
243
  expect("=");
225
- config.constants.push({ name, value: parseValue(), args });
244
+ const module = parseModuleScope();
245
+ config.constants.push({ name, value: parseValue(), args, ...(module && { module }) });
226
246
  continue;
227
247
  }
228
248
  if (peek().text === "<-") {
@@ -276,7 +296,7 @@ export const parseConfig = (source: string): ModelConfig => {
276
296
  config.actionConstraints.push(...parseNames());
277
297
  break;
278
298
  case "ALIAS":
279
- expectName();
299
+ setSingle("alias", token.text);
280
300
  break;
281
301
  case "POSTCONDITION":
282
302
  case "POSTCONDITIONS":
@@ -285,7 +305,15 @@ export const parseConfig = (source: string): ModelConfig => {
285
305
  case "_POSSIBLE":
286
306
  config.possible.push(...parseNames());
287
307
  break;
308
+ case "_PERIODIC":
309
+ setSingle("periodic", token.text);
310
+ break;
311
+ case "_RL_REWARD":
312
+ setSingle("rlReward", token.text);
313
+ break;
288
314
  case "CHECK_DEADLOCK": {
315
+ if (deadlock.isSet) throw new TlaConfigError("The keyword CHECK_DEADLOCK appears twice");
316
+ deadlock.isSet = true;
289
317
  const value = advance().text;
290
318
  if (value !== "TRUE" && value !== "FALSE") {
291
319
  throw new TlaConfigError(
@@ -1,5 +1,5 @@
1
- import type { Definition, Expression } from "./ast";
2
- import { getChildren, isImpureBuiltin, type Environment } from "./evaluate";
1
+ import { getChildren, type Definition, type Expression } from "./ast";
2
+ import { isImpureBuiltin, type Environment } from "./evaluate";
3
3
 
4
4
  const STATE_INDEPENDENT_KINDS = new Set([
5
5
  "Prime",