tla-ts 0.0.9-dev.2813db5 → 0.0.9-dev.4ce0657

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 (48) hide show
  1. package/README.md +21 -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 +1 -0
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.js +1 -1
  10. package/dist/prove.cjs +16 -16
  11. package/dist/prove.js +20 -20
  12. package/dist/run.cjs +28 -28
  13. package/dist/run.js +31 -31
  14. package/dist/tlapm.cjs +2 -2
  15. package/dist/tlapm.js +1 -1
  16. package/dist/transfer.cjs +18 -18
  17. package/dist/transfer.js +26 -26
  18. package/dist/worker.cjs +4 -4
  19. package/dist/worker.js +4 -4
  20. package/package.json +3 -1
  21. package/src/check.ts +44 -31
  22. package/src/cli/options.ts +1 -1
  23. package/src/cli/tlc.ts +17 -8
  24. package/src/cli/typescript.ts +26 -0
  25. package/src/environment.ts +4 -0
  26. package/src/errors.ts +15 -0
  27. package/src/evaluate.ts +65 -10
  28. package/src/instances.ts +67 -6
  29. package/src/liveness-checker.ts +6 -3
  30. package/src/liveness.ts +7 -3
  31. package/src/prover/smt/solver/solver.ts +31 -27
  32. package/src/successors.ts +3 -3
  33. package/src/typescript/actions.ts +494 -0
  34. package/src/typescript/collections.ts +615 -0
  35. package/src/typescript/compile.ts +70 -0
  36. package/src/typescript/context.ts +106 -0
  37. package/src/typescript/emit.ts +122 -0
  38. package/src/typescript/expressions.ts +508 -0
  39. package/src/typescript/formula.ts +160 -0
  40. package/src/typescript/functions.ts +295 -0
  41. package/src/typescript/model.ts +164 -0
  42. package/src/typescript/names.ts +116 -0
  43. package/src/typescript/program.ts +51 -0
  44. package/src/typescript/properties.ts +141 -0
  45. package/src/typescript/scope.ts +117 -0
  46. package/src/typescript/steps.ts +175 -0
  47. package/src/typescript/types.ts +178 -0
  48. package/src/values.ts +11 -9
