tla-ts 0.0.8 → 0.0.9-dev.331c500

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 (63) hide show
  1. package/README.md +23 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +48 -48
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +27 -9
  8. package/dist/index.d.ts +27 -9
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove.cjs +30 -30
  13. package/dist/prove.js +32 -32
  14. package/dist/run.cjs +28 -28
  15. package/dist/run.js +31 -31
  16. package/dist/tlapm.cjs +2 -2
  17. package/dist/tlapm.js +1 -1
  18. package/dist/transfer.cjs +30 -33
  19. package/dist/transfer.js +30 -33
  20. package/dist/worker.cjs +4 -4
  21. package/dist/worker.js +4 -4
  22. package/package.json +3 -1
  23. package/src/check.ts +77 -46
  24. package/src/cli/options.ts +2 -1
  25. package/src/cli/tlc.ts +26 -8
  26. package/src/cli/typescript.ts +26 -0
  27. package/src/codegen.ts +0 -5
  28. package/src/dependencies.ts +348 -24
  29. package/src/environment.ts +27 -11
  30. package/src/errors.ts +15 -0
  31. package/src/evaluate.ts +188 -712
  32. package/src/instances.ts +67 -6
  33. package/src/lexer.ts +140 -51
  34. package/src/liveness-checker.ts +6 -3
  35. package/src/liveness.ts +8 -18
  36. package/src/parallel-worker.ts +7 -5
  37. package/src/parallel.ts +18 -9
  38. package/src/prover/smt/solver/solver.ts +31 -27
  39. package/src/sany/generator.ts +9 -7
  40. package/src/sany/linter.ts +30 -21
  41. package/src/search.ts +48 -32
  42. package/src/spec-description.ts +1 -1
  43. package/src/successors.ts +6 -12
  44. package/src/symmetry.ts +32 -143
  45. package/src/tlc/fingerprint.ts +69 -116
  46. package/src/tlc/order.ts +27 -48
  47. package/src/tlc/replay.ts +1 -1
  48. package/src/typescript/actions.ts +494 -0
  49. package/src/typescript/collections.ts +615 -0
  50. package/src/typescript/compile.ts +70 -0
  51. package/src/typescript/context.ts +106 -0
  52. package/src/typescript/emit.ts +122 -0
  53. package/src/typescript/expressions.ts +508 -0
  54. package/src/typescript/formula.ts +160 -0
  55. package/src/typescript/functions.ts +295 -0
  56. package/src/typescript/model.ts +164 -0
  57. package/src/typescript/names.ts +116 -0
  58. package/src/typescript/program.ts +51 -0
  59. package/src/typescript/properties.ts +142 -0
  60. package/src/typescript/scope.ts +117 -0
  61. package/src/typescript/steps.ts +175 -0
  62. package/src/typescript/types.ts +178 -0
  63. package/src/values.ts +151 -85
