tla-ts 0.0.8 → 0.0.9-dev.0dd11f695

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 (119) hide show
  1. package/README.md +30 -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 +40 -40
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +98 -19
  8. package/dist/index.d.ts +98 -19
  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-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +128 -106
  21. package/dist/transfer.js +128 -106
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -3
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlc-arguments.ts +646 -0
  35. package/src/cli/tlc-usage.ts +362 -0
  36. package/src/cli/tlc.ts +571 -185
  37. package/src/cli/typescript.ts +26 -0
  38. package/src/cli/xml-exporter.ts +4 -10
  39. package/src/codegen.ts +190 -51
  40. package/src/config.ts +101 -68
  41. package/src/coverage.ts +855 -0
  42. package/src/dependencies.ts +340 -24
  43. package/src/dfid.ts +636 -0
  44. package/src/environment.ts +289 -109
  45. package/src/errors.ts +142 -45
  46. package/src/evaluate.ts +734 -980
  47. package/src/exit-codes.ts +37 -1
  48. package/src/index.ts +3 -0
  49. package/src/instances.ts +85 -9
  50. package/src/java-overrides.ts +2 -12
  51. package/src/json-reader.ts +456 -0
  52. package/src/json.ts +262 -139
  53. package/src/levels.ts +2 -3
  54. package/src/lexer.ts +150 -70
  55. package/src/liveness-checker.ts +10 -18
  56. package/src/liveness.ts +122 -64
  57. package/src/parallel-worker.ts +14 -10
  58. package/src/parallel.ts +41 -17
  59. package/src/parser.ts +436 -90
  60. package/src/pcal/ast.ts +7 -28
  61. package/src/pcal/parse.ts +11 -39
  62. package/src/pcal/tokenize.ts +4 -20
  63. package/src/pcal/translate.ts +10 -42
  64. package/src/pcal/validate.ts +3 -21
  65. package/src/pretty-print.ts +1 -2
  66. package/src/prover/smt/solver/solver.ts +31 -27
  67. package/src/randomization.ts +84 -35
  68. package/src/resolve.ts +18 -60
  69. package/src/runtime.ts +11 -4
  70. package/src/sany/builtins.ts +3 -4
  71. package/src/sany/generator.ts +128 -176
  72. package/src/sany/levels.ts +6 -30
  73. package/src/sany/lexer.ts +7 -23
  74. package/src/sany/linter.ts +31 -29
  75. package/src/sany/modules.ts +1 -5
  76. package/src/sany/nodes.ts +4 -28
  77. package/src/sany/parse-error.ts +44 -100
  78. package/src/sany/report.ts +25 -40
  79. package/src/sany/selectors.ts +8 -22
  80. package/src/sany/source.ts +8 -15
  81. package/src/sany/xml.ts +11 -42
  82. package/src/search.ts +550 -150
  83. package/src/simulate.ts +694 -0
  84. package/src/spec-description.ts +167 -49
  85. package/src/standard-definitions.ts +2 -3
  86. package/src/standard-modules.ts +264 -68
  87. package/src/state-graph.ts +51 -18
  88. package/src/subexpressions.ts +31 -5
  89. package/src/successors.ts +269 -85
  90. package/src/symmetry.ts +59 -147
  91. package/src/tableau.ts +1 -2
  92. package/src/tlc/fingerprint.ts +226 -151
  93. package/src/tlc/jar-data.ts +113 -6
  94. package/src/tlc/messages.ts +122 -37
  95. package/src/tlc/order.ts +56 -82
  96. package/src/tlc/random.ts +16 -16
  97. package/src/tlc/replay.ts +564 -212
  98. package/src/tlc/summary.ts +2 -4
  99. package/src/tlc/tlc-operators.ts +81 -36
  100. package/src/tlc/tlcext-operators.ts +138 -117
  101. package/src/tlc/trace-spec.ts +273 -0
  102. package/src/tlc/value-stream.ts +143 -0
  103. package/src/tlc/version.ts +2 -4
  104. package/src/typescript/actions.ts +494 -0
  105. package/src/typescript/collections.ts +615 -0
  106. package/src/typescript/compile.ts +70 -0
  107. package/src/typescript/context.ts +106 -0
  108. package/src/typescript/emit.ts +122 -0
  109. package/src/typescript/expressions.ts +508 -0
  110. package/src/typescript/formula.ts +160 -0
  111. package/src/typescript/functions.ts +295 -0
  112. package/src/typescript/model.ts +164 -0
  113. package/src/typescript/names.ts +116 -0
  114. package/src/typescript/program.ts +51 -0
  115. package/src/typescript/properties.ts +148 -0
  116. package/src/typescript/scope.ts +117 -0
  117. package/src/typescript/steps.ts +175 -0
  118. package/src/typescript/types.ts +178 -0
  119. package/src/values.ts +910 -318
@@ -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
+ };