@@ -21,36 +21,40 @@ export const checkSmt = (text: string, options: DecideOptions): SmtCheck => {
21
21
  const manager = new AstManager(
22
22
  new ResourceLimit(Date.now() + options.timeLimitMs, options.signal),
23
23
  );
24
- // combined_solver gives each assertion to the incremental smt kernel as well, which rewrites it
25
- // when it is asserted and keeps it, though check-sat then runs the tactic on the assertions. The
26
- // kernel's model finder counts a step of the resource limit when it is made, and
27
- // solver::assert_expr counts one for each assertion.
28
- const incremental = new AssertedFormulas(manager);
29
- manager.limit.inc();
30
- const problem = parseSmtlib(text, manager, (assertion) => {
24
+ // The limit stops watching the collector however the check ends, as an unsupported input or a
25
+ // problem without check-sat ends it early.
26
+ try {
27
+ // combined_solver gives each assertion to the incremental smt kernel as well, which rewrites it
28
+ // when it is asserted and keeps it, though check-sat then runs the tactic on the assertions. The
29
+ // kernel's model finder counts a step of the resource limit when it is made, and
30
+ // solver::assert_expr counts one for each assertion.
31
+ const incremental = new AssertedFormulas(manager);
31
32
  manager.limit.inc();
32
- incremental.assertExpr(assertion);
33
- });
34
- if (!problem.hasCheckSat) return { verdict: "unknown", numInstances: 0 };
35
- const goal = applyUfniaTactic(manager, problem.assertions);
36
- // and_then runs smt_tactic only on a goal that the preprocessing left undecided.
37
- if (goal.isInconsistent || goal.forms.size === 0) {
33
+ const problem = parseSmtlib(text, manager, (assertion) => {
34
+ manager.limit.inc();
35
+ incremental.assertExpr(assertion);
36
+ });
37
+ if (!problem.hasCheckSat) return { verdict: "unknown", numInstances: 0 };
38
+ const goal = applyUfniaTactic(manager, problem.assertions);
39
+ // and_then runs smt_tactic only on a goal that the preprocessing left undecided.
40
+ if (goal.isInconsistent || goal.forms.size === 0) {
41
+ return { verdict: goal.isInconsistent ? "unsat" : "sat", numInstances: 0 };
42
+ }
43
+ // smt_tactic makes the context, which makes its asserted formulas first, and asserts the goal.
44
+ // setup_context then makes the theories, before the formulas are reduced.
45
+ const asserted = new AssertedFormulas(manager);
46
+ const context = new Context(manager, { isMbqi: true, relevancyLevel: 2 });
47
+ for (const assertion of goal.forms.items) asserted.assertExpr(assertion);
48
+ context.setupContext();
49
+ context.internalizeAssertions(asserted);
50
+ const result = context.search();
51
+ return {
52
+ verdict: result === L_FALSE ? "unsat" : result === L_TRUE ? "sat" : "unknown",
53
+ numInstances: context.qmanager.getNumInstances(),
54
+ };
55
+ } finally {
38
56
  manager.limit.release();
39
- return { verdict: goal.isInconsistent ? "unsat" : "sat", numInstances: 0 };
40
57
  }
41
- // smt_tactic makes the context, which makes its asserted formulas first, and asserts the goal.
42
- // setup_context then makes the theories, before the formulas are reduced.
43
- const asserted = new AssertedFormulas(manager);
44
- const context = new Context(manager, { isMbqi: true, relevancyLevel: 2 });
45
- for (const assertion of goal.forms.items) asserted.assertExpr(assertion);
46
- context.setupContext();
47
- context.internalizeAssertions(asserted);
48
- const result = context.search();
49
- manager.limit.release();
50
- return {
51
- verdict: result === L_FALSE ? "unsat" : result === L_TRUE ? "sat" : "unknown",
52
- numInstances: context.qmanager.getNumInstances(),
53
- };
54
58
  };
55
59
 
56
60
  // Throws SmtParseError on malformed input. Input outside the subset the solver supports is unknown,
package/src/successors.ts CHANGED
@@ -204,7 +204,7 @@ const getRuntimeVariableIndex = (
204
204
  }
205
205
  if (expression.kind !== "Identifier") return undefined;
206
206
  const binding = lookupScope(scope, expression.name);
207
- if (binding?.kind === "Thunk") {
207
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
208
208
  return getRuntimeVariableIndex(binding.expression, binding.scope, partial, run, isPrimed);
209
209
  }
210
210
  if (binding) return undefined;
@@ -569,7 +569,7 @@ const compileUnchanged = (expression: Expression, environment: Environment): Run
569
569
  return (run, scope, partial, action, isFixed, onComplete) => {
570
570
  const binding =
571
571
  expression.kind === "Identifier" ? lookupScope(scope, expression.name) : undefined;
572
- if (binding?.kind === "Thunk") {
572
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
573
573
  getRunner(getUnchangedWrapper(binding.expression), environment, false)(
574
574
  run,
575
575
  binding.scope,
@@ -640,7 +640,7 @@ const compileIdentifier = (
640
640
  const compiled = { body: undefined as Runner | undefined };
641
641
  return (run, scope, partial, action, isFixed, onComplete) => {
642
642
  const binding = lookupScope(scope, expression.name);
643
- if (binding?.kind === "Thunk") {
643
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
644
644
  getRunner(binding.expression, environment, isInit)(
645
645
  run,
646
646
  binding.scope,
@@ -0,0 +1,494 @@
1
+ import ts from "@typescript/typescript6";
2
+ import { getUpdatedValue, MUTATING_METHODS } from "./collections";
3
+ import {
4
+ type Context,
5
+ getFunction,
6
+ getSymbol,
7
+ getTopLevelDeclaration,
8
+ isMethodCall,
9
+ } from "./context";
10
+ import { TlaTypeScriptError } from "../errors";
11
+ import { translateExpression, translateKey } from "./expressions";
12
+ import { and, DISABLED, type Formula, letIn, text, wrap, wrapEquated } from "./formula";
13
+ import { translateIf, translateSwitch, translateThrow } from "./functions";
14
+ import { bindPattern, bindValues, type Scope } from "./scope";
15
+ import { getKind } from "./types";
16
+
17
+ interface Path {
18
+ scope: Scope;
19
+ // State variables and mutable locals, which assignments may change.
20
+ mutable: Set<ts.Symbol>;
21
+ isAssigned: boolean;
22
+ }
23
+
24
+ interface Target {
25
+ symbol: ts.Symbol;
26
+ current: string;
27
+ // The path to the changed part, as an EXCEPT selector such as .field[2].
28
+ selector: string;
29
+ }
30
+
31
+ interface Removed {
32
+ value: string;
33
+ path: Path;
34
+ }
35
+
36
+ interface Frame {
37
+ // What follows the statements once they complete.
38
+ next: (path: Path) => Formula;
39
+ // What a return statement does: end the action, or leave an inlined helper.
40
+ exit: (path: Path) => Formula;
41
+ breakTo: ((path: Path) => Formula) | undefined;
42
+ // Helpers being inlined, to reject recursion.
43
+ inlining: Set<ts.Declaration>;
44
+ }
45
+
46
+ const COMPOUND_OPERATORS = new Map([
47
+ [ts.SyntaxKind.PlusEqualsToken, "+"],
48
+ [ts.SyntaxKind.MinusEqualsToken, "-"],
49
+ [ts.SyntaxKind.AsteriskEqualsToken, "*"],
50
+ ]);
51
+
52
+ const INCREMENT_OPERATORS = new Map<ts.SyntaxKind, string>([
53
+ [ts.SyntaxKind.PlusPlusToken, "+"],
54
+ [ts.SyntaxKind.MinusMinusToken, "-"],
55
+ ]);
56
+
57
+ // The current value of an assignment target, and how to replace it.
58
+ const getTarget = (node: ts.Expression, path: Path, context: Context): Target => {
59
+ if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node)) {
60
+ return getTarget(node.expression, path, context);
61
+ }
62
+ if (ts.isIdentifier(node)) {
63
+ const symbol = getSymbol(node, context.checker);
64
+ const current = symbol === undefined ? undefined : path.scope.bindings.get(symbol);
65
+ if (symbol === undefined || current === undefined || !path.mutable.has(symbol)) {
66
+ throw new TlaTypeScriptError(
67
+ `Only state variables and local lets can change: ${node.text}`,
68
+ node,
69
+ );
70
+ }
71
+ return { symbol, current, selector: "" };
72
+ }
73
+ if (ts.isPropertyAccessExpression(node)) {
74
+ if (getKind(node.expression, context) !== "other") {
75
+ throw new TlaTypeScriptError(`Can't assign to ${node.getText()}`, node);
76
+ }
77
+ const target = getTarget(node.expression, path, context);
78
+ return { ...target, selector: `${target.selector}.${node.name.text}` };
79
+ }
80
+ if (ts.isElementAccessExpression(node)) {
81
+ const target = getTarget(node.expression, path, context);
82
+ const key = translateKey(node, path.scope, context);
83
+ return { ...target, selector: `${target.selector}[${key}]` };
84
+ }
85
+ if (
86
+ isMethodCall(node) &&
87
+ node.expression.name.text === "get" &&
88
+ node.arguments.length === 1 &&
89
+ getKind(node.expression.expression, context) === "map"
90
+ ) {
91
+ const target = getTarget(node.expression.expression, path, context);
92
+ const key = translateExpression(node.arguments[0], path.scope, context);
93
+ return { ...target, selector: `${target.selector}[${key}]` };
94
+ }
95
+ throw new TlaTypeScriptError(`Can't assign to ${node.getText()}`, node);
96
+ };
97
+
98
+ const assign = (
99
+ node: ts.Expression,
100
+ path: Path,
101
+ context: Context,
102
+ getValue: (current: string) => string,
103
+ ): Path => {
104
+ const target = getTarget(node, path, context);
105
+ const value =
106
+ target.selector === ""
107
+ ? getValue(target.current)
108
+ : `[${wrap(target.current)} EXCEPT !${target.selector} = ${wrapEquated(getValue("@"))}]`;
109
+ return {
110
+ scope: { ...path.scope, bindings: new Map([...path.scope.bindings, [target.symbol, value]]) },
111
+ mutable: path.mutable,
112
+ isAssigned: path.isAssigned || context.variables.has(target.symbol),
113
+ };
114
+ };
115
+
116
+ // Assigns a value to a target, or to each target in a destructuring pattern. Every value is read
117
+ // before any target changes, so [a, b] = [b, a] swaps.
118
+ const assignPattern = (
119
+ target: ts.Expression,
120
+ source: ts.Expression | undefined,
121
+ value: string,
122
+ path: Path,
123
+ context: Context,
124
+ ): Path => {
125
+ if (ts.isArrayLiteralExpression(target)) {
126
+ return target.elements.reduce((current, element, index) => {
127
+ if (ts.isOmittedExpression(element)) return current;
128
+ if (ts.isSpreadElement(element)) {
129
+ throw new TlaTypeScriptError("Rest elements can't be assigned", element);
130
+ }
131
+ const sourceElement =
132
+ source !== undefined && ts.isArrayLiteralExpression(source)
133
+ ? source.elements[index]
134
+ : undefined;
135
+ return sourceElement !== undefined && !ts.isSpreadElement(sourceElement)
136
+ ? assignPattern(
137
+ element,
138
+ sourceElement,
139
+ translateExpression(sourceElement, path.scope, context),
140
+ current,
141
+ context,
142
+ )
143
+ : assignPattern(element, undefined, `${wrap(value)}[${index + 1}]`, current, context);
144
+ }, path);
145
+ }
146
+ if (ts.isObjectLiteralExpression(target)) {
147
+ return target.properties.reduce((current, property) => {
148
+ if (ts.isShorthandPropertyAssignment(property)) {
149
+ return assignPattern(
150
+ property.name,
151
+ undefined,
152
+ `${wrap(value)}.${property.name.text}`,
153
+ current,
154
+ context,
155
+ );
156
+ }
157
+ if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name)) {
158
+ return assignPattern(
159
+ property.initializer,
160
+ undefined,
161
+ `${wrap(value)}.${property.name.text}`,
162
+ current,
163
+ context,
164
+ );
165
+ }
166
+ throw new TlaTypeScriptError(`Can't assign to ${property.getText()}`, property);
167
+ }, path);
168
+ }
169
+ return assign(target, path, context, () => value);
170
+ };
171
+
172
+ // The value that a call like queue.shift() returns, before it changes the queue.
173
+ const getRemovedValue = (
174
+ node: ts.Expression,
175
+ path: Path,
176
+ context: Context,
177
+ ): Removed | undefined => {
178
+ if (ts.isNonNullExpression(node) || ts.isParenthesizedExpression(node)) {
179
+ return getRemovedValue(node.expression, path, context);
180
+ }
181
+ if (!isMethodCall(node)) return undefined;
182
+ const method = node.expression.name.text;
183
+ if (method !== "shift" && method !== "pop") return undefined;
184
+ const receiver = node.expression.expression;
185
+ if (getKind(receiver, context) !== "sequence") return undefined;
186
+ const sequence = translateExpression(receiver, path.scope, context);
187
+ return {
188
+ value: method === "shift" ? `Head(${sequence})` : `${wrap(sequence)}[Len(${sequence})]`,
189
+ path: assign(receiver, path, context, (current) =>
190
+ method === "shift" ? `Tail(${current})` : `SubSeq(${current}, 1, Len(${current}) - 1)`,
191
+ ),
192
+ };
193
+ };
194
+
195
+ // The path after an assignment, such as x = 1, x += 1, or x++.
196
+ const getAssignedPath = (expression: ts.Expression, path: Path, context: Context) => {
197
+ if (ts.isPostfixUnaryExpression(expression) || ts.isPrefixUnaryExpression(expression)) {
198
+ const operator = INCREMENT_OPERATORS.get(expression.operator);
199
+ return operator === undefined
200
+ ? undefined
201
+ : assign(expression.operand, path, context, (current) => `${wrap(current)} ${operator} 1`);
202
+ }
203
+ if (!ts.isBinaryExpression(expression)) return undefined;
204
+ const kind = expression.operatorToken.kind;
205
+ if (kind === ts.SyntaxKind.EqualsToken) {
206
+ const value = translateExpression(expression.right, path.scope, context);
207
+ return assignPattern(expression.left, expression.right, value, path, context);
208
+ }
209
+ const operator =
210
+ kind === ts.SyntaxKind.PlusEqualsToken && getKind(expression.left, context) === "string"
211
+ ? "\\o"
212
+ : COMPOUND_OPERATORS.get(kind);
213
+ if (operator === undefined) return undefined;
214
+ const value = wrap(translateExpression(expression.right, path.scope, context));
215
+ return assign(
216
+ expression.left,
217
+ path,
218
+ context,
219
+ (current) => `${wrap(current)} ${operator} ${value}`,
220
+ );
221
+ };
222
+
223
+ const translateCallStatement = (
224
+ expression: ts.CallExpression,
225
+ path: Path,
226
+ context: Context,
227
+ frame: Frame,
228
+ continueWith: (path: Path) => Formula,
229
+ ): Formula => {
230
+ const values = expression.arguments.map((argument) =>
231
+ translateExpression(argument, path.scope, context),
232
+ );
233
+ if (isMethodCall(expression)) {
234
+ const receiver = expression.expression.expression;
235
+ const method = expression.expression.name.text;
236
+ const isConsole = receiver.getText() === "console";
237
+ if (isConsole && method === "log") {
238
+ const value = values.length === 1 ? values[0] : `<<${values.join(", ")}>>`;
239
+ return and([text(`PrintT(${value})`), continueWith(path)]);
240
+ }
241
+ if (isConsole && method === "assert") {
242
+ const message = values[1] ?? JSON.stringify("Assertion failed");
243
+ return and([text(`Assert(${values[0]}, ${message})`), continueWith(path)]);
244
+ }
245
+ if (MUTATING_METHODS.has(method)) {
246
+ const kind = getKind(receiver, context);
247
+ return continueWith(
248
+ assign(receiver, path, context, (current) => {
249
+ const value = getUpdatedValue(current, kind, expression, path.scope, context);
250
+ if (value === undefined) {
251
+ throw new TlaTypeScriptError(`Unsupported method: ${method}`, expression);
252
+ }
253
+ return value;
254
+ }),
255
+ );
256
+ }
257
+ }
258
+ // A helper that changes state runs inline, as part of the action.
259
+ const helper = getTopLevelDeclaration(getSymbol(expression.expression, context.checker));
260
+ const helperFunction = getFunction(helper);
261
+ if (helper === undefined || helperFunction?.body === undefined) {
262
+ throw new TlaTypeScriptError(`Unsupported statement: ${expression.getText()}`, expression);
263
+ }
264
+ if (frame.inlining.has(helper)) {
265
+ throw new TlaTypeScriptError("Helpers that change state can't call themselves", expression);
266
+ }
267
+ const bound = bindValues(
268
+ helperFunction.parameters.map((parameter) => parameter.name),
269
+ values,
270
+ path.scope,
271
+ context,
272
+ );
273
+ const body = ts.isBlock(helperFunction.body)
274
+ ? helperFunction.body.statements
275
+ : [ts.factory.createExpressionStatement(helperFunction.body)];
276
+ const afterCall = (inner: Path) =>
277
+ continueWith({ ...inner, scope: { ...inner.scope, previous: path.scope.previous } });
278
+ return letIn(
279
+ bound.definitions,
280
+ translateStatements(body, { ...path, scope: bound.scope }, context, {
281
+ next: afterCall,
282
+ exit: afterCall,
283
+ breakTo: undefined,
284
+ inlining: new Set([...frame.inlining, helper]),
285
+ }),
286
+ );
287
+ };
288
+
289
+ const translateExpressionStatement = (
290
+ expression: ts.Expression,
291
+ path: Path,
292
+ context: Context,
293
+ frame: Frame,
294
+ continueWith: (path: Path) => Formula,
295
+ ): Formula => {
296
+ if (ts.isParenthesizedExpression(expression)) {
297
+ return translateExpressionStatement(expression.expression, path, context, frame, continueWith);
298
+ }
299
+ if (ts.isCallExpression(expression)) {
300
+ return translateCallStatement(expression, path, context, frame, continueWith);
301
+ }
302
+ const assigned = getAssignedPath(expression, path, context);
303
+ if (assigned === undefined) {
304
+ throw new TlaTypeScriptError(`Unsupported statement: ${expression.getText()}`, expression);
305
+ }
306
+ return continueWith(assigned);
307
+ };
308
+
309
+ // Binds each declared local to a LET definition. A let can change later, and a const can't.
310
+ const translateDeclarations = (
311
+ declarations: readonly ts.VariableDeclaration[],
312
+ path: Path,
313
+ context: Context,
314
+ continueWith: (path: Path) => Formula,
315
+ ): Formula => {
316
+ if (declarations.length === 0) return continueWith(path);
317
+ const declaration = declarations[0];
318
+ const rest = declarations.slice(1);
319
+ if (declaration.initializer === undefined) {
320
+ throw new TlaTypeScriptError("Declare locals with a value", declaration);
321
+ }
322
+ if (getFunction(declaration.initializer) !== undefined) {
323
+ return translateDeclarations(rest, path, context, continueWith);
324
+ }
325
+ const removed = getRemovedValue(declaration.initializer, path, context);
326
+ const value = removed?.value ?? translateExpression(declaration.initializer, path.scope, context);
327
+ const afterCall = removed?.path ?? path;
328
+ const bound = bindPattern(declaration.name, value, afterCall.scope, context);
329
+ const symbol = ts.isIdentifier(declaration.name)
330
+ ? getSymbol(declaration.name, context.checker)
331
+ : undefined;
332
+ const isLet = (declaration.parent.flags & ts.NodeFlags.Let) !== 0;
333
+ const mutable = isLet && symbol !== undefined ? new Set([...path.mutable, symbol]) : path.mutable;
334
+ return letIn(
335
+ bound.definitions,
336
+ translateDeclarations(
337
+ rest,
338
+ { ...afterCall, scope: bound.scope, mutable },
339
+ context,
340
+ continueWith,
341
+ ),
342
+ );
343
+ };
344
+
345
+ const translateStatements = (
346
+ statements: readonly ts.Statement[],
347
+ path: Path,
348
+ context: Context,
349
+ frame: Frame,
350
+ ): Formula => {
351
+ if (statements.length === 0) return frame.next(path);
352
+ const statement = statements[0];
353
+ const continueWith = (inner: Path) =>
354
+ translateStatements(statements.slice(1), inner, context, frame);
355
+ if (ts.isBlock(statement)) {
356
+ return translateStatements(statement.statements, path, context, {
357
+ ...frame,
358
+ next: continueWith,
359
+ });
360
+ }
361
+ if (ts.isEmptyStatement(statement)) return continueWith(path);
362
+ if (ts.isVariableStatement(statement)) {
363
+ return translateDeclarations(
364
+ statement.declarationList.declarations,
365
+ path,
366
+ context,
367
+ continueWith,
368
+ );
369
+ }
370
+ if (ts.isIfStatement(statement)) {
371
+ return translateIf(
372
+ statement,
373
+ path.scope,
374
+ context,
375
+ (branch) => translateStatements([branch], path, context, { ...frame, next: continueWith }),
376
+ () => continueWith(path),
377
+ );
378
+ }
379
+ if (ts.isReturnStatement(statement)) {
380
+ if (statement.expression !== undefined) {
381
+ throw new TlaTypeScriptError("Actions can't return a value", statement);
382
+ }
383
+ return frame.exit(path);
384
+ }
385
+ if (ts.isBreakStatement(statement)) {
386
+ if (frame.breakTo === undefined) throw new TlaTypeScriptError("Unsupported break", statement);
387
+ return frame.breakTo(path);
388
+ }
389
+ if (ts.isThrowStatement(statement)) return text(translateThrow(statement, path.scope, context));
390
+ if (ts.isSwitchStatement(statement)) {
391
+ return translateSwitch(
392
+ statement,
393
+ path.scope,
394
+ context,
395
+ (clause) =>
396
+ translateStatements(clause, path, context, {
397
+ ...frame,
398
+ next: continueWith,
399
+ breakTo: continueWith,
400
+ }),
401
+ () => continueWith(path),
402
+ );
403
+ }
404
+ if (ts.isExpressionStatement(statement)) {
405
+ return translateExpressionStatement(statement.expression, path, context, frame, continueWith);
406
+ }
407
+ if (ts.isIterationStatement(statement, false)) {
408
+ throw new TlaTypeScriptError(
409
+ "Loops aren't supported. Use map(), filter(), every(), some(), or a parameter",
410
+ statement,
411
+ );
412
+ }
413
+ throw new TlaTypeScriptError(`Unsupported statement: ${statement.getText()}`, statement);
414
+ };
415
+
416
+ // An action's body as a TLA+ action: each path that assigns a state variable becomes a step, and
417
+ // every other path disables the action.
418
+ export const translateAction = (
419
+ statements: readonly ts.Statement[],
420
+ scope: Scope,
421
+ context: Context,
422
+ ): Formula => {
423
+ const finish = (path: Path): Formula => {
424
+ if (!path.isAssigned) return DISABLED;
425
+ const assignments = [...context.variables].map((entry) => ({
426
+ name: entry[1],
427
+ value: path.scope.bindings.get(entry[0]) ?? entry[1],
428
+ }));
429
+ const unchanged = assignments.filter((assignment) => assignment.value === assignment.name);
430
+ return and([
431
+ ...assignments
432
+ .filter((assignment) => assignment.value !== assignment.name)
433
+ .map((assignment) => text(`${assignment.name}' = ${wrapEquated(assignment.value)}`)),
434
+ ...(unchanged.length > 0
435
+ ? [text(`UNCHANGED <<${unchanged.map((assignment) => assignment.name).join(", ")}>>`)]
436
+ : []),
437
+ ]);
438
+ };
439
+ return translateStatements(
440
+ statements,
441
+ { scope, mutable: new Set(context.variables.keys()), isAssigned: false },
442
+ context,
443
+ { next: finish, exit: finish, breakTo: undefined, inlining: new Set() },
444
+ );
445
+ };
446
+
447
+ const getRoot = (node: ts.Expression): ts.Expression => {
448
+ if (isMethodCall(node) && node.expression.name.text === "get") {
449
+ return getRoot(node.expression.expression);
450
+ }
451
+ return ts.isPropertyAccessExpression(node) ||
452
+ ts.isElementAccessExpression(node) ||
453
+ ts.isParenthesizedExpression(node) ||
454
+ ts.isNonNullExpression(node)
455
+ ? getRoot(node.expression)
456
+ : node;
457
+ };
458
+
459
+ // Whether a function assigns a state variable, directly or through a helper it calls.
460
+ export const writesState = (
461
+ node: ts.Node,
462
+ context: Context,
463
+ visited = new Set<ts.Node>(),
464
+ ): boolean => {
465
+ const isStateRoot = (target: ts.Expression) => {
466
+ const root = getRoot(target);
467
+ const symbol = ts.isIdentifier(root) ? getSymbol(root, context.checker) : undefined;
468
+ return symbol !== undefined && context.variables.has(symbol);
469
+ };
470
+ const isAssignment =
471
+ ts.isBinaryExpression(node) &&
472
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
473
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
474
+ isStateRoot(node.left);
475
+ const isUpdate =
476
+ (ts.isPostfixUnaryExpression(node) || ts.isPrefixUnaryExpression(node)) &&
477
+ INCREMENT_OPERATORS.has(node.operator) &&
478
+ isStateRoot(node.operand);
479
+ const isMutation =
480
+ isMethodCall(node) &&
481
+ MUTATING_METHODS.has(node.expression.name.text) &&
482
+ isStateRoot(node.expression.expression);
483
+ if (isAssignment || isUpdate || isMutation) return true;
484
+ if (ts.isCallExpression(node)) {
485
+ const helper = getTopLevelDeclaration(getSymbol(node.expression, context.checker));
486
+ if (helper !== undefined && !visited.has(helper)) {
487
+ visited.add(helper);
488
+ if (writesState(helper, context, visited)) return true;
489
+ }
490
+ }
491
+ return (
492
+ ts.forEachChild(node, (child) => writesState(child, context, visited) || undefined) ?? false
493
+ );
494
+ };