@@ -0,0 +1,615 @@
1
+ import ts from "@typescript/typescript6";
2
+ import {
3
+ type Context,
4
+ getCallee,
5
+ getSymbol,
6
+ isMethodCall,
7
+ type MethodCall,
8
+ share,
9
+ } from "./context";
10
+ import { TlaTypeScriptError } from "../errors";
11
+ import { translateExpression } from "./expressions";
12
+ import { wrap, wrapEquated } from "./formula";
13
+ import { translateBody } from "./functions";
14
+ import { bindNames, bindPatternInline, type Scope } from "./scope";
15
+ import { getKind, type Kind } from "./types";
16
+
17
+ interface Unordered {
18
+ set: string;
19
+ // Whether map() built the set, so that it may have fewer elements than the array would.
20
+ isMapped: boolean;
21
+ }
22
+
23
+ // Methods that read their array once, so that sharing it with a LET gains nothing.
24
+ const SINGLE_USE_METHODS = new Set(["concat", "with", "filter"]);
25
+
26
+ interface Element {
27
+ variable: string;
28
+ scope: Scope;
29
+ }
30
+
31
+ interface Update {
32
+ (current: string, values: string[], context: Context): string;
33
+ }
34
+
35
+ const getCallback = (callback: ts.Expression, context: Context) => {
36
+ const callee = getCallee(callback, context);
37
+ if (callee?.body === undefined) throw new TlaTypeScriptError("Pass a function here", callback);
38
+ return { parameters: callee.parameters, body: callee.body };
39
+ };
40
+
41
+ const translateCallback = (callback: ts.Expression, scope: Scope, context: Context) =>
42
+ translateBody(getCallback(callback, context).body, scope, context);
43
+
44
+ const rejectIndex = (callback: ts.Expression, message: string, context: Context) => {
45
+ if (getCallback(callback, context).parameters[1] !== undefined) {
46
+ throw new TlaTypeScriptError(message, callback);
47
+ }
48
+ };
49
+
50
+ // Binds a callback's element parameter to a fresh variable, which a quantifier then binds.
51
+ const bindElement = (callback: ts.Expression, scope: Scope, context: Context): Element => {
52
+ const parameter = getCallback(callback, context).parameters[0];
53
+ if (parameter === undefined) return { variable: context.names.getFresh("element"), scope };
54
+ if (!ts.isIdentifier(parameter.name)) {
55
+ const variable = context.names.getFresh("element");
56
+ return { variable, scope: bindPatternInline(parameter.name, variable, scope, context) };
57
+ }
58
+ const variable = context.names.getFresh(parameter.name.text);
59
+ const symbol = getSymbol(parameter.name, context.checker);
60
+ return { variable, scope: bindNames(scope, [{ name: variable, symbol }]) };
61
+ };
62
+
63
+ // Binds a callback's (element, index) parameters for the TLA+ index of a sequence, which counts
64
+ // from 1 where JavaScript counts from 0.
65
+ const bindIndexed = (
66
+ callback: ts.Expression,
67
+ element: string | undefined,
68
+ index: string,
69
+ scope: Scope,
70
+ context: Context,
71
+ ) => {
72
+ const parameters = getCallback(callback, context).parameters;
73
+ const withElement =
74
+ element === undefined || parameters[0] === undefined
75
+ ? scope
76
+ : bindPatternInline(parameters[0].name, element, scope, context);
77
+ return parameters[1] === undefined
78
+ ? withElement
79
+ : bindPatternInline(parameters[1].name, `(${index} - 1)`, withElement, context);
80
+ };
81
+
82
+ const getValues = (value: string, context: Context): Unordered => ({
83
+ set: share(value, "map", context, (map) => {
84
+ const key = context.names.getFresh("key");
85
+ return `{${map}[${key}] : ${key} \\in DOMAIN ${map}}`;
86
+ }),
87
+ isMapped: true,
88
+ });
89
+
90
+ const getEntries = (value: string, context: Context): Unordered => ({
91
+ set: share(value, "map", context, (map) => {
92
+ const key = context.names.getFresh("key");
93
+ return `{<<${key}, ${map}[${key}]>> : ${key} \\in DOMAIN ${map}}`;
94
+ }),
95
+ isMapped: false,
96
+ });
97
+
98
+ const getElements = (value: string, context: Context) =>
99
+ share(value, "sequence", context, (sequence) => {
100
+ const index = context.names.getFresh("index");
101
+ return `{${sequence}[${index}] : ${index} \\in DOMAIN ${sequence}}`;
102
+ });
103
+
104
+ // A set built from a Set, Map, or object, whose element order TLA+ doesn't keep.
105
+ const translateUnordered = (
106
+ node: ts.Expression,
107
+ scope: Scope,
108
+ context: Context,
109
+ ): Unordered | undefined => {
110
+ const translate = (inner: ts.Expression) => translateExpression(inner, scope, context);
111
+ if (ts.isParenthesizedExpression(node)) {
112
+ return translateUnordered(node.expression, scope, context);
113
+ }
114
+ if (
115
+ ts.isArrayLiteralExpression(node) &&
116
+ node.elements.length === 1 &&
117
+ ts.isSpreadElement(node.elements[0])
118
+ ) {
119
+ const spread = node.elements[0].expression;
120
+ const kind = getKind(spread, context);
121
+ if (kind === "set") return { set: translate(spread), isMapped: false };
122
+ if (kind === "map") return getEntries(translate(spread), context);
123
+ return translateUnordered(spread, scope, context);
124
+ }
125
+ if (!isMethodCall(node)) return undefined;
126
+ const receiver = node.expression.expression;
127
+ const method = node.expression.name.text;
128
+ if (ts.isIdentifier(receiver) && receiver.text === "Object") {
129
+ const record = translate(node.arguments[0]);
130
+ if (method === "keys") return { set: `DOMAIN ${wrap(record)}`, isMapped: false };
131
+ if (method === "values") return getValues(record, context);
132
+ if (method === "entries") return getEntries(record, context);
133
+ return undefined;
134
+ }
135
+ const kind = getKind(receiver, context);
136
+ if (kind === "set" && (method === "values" || method === "keys")) {
137
+ return { set: translate(receiver), isMapped: false };
138
+ }
139
+ if (kind === "set" && method === "entries") {
140
+ const element = context.names.getFresh("element");
141
+ return {
142
+ set: `{<<${element}, ${element}>> : ${element} \\in ${wrap(translate(receiver))}}`,
143
+ isMapped: false,
144
+ };
145
+ }
146
+ if (kind === "map" && method === "keys") {
147
+ return { set: `DOMAIN ${wrap(translate(receiver))}`, isMapped: false };
148
+ }
149
+ if (kind === "map" && method === "values") return getValues(translate(receiver), context);
150
+ if (kind === "map" && method === "entries") return getEntries(translate(receiver), context);
151
+ if (method === "toArray") return translateUnordered(receiver, scope, context);
152
+ if (method !== "filter" && method !== "map") return undefined;
153
+ const source = translateUnordered(receiver, scope, context);
154
+ if (source === undefined) return undefined;
155
+ const callback = node.arguments[0];
156
+ rejectIndex(callback, "Elements of a set have no index", context);
157
+ const element = bindElement(callback, scope, context);
158
+ const body = translateCallback(callback, element.scope, context);
159
+ return method === "filter"
160
+ ? { set: `{${element.variable} \\in ${wrap(source.set)} : ${body}}`, isMapped: source.isMapped }
161
+ : { set: `{${body} : ${element.variable} \\in ${wrap(source.set)}}`, isMapped: true };
162
+ };
163
+
164
+ // The elements of a set, an array, or an iterator over a collection, as a TLA+ set.
165
+ export const translateSet = (node: ts.Expression, scope: Scope, context: Context) => {
166
+ const unordered = translateUnordered(node, scope, context);
167
+ if (unordered !== undefined) return unordered.set;
168
+ const kind = getKind(node, context);
169
+ const value = translateExpression(node, scope, context);
170
+ if (kind === "set") return value;
171
+ if (kind !== "sequence") throw new TlaTypeScriptError("Expected a Set or an array", node);
172
+ return getElements(value, context);
173
+ };
174
+
175
+ // The number of elements in a collection, or undefined if the receiver isn't one.
176
+ export const translateSize = (node: ts.Expression, scope: Scope, context: Context) => {
177
+ const unordered = translateUnordered(node, scope, context);
178
+ if (unordered?.isMapped) {
179
+ throw new TlaTypeScriptError(
180
+ "map() can merge equal elements, so count before mapping",
181
+ node.parent,
182
+ );
183
+ }
184
+ if (unordered !== undefined) return `Cardinality(${unordered.set})`;
185
+ const kind = getKind(node, context);
186
+ const value = translateExpression(node, scope, context);
187
+ if (kind === "sequence" || kind === "string") return `Len(${value})`;
188
+ if (kind === "set") return `Cardinality(${value})`;
189
+ if (kind === "map") return `Cardinality(DOMAIN ${wrap(value)})`;
190
+ return undefined;
191
+ };
192
+
193
+ // [x \in S |-> e] from source.map((x) => [x, e]), as new Map() and Object.fromEntries() take it.
194
+ export const translateFunctionConstructor = (
195
+ node: ts.Expression,
196
+ scope: Scope,
197
+ context: Context,
198
+ ) => {
199
+ if (!isMethodCall(node) || node.expression.name.text !== "map") return undefined;
200
+ const receiver = node.expression.expression;
201
+ const source =
202
+ translateUnordered(receiver, scope, context)?.set ??
203
+ (getKind(receiver, context) === "sequence"
204
+ ? getElements(translateExpression(receiver, scope, context), context)
205
+ : undefined);
206
+ const callback = node.arguments[0];
207
+ const parameter = getCallback(callback, context).parameters[0];
208
+ const body =
209
+ (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) &&
210
+ !ts.isBlock(callback.body)
211
+ ? callback.body
212
+ : undefined;
213
+ const pair = body !== undefined && ts.isParenthesizedExpression(body) ? body.expression : body;
214
+ const isKeyedByParameter =
215
+ pair !== undefined &&
216
+ ts.isArrayLiteralExpression(pair) &&
217
+ pair.elements.length === 2 &&
218
+ parameter !== undefined &&
219
+ ts.isIdentifier(parameter.name) &&
220
+ ts.isIdentifier(pair.elements[0]) &&
221
+ pair.elements[0].text === parameter.name.text;
222
+ if (source === undefined || !isKeyedByParameter) {
223
+ throw new TlaTypeScriptError(
224
+ "Build a Map or record from a set with set.values().map((key) => [key, value])",
225
+ node,
226
+ );
227
+ }
228
+ const element = bindElement(callback, scope, context);
229
+ const value = translateExpression(pair.elements[1], element.scope, context);
230
+ return `[${element.variable} \\in ${source} |-> ${value}]`;
231
+ };
232
+
233
+ // A sequence from Array.from({ length: n }, callback) or new Array(n).fill(value).
234
+ export const translateArrayConstructor = (node: MethodCall, scope: Scope, context: Context) => {
235
+ const receiver = node.expression.expression;
236
+ const method = node.expression.name.text;
237
+ const translateLength = (length: ts.Expression) =>
238
+ wrap(translateExpression(length, scope, context));
239
+ const callback = node.arguments[1];
240
+ const options = node.arguments[0];
241
+ if (
242
+ ts.isIdentifier(receiver) &&
243
+ receiver.text === "Array" &&
244
+ method === "from" &&
245
+ node.arguments.length === 2 &&
246
+ ts.isObjectLiteralExpression(options)
247
+ ) {
248
+ const length = options.properties.find((property) => property.name?.getText() === "length");
249
+ if (length === undefined || !ts.isPropertyAssignment(length)) {
250
+ throw new TlaTypeScriptError("Array.from needs { length: n }", node);
251
+ }
252
+ const index = context.names.getFresh("index");
253
+ const inner = bindIndexed(callback, undefined, index, scope, context);
254
+ return `[${index} \\in 1..${translateLength(length.initializer)} |-> ${translateCallback(callback, inner, context)}]`;
255
+ }
256
+ if (method !== "fill" || node.arguments.length !== 1) return undefined;
257
+ const array =
258
+ ts.isNewExpression(receiver) || ts.isCallExpression(receiver) ? receiver : undefined;
259
+ const length =
260
+ array !== undefined &&
261
+ ts.isIdentifier(array.expression) &&
262
+ array.expression.text === "Array" &&
263
+ array.arguments?.length === 1
264
+ ? array.arguments[0]
265
+ : undefined;
266
+ if (length === undefined) return undefined;
267
+ const index = context.names.getFresh("index");
268
+ return `[${index} \\in 1..${translateLength(length)} |-> ${translateExpression(node.arguments[0], scope, context)}]`;
269
+ };
270
+
271
+ // The first index in a sequence whose element passes a test, or undefined if none does.
272
+ const translateFirstIndex = (
273
+ sequence: string,
274
+ callback: ts.Expression,
275
+ scope: Scope,
276
+ context: Context,
277
+ ) => {
278
+ const getTest = (index: string) =>
279
+ translateCallback(
280
+ callback,
281
+ bindIndexed(callback, `${wrap(sequence)}[${index}]`, index, scope, context),
282
+ context,
283
+ );
284
+ const index = context.names.getFresh("index");
285
+ const earlier = context.names.getFresh("earlier");
286
+ return {
287
+ exists: `\\E ${index} \\in DOMAIN ${wrap(sequence)} : ${getTest(index)}`,
288
+ first: `CHOOSE ${index} \\in DOMAIN ${wrap(sequence)} : ${wrap(getTest(index))} /\\ \\A ${earlier} \\in 1..(${index} - 1) : ~${wrap(getTest(earlier))}`,
289
+ };
290
+ };
291
+
292
+ const translateSequenceOperation = (
293
+ node: MethodCall,
294
+ sequence: string,
295
+ scope: Scope,
296
+ context: Context,
297
+ isDefined: boolean,
298
+ ) => {
299
+ const method = node.expression.name.text;
300
+ const translate = (inner: ts.Expression) => translateExpression(inner, scope, context);
301
+ const argument = node.arguments[0];
302
+ const wrapped = wrap(sequence);
303
+ const isNegative = (inner: ts.Expression): inner is ts.PrefixUnaryExpression =>
304
+ ts.isPrefixUnaryExpression(inner) && inner.operator === ts.SyntaxKind.MinusToken;
305
+ // An index that may count back from the end, as slice() and at() take it.
306
+ const getOffset = (inner: ts.Expression) =>
307
+ isNegative(inner) ? `Len(${sequence}) - ${wrap(translate(inner.operand))}` : translate(inner);
308
+ const orUndefined = (exists: string, value: string) => {
309
+ if (isDefined) return value;
310
+ context.prelude.add("Undefined");
311
+ return `IF ${exists} THEN ${value} ELSE Undefined`;
312
+ };
313
+ const translateEach = (format: (index: string, body: string) => string) => () => {
314
+ const index = context.names.getFresh("index");
315
+ const inner = bindIndexed(argument, `${wrapped}[${index}]`, index, scope, context);
316
+ return format(index, translateCallback(argument, inner, context));
317
+ };
318
+ const operations = new Map<string, () => string>([
319
+ [
320
+ "at",
321
+ () => {
322
+ const index = isNegative(argument)
323
+ ? `${getOffset(argument)} + 1`
324
+ : `${wrap(translate(argument))} + 1`;
325
+ return orUndefined(`${index} \\in DOMAIN ${wrapped}`, `${wrapped}[${index}]`);
326
+ },
327
+ ],
328
+ [
329
+ "includes",
330
+ () => {
331
+ const index = context.names.getFresh("index");
332
+ return `\\E ${index} \\in DOMAIN ${wrapped} : ${wrapped}[${index}] = ${wrap(translate(argument))}`;
333
+ },
334
+ ],
335
+ [
336
+ "indexOf",
337
+ () =>
338
+ share(translate(argument), "value", context, (value) => {
339
+ const index = context.names.getFresh("index");
340
+ const earlier = context.names.getFresh("earlier");
341
+ const isFound = `${wrapped}[${index}] = ${value}`;
342
+ return `IF \\E ${index} \\in DOMAIN ${wrapped} : ${isFound} THEN (CHOOSE ${index} \\in DOMAIN ${wrapped} : ${isFound} /\\ \\A ${earlier} \\in 1..(${index} - 1) : ${wrapped}[${earlier}] # ${value}) - 1 ELSE -1`;
343
+ }),
344
+ ],
345
+ [
346
+ "slice",
347
+ () => {
348
+ const start = argument === undefined ? "0" : getOffset(argument);
349
+ const end =
350
+ node.arguments[1] === undefined ? undefined : wrap(getOffset(node.arguments[1]));
351
+ const last =
352
+ end === undefined
353
+ ? `Len(${sequence})`
354
+ : `IF ${end} < Len(${sequence}) THEN ${end} ELSE Len(${sequence})`;
355
+ const first = /^\d+$/.test(start) ? String(Number(start) + 1) : `${wrap(start)} + 1`;
356
+ return `SubSeq(${sequence}, ${first}, ${last})`;
357
+ },
358
+ ],
359
+ [
360
+ "concat",
361
+ () =>
362
+ [
363
+ sequence,
364
+ ...node.arguments.map((inner) =>
365
+ getKind(inner, context) === "sequence" ? translate(inner) : `<<${translate(inner)}>>`,
366
+ ),
367
+ ]
368
+ .map(wrap)
369
+ .join(" \\o "),
370
+ ],
371
+ [
372
+ "with",
373
+ () =>
374
+ `[${wrapped} EXCEPT ![${wrap(translate(argument))} + 1] = ${wrapEquated(translate(node.arguments[1]))}]`,
375
+ ],
376
+ [
377
+ "toReversed",
378
+ () => {
379
+ const index = context.names.getFresh("index");
380
+ return `[${index} \\in DOMAIN ${wrapped} |-> ${wrapped}[Len(${sequence}) - ${index} + 1]]`;
381
+ },
382
+ ],
383
+ ["map", translateEach((index, body) => `[${index} \\in DOMAIN ${wrapped} |-> ${body}]`)],
384
+ ["every", translateEach((index, body) => `\\A ${index} \\in DOMAIN ${wrapped} : ${body}`)],
385
+ ["some", translateEach((index, body) => `\\E ${index} \\in DOMAIN ${wrapped} : ${body}`)],
386
+ [
387
+ "filter",
388
+ () => {
389
+ rejectIndex(argument, "filter() can't take an index", context);
390
+ const element = bindElement(argument, scope, context);
391
+ return `SelectSeq(${sequence}, LAMBDA ${element.variable} : ${translateCallback(argument, element.scope, context)})`;
392
+ },
393
+ ],
394
+ [
395
+ "find",
396
+ () => {
397
+ const result = translateFirstIndex(sequence, argument, scope, context);
398
+ return orUndefined(result.exists, `${wrapped}[${result.first}]`);
399
+ },
400
+ ],
401
+ [
402
+ "findIndex",
403
+ () => {
404
+ const result = translateFirstIndex(sequence, argument, scope, context);
405
+ return `IF ${result.exists} THEN (${result.first}) - 1 ELSE -1`;
406
+ },
407
+ ],
408
+ ]);
409
+ const operation = operations.get(method);
410
+ if (operation === undefined)
411
+ throw new TlaTypeScriptError(`Unsupported array method: ${method}`, node);
412
+ return operation();
413
+ };
414
+
415
+ const translateUnorderedMethod = (
416
+ node: MethodCall,
417
+ source: Unordered,
418
+ scope: Scope,
419
+ context: Context,
420
+ isDefined: boolean,
421
+ ) => {
422
+ const method = node.expression.name.text;
423
+ const argument = node.arguments[0];
424
+ if (method === "includes" || method === "has") {
425
+ return `${wrap(translateExpression(argument, scope, context))} \\in ${wrap(source.set)}`;
426
+ }
427
+ if (method !== "every" && method !== "some" && method !== "find") {
428
+ throw new TlaTypeScriptError(`Unsupported method on a set's elements: ${method}`, node);
429
+ }
430
+ rejectIndex(argument, "Elements of a set have no index", context);
431
+ const element = bindElement(argument, scope, context);
432
+ const body = translateCallback(argument, element.scope, context);
433
+ const binding = `${element.variable} \\in ${wrap(source.set)} : ${body}`;
434
+ if (method === "every") return `\\A ${binding}`;
435
+ if (method === "some") return `\\E ${binding}`;
436
+ if (isDefined) return `CHOOSE ${binding}`;
437
+ context.prelude.add("Undefined");
438
+ return `IF \\E ${binding} THEN CHOOSE ${binding} ELSE Undefined`;
439
+ };
440
+
441
+ const translateSetMethod = (node: MethodCall, scope: Scope, context: Context) => {
442
+ const method = node.expression.name.text;
443
+ const set = wrap(translateExpression(node.expression.expression, scope, context));
444
+ const other =
445
+ node.arguments[0] === undefined
446
+ ? ""
447
+ : wrap(translateExpression(node.arguments[0], scope, context));
448
+ const operations = new Map([
449
+ ["has", `${other} \\in ${set}`],
450
+ ["union", `${set} \\cup ${other}`],
451
+ ["intersection", `${set} \\cap ${other}`],
452
+ ["difference", `${set} \\ ${other}`],
453
+ ["symmetricDifference", `(${set} \\ ${other}) \\cup (${other} \\ ${set})`],
454
+ ["isSubsetOf", `${set} \\subseteq ${other}`],
455
+ ["isSupersetOf", `${other} \\subseteq ${set}`],
456
+ ["isDisjointFrom", `${set} \\cap ${other} = {}`],
457
+ ]);
458
+ const operation = operations.get(method);
459
+ if (operation === undefined)
460
+ throw new TlaTypeScriptError(`Unsupported Set method: ${method}`, node);
461
+ return operation;
462
+ };
463
+
464
+ const translateMapMethod = (
465
+ node: MethodCall,
466
+ scope: Scope,
467
+ context: Context,
468
+ isDefined: boolean,
469
+ ) => {
470
+ const method = node.expression.name.text;
471
+ const map = wrap(translateExpression(node.expression.expression, scope, context));
472
+ const key =
473
+ node.arguments[0] === undefined
474
+ ? ""
475
+ : wrap(translateExpression(node.arguments[0], scope, context));
476
+ if (method === "has") return `${key} \\in DOMAIN ${map}`;
477
+ if (method !== "get") throw new TlaTypeScriptError(`Unsupported Map method: ${method}`, node);
478
+ if (isDefined) return `${map}[${key}]`;
479
+ context.prelude.add("Undefined");
480
+ return share(map, "map", context, (sharedMap) =>
481
+ share(
482
+ key,
483
+ "key",
484
+ context,
485
+ (sharedKey) =>
486
+ `IF ${sharedKey} \\in DOMAIN ${sharedMap} THEN ${sharedMap}[${sharedKey}] ELSE Undefined`,
487
+ ),
488
+ );
489
+ };
490
+
491
+ const UPDATES = new Map<Kind, Map<string, Update>>([
492
+ [
493
+ "sequence",
494
+ new Map<string, Update>([
495
+ [
496
+ "push",
497
+ (current, values) =>
498
+ values.length === 1
499
+ ? `Append(${current}, ${values[0]})`
500
+ : `${wrap(current)} \\o <<${values.join(", ")}>>`,
501
+ ],
502
+ ["unshift", (current, values) => `<<${values.join(", ")}>> \\o ${wrap(current)}`],
503
+ ["pop", (current) => `SubSeq(${current}, 1, Len(${current}) - 1)`],
504
+ ["shift", (current) => `Tail(${current})`],
505
+ ]),
506
+ ],
507
+ [
508
+ "set",
509
+ new Map<string, Update>([
510
+ ["add", (current, values) => `${wrap(current)} \\cup {${values[0]}}`],
511
+ ["delete", (current, values) => `${wrap(current)} \\ {${values[0]}}`],
512
+ ["clear", () => "{}"],
513
+ ]),
514
+ ],
515
+ [
516
+ "map",
517
+ new Map<string, Update>([
518
+ ["set", (current, values) => `(${values[0]} :> ${values[1]}) @@ ${wrap(current)}`],
519
+ [
520
+ "delete",
521
+ (current, values, context) => {
522
+ const key = context.names.getFresh("key");
523
+ return `[${key} \\in DOMAIN ${wrap(current)} \\ {${values[0]}} |-> ${wrap(current)}[${key}]]`;
524
+ },
525
+ ],
526
+ ["clear", () => "<<>>"],
527
+ ]),
528
+ ],
529
+ ]);
530
+
531
+ export const MUTATING_METHODS = new Set(
532
+ [...UPDATES.values()].flatMap((updates) => [...updates.keys()]),
533
+ );
534
+
535
+ // The value of a collection after a mutating method call, or undefined if the method doesn't
536
+ // mutate.
537
+ export const getUpdatedValue = (
538
+ current: string,
539
+ kind: Kind,
540
+ node: MethodCall,
541
+ scope: Scope,
542
+ context: Context,
543
+ ) => {
544
+ const values = node.arguments.map((argument) => translateExpression(argument, scope, context));
545
+ return UPDATES.get(kind)?.get(node.expression.name.text)?.(current, values, context);
546
+ };
547
+
548
+ export const translateMethod = (
549
+ node: MethodCall,
550
+ scope: Scope,
551
+ context: Context,
552
+ isDefined: boolean,
553
+ ) => {
554
+ const receiver = node.expression.expression;
555
+ const unordered = translateUnordered(receiver, scope, context);
556
+ if (unordered !== undefined) {
557
+ return translateUnorderedMethod(node, unordered, scope, context, isDefined);
558
+ }
559
+ // A mutating method on a fresh copy, such as new Set(s).add(x), returns the updated copy.
560
+ const isCopy =
561
+ ts.isNewExpression(receiver) &&
562
+ receiver.arguments?.length === 1 &&
563
+ ts.isIdentifier(receiver.expression) &&
564
+ (receiver.expression.text === "Set" || receiver.expression.text === "Map");
565
+ const kind = getKind(receiver, context);
566
+ const updated = isCopy
567
+ ? getUpdatedValue(translateExpression(receiver, scope, context), kind, node, scope, context)
568
+ : undefined;
569
+ if (updated !== undefined) return updated;
570
+ if (kind === "sequence") {
571
+ const method = node.expression.name.text;
572
+ const sequence = translateExpression(receiver, scope, context);
573
+ const translateWith = (shared: string) =>
574
+ translateSequenceOperation(node, shared, scope, context, isDefined);
575
+ return SINGLE_USE_METHODS.has(method)
576
+ ? translateWith(sequence)
577
+ : share(sequence, "sequence", context, translateWith);
578
+ }
579
+ if (kind === "set") return translateSetMethod(node, scope, context);
580
+ if (kind === "map") return translateMapMethod(node, scope, context, isDefined);
581
+ throw new TlaTypeScriptError(`Unsupported call: ${node.expression.getText()}`, node);
582
+ };
583
+
584
+ export const translateNew = (node: ts.NewExpression, scope: Scope, context: Context) => {
585
+ const constructor = node.expression.getText();
586
+ const argument = node.arguments?.[0];
587
+ if (constructor === "Set") {
588
+ if (argument === undefined) return "{}";
589
+ if (ts.isArrayLiteralExpression(argument) && !argument.elements.some(ts.isSpreadElement)) {
590
+ return `{${argument.elements.map((element) => translateExpression(element, scope, context)).join(", ")}}`;
591
+ }
592
+ return translateSet(argument, scope, context);
593
+ }
594
+ if (constructor !== "Map") {
595
+ throw new TlaTypeScriptError(`Unsupported constructor: new ${constructor}`, node);
596
+ }
597
+ if (argument === undefined) return "<<>>";
598
+ if (ts.isArrayLiteralExpression(argument)) {
599
+ if (argument.elements.length === 0) return "<<>>";
600
+ return argument.elements
601
+ .toReversed()
602
+ .map((entry) => {
603
+ if (!ts.isArrayLiteralExpression(entry) || entry.elements.length !== 2) {
604
+ throw new TlaTypeScriptError("Write each Map entry as [key, value]", entry);
605
+ }
606
+ return `(${translateExpression(entry.elements[0], scope, context)} :> ${translateExpression(entry.elements[1], scope, context)})`;
607
+ })
608
+ .join(" @@ ");
609
+ }
610
+ if (getKind(argument, context) === "map") return translateExpression(argument, scope, context);
611
+ const map = translateFunctionConstructor(argument, scope, context);
612
+ if (map === undefined)
613
+ throw new TlaTypeScriptError(`Unsupported constructor: new ${constructor}`, node);
614
+ return map;
615
+ };
@@ -0,0 +1,70 @@
1
+ import { basename } from "node:path";
2
+ import ts from "@typescript/typescript6";
3
+ import { writesState } from "./actions";
4
+ import { type Context, createContext } from "./context";
5
+ import { type CompiledSpec, createSections, emit, type Sections } from "./emit";
6
+ import { TlaTypeScriptError } from "../errors";
7
+ import { indent, wrapEquated } from "./formula";
8
+ import { translateBody } from "./functions";
9
+ import { type Exported, type Model, readModel, type Variable } from "./model";
10
+ import { createProgram } from "./program";
11
+ import { translateInvariant, translateProperty, VALUE_TAGS } from "./properties";
12
+ import { createStateScope } from "./scope";
13
+ import { translateStep } from "./steps";
14
+ import { getDomain } from "./types";
15
+
16
+ // A state variable starts at its initializer, or at every value of its type without one.
17
+ const translateInitial = (variable: Variable, context: Context) => {
18
+ const initializer = variable.declaration.initializer;
19
+ if (initializer === undefined) {
20
+ const type = context.checker.getTypeAtLocation(variable.declaration.name);
21
+ return `${variable.name} \\in ${getDomain(type, variable.declaration, context)}`;
22
+ }
23
+ const value = translateBody(initializer, createStateScope(context), context);
24
+ return `${variable.name} = ${indent(wrapEquated(value), " ")}`;
25
+ };
26
+
27
+ // An exported function is a property if a tag says so, an action if it changes state, and an
28
+ // invariant if it returns a boolean.
29
+ const translateExported = (
30
+ definition: Exported,
31
+ model: Model,
32
+ sections: Sections,
33
+ context: Context,
34
+ ) => {
35
+ const tag = [...definition.tags.keys()].find((candidate) => VALUE_TAGS.has(candidate));
36
+ if (tag !== undefined) return translateProperty(definition, tag, model, sections, context);
37
+ if (writesState(definition.body, context)) {
38
+ return translateStep(definition, sections, context);
39
+ }
40
+ const returnType = context.checker.getSignatureFromDeclaration(definition.node)?.getReturnType();
41
+ if (
42
+ returnType === undefined ||
43
+ (returnType.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) !== 0
44
+ ) {
45
+ return translateStep(definition, sections, context);
46
+ }
47
+ if (!(returnType.flags & ts.TypeFlags.BooleanLike)) {
48
+ throw new TlaTypeScriptError(
49
+ "An exported function that returns a value must return a boolean, or be tagged, such as @view",
50
+ definition.node,
51
+ );
52
+ }
53
+ return translateInvariant(definition, sections, context);
54
+ };
55
+
56
+ // Compiles a TypeScript file into a TLA+ spec and the config that checks it. Imports resolve
57
+ // relative to fileName, and the module takes its name, so die-hard.ts is the module DieHard.
58
+ export const compile = (source: string, fileName = "spec.ts"): CompiledSpec => {
59
+ const program = createProgram(source, fileName.replaceAll("\\", "/"));
60
+ const context = createContext(program.checker);
61
+ const model = readModel(program.sourceFile, context);
62
+ const sections = createSections();
63
+ sections.init.push(...model.variables.map((variable) => translateInitial(variable, context)));
64
+ for (const definition of model.exported) translateExported(definition, model, sections, context);
65
+ const moduleName = basename(fileName, ".ts")
66
+ .split(/[^A-Za-z0-9]+/)
67
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
68
+ .join("");
69
+ return emit(moduleName, model, sections, context);
70
+ };