@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6558 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16076 -0
  12. package/dist/index.js.map +61 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1078 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,1336 @@
1
+ import {
2
+ type HttpMethod,
3
+ httpMethods,
4
+ identityDigest,
5
+ jobError,
6
+ reservedErrors,
7
+ } from "@tsplc/compiler/ir";
8
+ import { jobStateFields } from "@tsplc/debug/manifest";
9
+ import ts from "typescript";
10
+ import type { AsyncContext, Job, MethodMembers, SourceRewrite } from "./async";
11
+ import { copyValue } from "./cooperative";
12
+ import { loweringKey } from "./lowering-key";
13
+ import type { NamedRoutine } from "./module-graph";
14
+ import {
15
+ copied,
16
+ type Edit,
17
+ edited,
18
+ from,
19
+ joined,
20
+ type Mapped,
21
+ mapped,
22
+ type Part,
23
+ } from "./positions";
24
+ import { holdsBorrow, symbolAt } from "./sdk";
25
+ import { backgroundJob } from "./tasks";
26
+ import {
27
+ calleeName,
28
+ hasModifier,
29
+ isAggregateType,
30
+ isPropertyName,
31
+ namedRecordText,
32
+ promisedType,
33
+ } from "./types";
34
+
35
+ type Step = Job["steps"][number];
36
+ /** What a step does when the operation it waits on fails; `cancellable` failures may be a cancel. */
37
+ type Reject = (error: Part, options: { cancellable: boolean }) => Part;
38
+
39
+ /**
40
+ * How the generated code names what it reads on its block: the members the coroutine adds, the
41
+ * methods that run it, and, in an async method, the members of the method's own class.
42
+ */
43
+ interface Naming {
44
+ member: (name: string) => string;
45
+ /** A method's declaration, with its modifier. */
46
+ entry: (name: keyof MethodMembers) => string;
47
+ /** `this.name` of a method's own class; undefined in a function, which has none. */
48
+ own: ((name: string) => string) | undefined;
49
+ }
50
+
51
+ const blockEntries: Record<keyof MethodMembers, string> = {
52
+ start: "start",
53
+ reset: "reset",
54
+ snapshot: "snapshot",
55
+ advance: "protected execute",
56
+ };
57
+
58
+ /** An async function's own block. */
59
+ const blockNaming: Naming = {
60
+ member: (name) => name,
61
+ entry: (name) => blockEntries[name],
62
+ own: undefined,
63
+ };
64
+
65
+ const isHttpMethod = (value: string | undefined): value is HttpMethod =>
66
+ httpMethods.some((method) => method === value);
67
+
68
+ /** A parameter, local or caught error, which lives on the block across suspensions. */
69
+ interface Field {
70
+ name: string;
71
+ type: string;
72
+ aggregate: boolean;
73
+ }
74
+
75
+ /** Statements that end in a semicolon. */
76
+ const terminated = (node: ts.Node) =>
77
+ ts.isExpressionStatement(node) ||
78
+ ts.isVariableStatement(node) ||
79
+ ts.isReturnStatement(node) ||
80
+ ts.isThrowStatement(node) ||
81
+ ts.isBreakOrContinueStatement(node);
82
+
83
+ /** The operator a compound update in a loop header applies. */
84
+ const compoundSteps = new Map<ts.SyntaxKind, string>([
85
+ [ts.SyntaxKind.PlusEqualsToken, "+"],
86
+ [ts.SyntaxKind.MinusEqualsToken, "-"],
87
+ ]);
88
+
89
+ /** The call an await waits on. */
90
+ const awaitedCall = (node: ts.Node) =>
91
+ ts.isAwaitExpression(node) ? node.expression : node;
92
+
93
+ const containsAwait = (node: ts.Node, source: ts.SourceFile): boolean =>
94
+ ts.isAwaitExpression(node) ||
95
+ node.getChildren(source).some((child) => containsAwait(child, source));
96
+
97
+ /** Whether the coroutine copies a statement into one step as written, rather than lowering it into steps. */
98
+ export const copiedWhole = (
99
+ statement: ts.Statement,
100
+ source: ts.SourceFile,
101
+ ): boolean =>
102
+ ts.isSwitchStatement(statement) ||
103
+ (ts.isIterationStatement(statement, false) &&
104
+ !containsAwait(statement, source));
105
+
106
+ /**
107
+ * A job's code identity: its steps, their targets and the state they keep. A job stores it when it
108
+ * starts and stops with `codeChanged` when an online change brings other code, since its step and
109
+ * fields were made for the code it started with. Never 0, the value of a field an online change adds.
110
+ */
111
+ const codeDigest = (code: string): number =>
112
+ Number.parseInt(identityDigest(code), 16) || 1;
113
+
114
+ /** URL expressions are compile-time values, never reads from mutable PLC state. */
115
+ const staticString = (
116
+ checker: ts.TypeChecker,
117
+ root: ts.Expression,
118
+ ): string | undefined => {
119
+ const active = new Set<ts.Node>();
120
+ const valueNode = (node: ts.Node): ts.Node | undefined => {
121
+ if (ts.isParenthesizedExpression(node)) {
122
+ return node.expression;
123
+ }
124
+ if (ts.isIdentifier(node)) {
125
+ const declaration = symbolAt(checker, node)?.declarations?.find(
126
+ ts.isVariableDeclaration,
127
+ );
128
+ if (
129
+ declaration &&
130
+ ts.isVariableDeclarationList(declaration.parent) &&
131
+ declaration.parent.flags & ts.NodeFlags.Const
132
+ ) {
133
+ return declaration.initializer;
134
+ }
135
+ }
136
+ if (ts.isPropertyAccessExpression(node)) {
137
+ const field = symbolAt(checker, node.name);
138
+ if (
139
+ !field?.declarations?.some(
140
+ (declaration) =>
141
+ ts.canHaveModifiers(declaration) &&
142
+ hasModifier(declaration, ts.SyntaxKind.ReadonlyKeyword),
143
+ )
144
+ ) {
145
+ return;
146
+ }
147
+ const object = resolve(node.expression);
148
+ if (object && ts.isObjectLiteralExpression(object)) {
149
+ for (const property of object.properties) {
150
+ if (
151
+ ts.isPropertyAssignment(property) &&
152
+ (ts.isIdentifier(property.name) ||
153
+ ts.isStringLiteral(property.name)) &&
154
+ property.name.text === node.name.text
155
+ ) {
156
+ return property.initializer;
157
+ }
158
+ }
159
+ }
160
+ return;
161
+ }
162
+ return node;
163
+ };
164
+ const resolve = (node: ts.Node): ts.Node | undefined => {
165
+ if (active.has(node)) {
166
+ return;
167
+ }
168
+ active.add(node);
169
+ try {
170
+ const next = valueNode(node);
171
+ return next && next !== node ? resolve(next) : next;
172
+ } finally {
173
+ active.delete(node);
174
+ }
175
+ };
176
+ const read = (node: ts.Node): string | undefined => {
177
+ const resolved = resolve(node);
178
+ if (!resolved || active.has(resolved)) {
179
+ return;
180
+ }
181
+ active.add(resolved);
182
+ try {
183
+ if (
184
+ ts.isStringLiteral(resolved) ||
185
+ ts.isNoSubstitutionTemplateLiteral(resolved)
186
+ ) {
187
+ return resolved.text;
188
+ }
189
+ if (ts.isTemplateExpression(resolved)) {
190
+ let value = resolved.head.text;
191
+ for (const part of resolved.templateSpans) {
192
+ const item = read(part.expression);
193
+ if (item === undefined) {
194
+ return;
195
+ }
196
+ value += item + part.literal.text;
197
+ }
198
+ return value;
199
+ }
200
+ if (
201
+ ts.isBinaryExpression(resolved) &&
202
+ resolved.operatorToken.kind === ts.SyntaxKind.PlusToken
203
+ ) {
204
+ const left = read(resolved.left);
205
+ const right = read(resolved.right);
206
+ if (left !== undefined && right !== undefined) {
207
+ return left + right;
208
+ }
209
+ }
210
+ } finally {
211
+ active.delete(resolved);
212
+ }
213
+ };
214
+ return read(root);
215
+ };
216
+
217
+ /**
218
+ * Replaces an async routine with a block that runs it as a resumable state machine. An async
219
+ * method's block joins its own class as members, renamed apart from the class's own.
220
+ */
221
+ export function lowerCoroutine(
222
+ context: AsyncContext,
223
+ file: SourceRewrite,
224
+ fn: NamedRoutine,
225
+ ): void {
226
+ const symbol = context.symbol(fn.name);
227
+ const method = symbol && context.methods.get(symbol);
228
+ const replace = (text: Part) =>
229
+ file.replacements.push({
230
+ start: fn.getStart(file.source),
231
+ end: fn.end,
232
+ text,
233
+ });
234
+ if (!method) {
235
+ const coroutine = new Coroutine(context, file, fn, blockNaming);
236
+ replace(coroutine.blockClass(coroutine.digest()));
237
+ const name = fn.name.getText(file.source);
238
+ file.jobs.set(loweringKey(file.source.fileName, name), {
239
+ name,
240
+ span: context.positions.node(fn),
241
+ steps: coroutine.steps,
242
+ });
243
+ return;
244
+ }
245
+ // The digest is of the code as a block of its own would run it, with the class's members as
246
+ // `this["name"]`, which keeps the digests an online change compares from one build to the next.
247
+ const code = new Coroutine(
248
+ context,
249
+ {
250
+ source: file.source,
251
+ extra: [],
252
+ importedAliases: new Set(),
253
+ blocks: new Map(),
254
+ },
255
+ fn,
256
+ {
257
+ ...blockNaming,
258
+ own: (name) => `this[${JSON.stringify(name)}]`,
259
+ },
260
+ ).digest();
261
+ const prefix = context.names.name("tsplcAsync", fn);
262
+ const members = new Coroutine(context, file, fn, {
263
+ member: (name) => `${prefix}_${name}`,
264
+ entry: (name) => `public ${method[name]}`,
265
+ own: (name) => `this.${name}`,
266
+ }).members(code);
267
+ replace(joined(members, "\n"));
268
+ }
269
+
270
+ /**
271
+ * One async routine's block under construction. Each step is a case of the block's state
272
+ * machine; awaiting an operation adds a child block or borrow that the steps start and poll.
273
+ */
274
+ class Coroutine {
275
+ private readonly body: ts.Block;
276
+ private readonly returnsVoid: boolean;
277
+ private readonly returnType: string;
278
+ private readonly resultAggregate: boolean;
279
+ private readonly fields = new Map<ts.Symbol, Field>();
280
+ private readonly parameters: (Field & { field: string })[];
281
+ private readonly states = new Map<number, Mapped>();
282
+ /** The loops that suspend, innermost last, with the steps their break and continue go to. */
283
+ private readonly loops: { breakStep: number; continueStep: number }[] = [];
284
+ private readonly yielding = new Set<number>();
285
+ readonly steps: Step[] = [];
286
+ private readonly children: string[] = [];
287
+ private readonly resets: string[] = [];
288
+ private readonly cancels: string[] = [];
289
+
290
+ private readonly entry: number;
291
+
292
+ constructor(
293
+ private readonly context: AsyncContext,
294
+ private readonly file: Pick<
295
+ SourceRewrite,
296
+ "source" | "extra" | "importedAliases" | "blocks"
297
+ >,
298
+ private readonly fn: NamedRoutine,
299
+ private readonly naming: Naming,
300
+ ) {
301
+ const promised = fn.type && promisedType(fn.type);
302
+ if (!fn.body || fn.typeParameters?.length || !promised) {
303
+ context.fail(
304
+ fn,
305
+ "Async functions require concrete parameters and an explicit Promise<T> result.",
306
+ );
307
+ }
308
+ this.body = fn.body;
309
+ this.returnsVoid = promised.kind === ts.SyntaxKind.VoidKeyword;
310
+ this.returnType = this.returnsVoid ? "BOOL" : this.text(promised);
311
+ this.resultAggregate = isAggregateType(
312
+ context.checker.getTypeFromTypeNode(promised),
313
+ );
314
+ this.parameters = fn.parameters.map((parameter, index) =>
315
+ this.parameter(parameter, index),
316
+ );
317
+ this.collect(fn.body);
318
+ const end = this.body.getLastToken(file.source);
319
+ if (!end) {
320
+ throw new Error("A block body ends in a brace.");
321
+ }
322
+ this.entry = this.block(
323
+ this.body.statements,
324
+ this.returnsVoid
325
+ ? this.state(this.finish("true"), end, "return", { yields: false })
326
+ : this.state(this.failure(jobError.malformedResponse), end, "throw", {
327
+ yields: false,
328
+ }),
329
+ (error) => this.failure(error),
330
+ );
331
+ }
332
+
333
+ private text(node: ts.Node): string {
334
+ return node.getText(this.file.source);
335
+ }
336
+
337
+ /** `this.name` of a member the coroutine adds. */
338
+ private self(name: string): string {
339
+ return `this.${this.naming.member(name)}`;
340
+ }
341
+
342
+ /** A symbol the program declares, which every declaration the coroutine reads has. */
343
+ private declared(node: ts.Node): ts.Symbol {
344
+ const symbol = this.context.symbol(node);
345
+ if (!symbol) {
346
+ throw new Error(`${node.getText(this.file.source)} declares no symbol.`);
347
+ }
348
+ return symbol;
349
+ }
350
+
351
+ private parameter(
352
+ parameter: ts.ParameterDeclaration,
353
+ index: number,
354
+ ): Field & { field: string } {
355
+ if (
356
+ !ts.isIdentifier(parameter.name) ||
357
+ !parameter.type ||
358
+ parameter.initializer ||
359
+ parameter.questionToken ||
360
+ parameter.dotDotDotToken
361
+ ) {
362
+ this.context.fail(
363
+ parameter,
364
+ "Async parameters require explicit concrete value types.",
365
+ );
366
+ }
367
+ if (holdsBorrow(this.context, parameter.type)) {
368
+ this.context.fail(
369
+ parameter,
370
+ "InOut cannot cross an async suspension; pass a value snapshot.",
371
+ );
372
+ }
373
+ const type = this.text(parameter.type);
374
+ const aggregate = isAggregateType(
375
+ this.context.checker.getTypeFromTypeNode(parameter.type),
376
+ );
377
+ const field = `argument${index}`;
378
+ this.fields.set(this.declared(parameter.name), {
379
+ name: field,
380
+ type,
381
+ aggregate,
382
+ });
383
+ return { name: parameter.name.text, type, aggregate, field };
384
+ }
385
+
386
+ /** Moves the routine's locals and caught errors onto the block, and rejects what cannot suspend. */
387
+ private collect(node: ts.Node): void {
388
+ // A loop that doesn't suspend runs within one step, with its own locals.
389
+ if (
390
+ ts.isIterationStatement(node, false) &&
391
+ copiedWhole(node, this.file.source)
392
+ ) {
393
+ return;
394
+ }
395
+ if (ts.isForOfStatement(node)) {
396
+ this.context.fail(
397
+ node,
398
+ "A for…of whose body awaits is not supported; count through the array's indexes with a for loop.",
399
+ );
400
+ }
401
+ if (ts.isFunctionLike(node) && node !== this.fn) {
402
+ this.context.fail(
403
+ node,
404
+ "Closures and nested functions are not supported in async PLC routines.",
405
+ );
406
+ }
407
+ if (ts.isCatchClause(node)) {
408
+ const declaration = node.variableDeclaration;
409
+ if (declaration) {
410
+ if (!ts.isIdentifier(declaration.name)) {
411
+ this.context.fail(
412
+ declaration,
413
+ "Catch requires a named error code or no binding.",
414
+ );
415
+ }
416
+ this.fields.set(this.declared(declaration.name), {
417
+ name: `caught${this.fields.size}`,
418
+ type: "UDINT",
419
+ aggregate: false,
420
+ });
421
+ }
422
+ this.collect(node.block);
423
+ return;
424
+ }
425
+ if (ts.isVariableDeclaration(node)) {
426
+ if (!ts.isIdentifier(node.name) || !node.initializer) {
427
+ this.context.fail(node, "Async locals need names and initializers.");
428
+ }
429
+ const type = node.type
430
+ ? this.text(node.type)
431
+ : this.inferredType(node, node.initializer);
432
+ if (!type) {
433
+ this.context.fail(
434
+ node,
435
+ "Annotate async locals with their concrete PLC type.",
436
+ );
437
+ }
438
+ this.fields.set(this.declared(node.name), {
439
+ name: `local${this.fields.size}`,
440
+ type,
441
+ aggregate: isAggregateType(
442
+ this.context.checker.getTypeAtLocation(node),
443
+ ),
444
+ });
445
+ }
446
+ ts.forEachChild(node, (child) => this.collect(child));
447
+ }
448
+
449
+ /** An unannotated local's type: BOOL for a boolean literal, or the result of the routine it awaits. */
450
+ private inferredType(
451
+ node: ts.VariableDeclaration,
452
+ initializer: ts.Expression,
453
+ ): string | undefined {
454
+ if (
455
+ initializer.kind === ts.SyntaxKind.TrueKeyword ||
456
+ initializer.kind === ts.SyntaxKind.FalseKeyword
457
+ ) {
458
+ return "BOOL";
459
+ }
460
+ if (
461
+ !ts.isAwaitExpression(initializer) ||
462
+ !ts.isCallExpression(initializer.expression)
463
+ ) {
464
+ return undefined;
465
+ }
466
+ const target = calleeName(initializer.expression.expression);
467
+ const symbol = target && this.context.symbol(target);
468
+ const called = symbol && this.context.functions.get(symbol);
469
+ const promised = called?.type && promisedType(called.type);
470
+ if (!called || !promised) {
471
+ return undefined;
472
+ }
473
+ const { source } = this.file;
474
+ if (called.getSourceFile() === source) {
475
+ return promised.getText(source);
476
+ }
477
+ const type = this.context.aliases(called).result;
478
+ this.context.importAliases(this.file, node, called, [type]);
479
+ return type;
480
+ }
481
+
482
+ /** The user's text with locals moved onto the block, so positions in it map exactly. */
483
+ private rewrite(node: ts.Node): Mapped {
484
+ const { source } = this.file;
485
+ const edits: Edit[] = [];
486
+ const visit = (child: ts.Node): void => {
487
+ // A step runs within one scan; only the awaits the statement lowering suspends at can wait.
488
+ if (ts.isAwaitExpression(child)) {
489
+ this.context.fail(
490
+ child,
491
+ "This suspension position is not supported; await into a named local or return.",
492
+ );
493
+ }
494
+ const replacement = this.replacement(child);
495
+ if (replacement === undefined) {
496
+ ts.forEachChild(child, visit);
497
+ } else {
498
+ edits.push({
499
+ start: child.getStart(source),
500
+ end: child.end,
501
+ text: replacement,
502
+ });
503
+ }
504
+ };
505
+ visit(node);
506
+ const start = node.getStart(source);
507
+ const rewritten = edited(
508
+ copied(node),
509
+ edits.map((edit) => ({
510
+ ...edit,
511
+ start: edit.start - start,
512
+ end: edit.end - start,
513
+ })),
514
+ );
515
+ // A statement written without its semicolon is followed by more code here.
516
+ return terminated(node) && !rewritten.text.endsWith(";")
517
+ ? mapped`${rewritten};`
518
+ : rewritten;
519
+ }
520
+
521
+ /** What a node becomes on the block: a field read, or a method's own member. */
522
+ private replacement(node: ts.Node): string | undefined {
523
+ const { own } = this.naming;
524
+ if (
525
+ own &&
526
+ ts.isPropertyAccessExpression(node) &&
527
+ node.expression.kind === ts.SyntaxKind.ThisKeyword
528
+ ) {
529
+ return own(node.name.text);
530
+ }
531
+ if (ts.isIdentifier(node) && !isPropertyName(node)) {
532
+ const symbol = this.context.symbol(node);
533
+ const field = symbol && this.fields.get(symbol);
534
+ if (field) {
535
+ return this.self(field.name);
536
+ }
537
+ }
538
+ if (ts.isShorthandPropertyAssignment(node)) {
539
+ const value =
540
+ this.context.checker.getShorthandAssignmentValueSymbol(node);
541
+ const field = value && this.fields.get(value);
542
+ if (field) {
543
+ return `${node.name.text}: ${this.self(field.name)}`;
544
+ }
545
+ }
546
+ return undefined;
547
+ }
548
+
549
+ /** A step of the job: `body` runs while it is current; `origin` is the source it runs. */
550
+ private state(
551
+ body: Part,
552
+ origin: ts.Node,
553
+ kind: Step["kind"],
554
+ { yields }: { yields: boolean },
555
+ ): number {
556
+ const id = this.states.size + 1;
557
+ this.states.set(id, from(origin, body));
558
+ this.steps.push({
559
+ step: id,
560
+ kind,
561
+ span: this.context.positions.node(origin),
562
+ text: this.context.positions.excerpt(
563
+ kind === "await" ? awaitedCall(origin) : origin,
564
+ ),
565
+ });
566
+ if (yields) {
567
+ this.yielding.add(id);
568
+ }
569
+ return id;
570
+ }
571
+
572
+ private finish(value: Part): Mapped {
573
+ return mapped`${this.self("value")} = ${copyValue(value, this.resultAggregate)}; ${this.self("busy")} = false; ${this.self("done")} = true; ${this.self("step")} = 0;`;
574
+ }
575
+
576
+ private failure(error: Part): Mapped {
577
+ const code = this.self("error");
578
+ return mapped`${code} = ${error}; if(${code} === 0)${code}=${jobError.malformedResponse}; ${this.self("busy")} = false; ${this.self("done")} = true; ${this.self("step")} = 0;`;
579
+ }
580
+
581
+ /** An awaited call's result as the target stores it: records and arrays are copied. */
582
+ private awaitedValue(value: string, call: ts.CallExpression): Part {
583
+ const { checker } = this.context;
584
+ const awaited = checker.getAwaitedType(checker.getTypeAtLocation(call));
585
+ return copyValue(value, awaited !== undefined && isAggregateType(awaited));
586
+ }
587
+
588
+ /** The steps that start and poll an awaited operation, then store its result in `target`. */
589
+ private awaitState(
590
+ awaited: ts.AwaitExpression | ts.CallExpression,
591
+ target: string | undefined,
592
+ next: number,
593
+ reject: Reject,
594
+ ): number {
595
+ const call = ts.isAwaitExpression(awaited) ? awaited.expression : awaited;
596
+ if (!ts.isCallExpression(call)) {
597
+ this.context.fail(
598
+ awaited,
599
+ "Await requires a tsPLC operation or a statically named async function.",
600
+ );
601
+ }
602
+ const name = calleeName(call.expression);
603
+ if (!name) {
604
+ this.context.fail(
605
+ call,
606
+ "Await requires a known async helper or SDK operation.",
607
+ );
608
+ }
609
+ const awaiting = { awaited, call, target, next, reject };
610
+ if (this.context.namesSdk(name, "sleep")) {
611
+ return this.sleepState(awaiting);
612
+ }
613
+ const rpc = this.context.namesSdk(name, "opcuaCall");
614
+ if (rpc || this.context.namesSdk(name, "fetch")) {
615
+ return this.requestState(awaiting, { rpc });
616
+ }
617
+ const symbol = this.context.symbol(name);
618
+ if (backgroundJob(this.context, symbol)) {
619
+ return this.jobState(awaiting);
620
+ }
621
+ if (!symbol || !this.context.functions.has(symbol)) {
622
+ this.context.fail(
623
+ call,
624
+ "Await requires a known async helper or SDK operation.",
625
+ );
626
+ }
627
+ const method = this.context.methods.get(symbol);
628
+ if (method) {
629
+ return this.methodState(awaiting, method);
630
+ }
631
+ return this.helperState(awaiting);
632
+ }
633
+
634
+ /** `await sleep(duration)`: an on-delay timer child. */
635
+ private sleepState({ awaited, call, target, next }: Awaiting): number {
636
+ const child = `child${this.children.length}`;
637
+ const [duration, ...rest] = call.arguments;
638
+ if (!duration || rest.length || call.typeArguments?.length || target) {
639
+ this.context.fail(call, "sleep takes one TIME and returns void.");
640
+ }
641
+ this.children.push(
642
+ `private ${this.naming.member(child)} = new OnDelayTimer();`,
643
+ );
644
+ this.resets.push(
645
+ `${this.self(child)}.update({enabled:false,duration:ms(0)});`,
646
+ );
647
+ const poll = this.state(
648
+ mapped`${this.self(child)}.update({enabled:true,duration:${this.rewrite(duration)}}); if(${this.self(child)}.out.done) { ${this.self("step")} = ${next}; }`,
649
+ awaited,
650
+ "await",
651
+ { yields: false },
652
+ );
653
+ return this.state(
654
+ mapped`${this.self(child)}.update({enabled:true,duration:${this.rewrite(duration)}});${this.self("step")}=${poll};`,
655
+ awaited,
656
+ "await",
657
+ { yields: true },
658
+ );
659
+ }
660
+
661
+ /** `await fetch(url, options)` or `await opcuaCall(path, request)`: an HTTP or RPC child block. */
662
+ private requestState(
663
+ { awaited, call, target, next, reject }: Awaiting,
664
+ { rpc }: { rpc: boolean },
665
+ ): number {
666
+ const { checker } = this.context;
667
+ const { source, extra, blocks } = this.file;
668
+ const child = `child${this.children.length}`;
669
+ const [address, second, ...rest] = call.arguments;
670
+ const [response, request, ...more] = call.typeArguments ?? [];
671
+ if (!address || rest.length || !response || more.length) {
672
+ this.context.fail(
673
+ call,
674
+ "fetch<Response, Request?> requires a URL and optional { method, json } options.",
675
+ );
676
+ }
677
+ const url = staticString(checker, address);
678
+ if (url === undefined) {
679
+ this.context.fail(
680
+ address,
681
+ "fetch URL must be a literal or compile-time const string; configuration properties must be readonly.",
682
+ );
683
+ }
684
+ const { method, json } = rpc
685
+ ? { method: "POST" as const, json: second }
686
+ : this.fetchOptions(second);
687
+ if (method === "GET" && json) {
688
+ this.context.fail(call, "GET requests cannot contain json.");
689
+ }
690
+ const responseType = this.text(response);
691
+ const httpName = this.context.names.name(
692
+ `Tsplc${rpc ? "Rpc" : "Http"}`,
693
+ call,
694
+ );
695
+ if (!json) {
696
+ extra.push(from(call, `interface ${httpName}Request {reserved:BOOL}`));
697
+ }
698
+ const requestType = json
699
+ ? this.requestType(json, request)
700
+ : `${httpName}Request`;
701
+ extra.push(
702
+ from(
703
+ call,
704
+ `interface ${httpName}Input {start:BOOL;cancel:BOOL;request:${requestType}}
705
+ interface ${httpName}Output {busy:BOOL;done:BOOL;error:UDINT;result:${responseType}}
706
+ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { protected execute(input:${httpName}Input):${httpName}Output {return {busy:false,done:false,error:0,result:defaultValue<${responseType}>()};} }`,
707
+ ),
708
+ );
709
+ blocks.set(
710
+ loweringKey(source.fileName, httpName),
711
+ rpc
712
+ ? { kind: "rpc", path: url }
713
+ : {
714
+ kind: "http",
715
+ url,
716
+ method,
717
+ json: Boolean(json),
718
+ },
719
+ );
720
+ this.children.push(
721
+ `private ${this.naming.member(child)} = new ${httpName}();`,
722
+ );
723
+ this.resets.push(
724
+ `${this.self(child)}.update({start:false,cancel:false,request:defaultValue<${requestType}>()});`,
725
+ );
726
+ this.cancels.push(
727
+ `${this.self(child)}.update({start:false,cancel:true,request:defaultValue<${requestType}>()});`,
728
+ );
729
+ return this.state(
730
+ mapped`${this.self(child)}.update({start:true,cancel:false,request:${json ? this.rewrite(json) : `defaultValue<${requestType}>()`}}); if(${this.self(child)}.out.done) { if(${this.self(child)}.out.error !== 0) {${reject(`${this.self(child)}.out.error`, { cancellable: true })}} else {${target ? mapped`${target} = ${this.awaitedValue(`${this.self(child)}.out.result`, call)};` : ""}${this.self("step")} = ${next};} }`,
731
+ awaited,
732
+ "await",
733
+ { yields: false },
734
+ );
735
+ }
736
+
737
+ /** A fetch's inline `{ method, json }` options. */
738
+ private fetchOptions(options: ts.Expression | undefined): {
739
+ method: HttpMethod;
740
+ json: ts.Expression | undefined;
741
+ } {
742
+ if (!options) {
743
+ return { method: "GET", json: undefined };
744
+ }
745
+ if (!ts.isObjectLiteralExpression(options)) {
746
+ this.context.fail(
747
+ options,
748
+ "fetch options must be an inline { method, json } object.",
749
+ );
750
+ }
751
+ const chosen: { method: HttpMethod; json: ts.Expression | undefined } = {
752
+ method: "GET",
753
+ json: undefined,
754
+ };
755
+ for (const property of options.properties) {
756
+ if (
757
+ !ts.isPropertyAssignment(property) ||
758
+ !ts.isIdentifier(property.name)
759
+ ) {
760
+ this.context.fail(property, "fetch options require named properties.");
761
+ }
762
+ if (property.name.text === "method") {
763
+ const value = staticString(this.context.checker, property.initializer);
764
+ if (!isHttpMethod(value)) {
765
+ this.context.fail(property, "Unsupported fetch method.");
766
+ }
767
+ chosen.method = value;
768
+ } else if (property.name.text === "json") {
769
+ chosen.json = property.initializer;
770
+ } else {
771
+ this.context.fail(property, "Unsupported fetch option.");
772
+ }
773
+ }
774
+ return chosen;
775
+ }
776
+
777
+ /** A json body's PLC record: the Request type argument, or the named type of the value. */
778
+ private requestType(
779
+ json: ts.Expression,
780
+ request: ts.TypeNode | undefined,
781
+ ): string {
782
+ if (request) {
783
+ return this.text(request);
784
+ }
785
+ return (
786
+ namedRecordText(this.context.checker, json) ??
787
+ this.context.fail(
788
+ json,
789
+ "Annotate json with a named PLC record or supply the Request type argument.",
790
+ )
791
+ );
792
+ }
793
+
794
+ /** `await job(...)` on a background task: borrow its mailbox until the result is taken. */
795
+ private jobState({ awaited, call, target, next, reject }: Awaiting): number {
796
+ const receiver = this.rewrite(call.expression);
797
+ const borrow = `borrow${this.children.length}`;
798
+ this.children.push(`private ${this.naming.member(borrow)}:BOOL=false;`);
799
+ this.resets.push(`${this.self(borrow)}=false;`);
800
+ this.cancels.push(
801
+ `if(${this.self(borrow)}){${receiver}.cancel();const borrowed=${receiver}.snapshot();if(!borrowed.valid||borrowed.busy)return;if(!${receiver}.reset())return;${this.self(borrow)}=false;}`,
802
+ );
803
+ const poll = this.state(
804
+ mapped`const borrowed=${receiver}.snapshot();if(borrowed.valid&&borrowed.done){if(${receiver}.reset()){${this.self(borrow)}=false;if(borrowed.error!==0){${reject("borrowed.error", { cancellable: true })}}else{${target ? mapped`${target}=${this.awaitedValue("borrowed.result", call)};` : ""}${this.self("step")}=${next};}}}`,
805
+ awaited,
806
+ "await",
807
+ { yields: false },
808
+ );
809
+ return this.state(
810
+ mapped`const available=${receiver}.snapshot();if(!available.valid)return;if(available.busy||available.done){${reject(jobError.noRequestSlot, { cancellable: false })}}else{const accepted:BOOL=${receiver}.start(${joined(
811
+ call.arguments.map((argument) => this.rewrite(argument)),
812
+ ",",
813
+ )});if(accepted){${this.self(borrow)}=true;${this.self("step")}=${poll};}}`,
814
+ awaited,
815
+ "await",
816
+ { yields: true },
817
+ );
818
+ }
819
+
820
+ /** `await instance.method(...)`: drive the async method's members on its block. */
821
+ private methodState(
822
+ { awaited, call, target, next, reject }: Awaiting,
823
+ method: MethodMembers,
824
+ ): number {
825
+ if (!ts.isPropertyAccessExpression(call.expression)) {
826
+ this.context.fail(call, "Async methods require a static receiver.");
827
+ }
828
+ const receiver = this.rewrite(call.expression.expression);
829
+ const borrow = `methodBorrow${this.children.length}`;
830
+ this.children.push(`private ${this.naming.member(borrow)}:BOOL=false;`);
831
+ this.resets.push(
832
+ `if(${this.self(borrow)}){${receiver}.${method.reset}();${this.self(borrow)}=false;}`,
833
+ );
834
+ this.cancels.push(
835
+ `if(${this.self(borrow)}){${receiver}.${method.advance}({cancel:true});const cancellingChild=${receiver}.${method.snapshot}();if(cancellingChild.busy)return;${receiver}.${method.reset}();${this.self(borrow)}=false;}`,
836
+ );
837
+ const poll = this.state(
838
+ mapped`${receiver}.${method.advance}({cancel:false});const childState=${receiver}.${method.snapshot}();if(childState.done){${receiver}.${method.reset}();${this.self(borrow)}=false;if(childState.error!==0){${reject("childState.error", { cancellable: true })}}else{${target ? mapped`${target}=${this.awaitedValue("childState.result", call)};` : ""}${this.self("step")}=${next};}}`,
839
+ awaited,
840
+ "await",
841
+ { yields: false },
842
+ );
843
+ return this.state(
844
+ mapped`const accepted:BOOL=${receiver}.${method.start}(${joined(
845
+ call.arguments.map((argument) => this.rewrite(argument)),
846
+ ",",
847
+ )});if(!accepted){${reject(jobError.noRequestSlot, { cancellable: false })}}else{${this.self(borrow)}=true;${receiver}.${method.advance}({cancel:false});${this.self("step")}=${poll};}`,
848
+ awaited,
849
+ "await",
850
+ { yields: true },
851
+ );
852
+ }
853
+
854
+ /** `await helper(...)`: the helper's own coroutine block as a child. */
855
+ private helperState({
856
+ awaited,
857
+ call,
858
+ target,
859
+ next,
860
+ reject,
861
+ }: Awaiting): number {
862
+ const child = `child${this.children.length}`;
863
+ if (!ts.isIdentifier(call.expression)) {
864
+ this.context.fail(call, "Async helpers require a static function.");
865
+ }
866
+ this.children.push(
867
+ `private ${this.naming.member(child)} = new ${this.text(call.expression)}();`,
868
+ );
869
+ this.resets.push(`${this.self(child)}.reset();`);
870
+ this.cancels.push(
871
+ `${this.self(child)}.update({cancel:true});const cancellingChild=${this.self(child)}.snapshot();if(cancellingChild.busy)return;`,
872
+ );
873
+ const poll = this.state(
874
+ mapped`${this.self(child)}.update({cancel:false}); const childState = ${this.self(child)}.snapshot(); if(childState.done) {if(childState.error !== 0) {${reject("childState.error", { cancellable: true })}} else {${target ? mapped`${target} = ${this.awaitedValue("childState.result", call)};` : ""}${this.self("step")} = ${next};} }`,
875
+ awaited,
876
+ "await",
877
+ { yields: false },
878
+ );
879
+ return this.state(
880
+ mapped`const accepted:BOOL = ${this.self(child)}.start(${joined(
881
+ call.arguments.map((argument) => this.rewrite(argument)),
882
+ ",",
883
+ )}); if(accepted){${this.self(child)}.update({cancel:false});${this.self("step")} = ${poll};}`,
884
+ awaited,
885
+ "await",
886
+ { yields: true },
887
+ );
888
+ }
889
+
890
+ /** Lowers statements back to front, so each knows the step that follows it; returns the first. */
891
+ private block(
892
+ statements: readonly ts.Statement[],
893
+ next: number,
894
+ reject: Reject,
895
+ ): number {
896
+ return statements.reduceRight(
897
+ (following, statement) => this.statement(statement, following, reject),
898
+ next,
899
+ );
900
+ }
901
+
902
+ private statement(
903
+ statement: ts.Statement,
904
+ next: number,
905
+ reject: Reject,
906
+ ): number {
907
+ const { checker } = this.context;
908
+ if (ts.isBlock(statement)) {
909
+ return this.block(statement.statements, next, reject);
910
+ }
911
+ if (ts.isIfStatement(statement)) {
912
+ const yes = this.block([statement.thenStatement], next, reject);
913
+ const no = statement.elseStatement
914
+ ? this.block([statement.elseStatement], next, reject)
915
+ : next;
916
+ return this.state(
917
+ mapped`if(${this.rewrite(statement.expression)}) ${this.self("step")} = ${yes}; else ${this.self("step")} = ${no};`,
918
+ statement.expression,
919
+ "statement",
920
+ { yields: false },
921
+ );
922
+ }
923
+ if (ts.isTryStatement(statement)) {
924
+ return this.tryStatement(statement, next, reject);
925
+ }
926
+ if (
927
+ ts.isIterationStatement(statement, false) &&
928
+ !copiedWhole(statement, this.file.source)
929
+ ) {
930
+ return this.loop(statement, next, reject);
931
+ }
932
+ const loop = this.loops.at(-1);
933
+ if (loop && ts.isBreakOrContinueStatement(statement) && !statement.label) {
934
+ return this.state(
935
+ `${this.self("step")} = ${ts.isBreakStatement(statement) ? loop.breakStep : loop.continueStep};`,
936
+ statement,
937
+ "statement",
938
+ { yields: false },
939
+ );
940
+ }
941
+ if (ts.isThrowStatement(statement)) {
942
+ if (
943
+ !checker.isTypeAssignableTo(
944
+ checker.getTypeAtLocation(statement.expression),
945
+ checker.getNumberType(),
946
+ )
947
+ ) {
948
+ this.context.fail(
949
+ statement,
950
+ "Async throw requires a numeric error code.",
951
+ );
952
+ }
953
+ // Only a literal code is checked; a computed one is the program's to keep out of the range.
954
+ if (
955
+ ts.isNumericLiteral(statement.expression) &&
956
+ Number(statement.expression.text) >= reservedErrors.first &&
957
+ Number(statement.expression.text) <= reservedErrors.last
958
+ ) {
959
+ this.context.fail(
960
+ statement,
961
+ `Error codes ${reservedErrors.first} to ${reservedErrors.last} are tsPLC's own; throw another code.`,
962
+ );
963
+ }
964
+ return this.state(
965
+ reject(this.rewrite(statement.expression), { cancellable: false }),
966
+ statement,
967
+ "throw",
968
+ { yields: false },
969
+ );
970
+ }
971
+ if (ts.isReturnStatement(statement)) {
972
+ return this.returnStatement(statement, reject);
973
+ }
974
+ if (ts.isVariableStatement(statement)) {
975
+ return [...statement.declarationList.declarations].reduceRight(
976
+ (following, declaration) =>
977
+ this.localInitializer(declaration, following, reject),
978
+ next,
979
+ );
980
+ }
981
+ if (
982
+ ts.isExpressionStatement(statement) &&
983
+ ts.isAwaitExpression(statement.expression)
984
+ ) {
985
+ return this.awaitState(statement.expression, undefined, next, reject);
986
+ }
987
+ if (ts.isWhileStatement(statement) || ts.isDoStatement(statement)) {
988
+ this.context.fail(
989
+ statement,
990
+ "Unbounded loops are not supported in async routines.",
991
+ );
992
+ }
993
+ // `count++;` and `total += n;` are assignments, the one form a step's statement takes.
994
+ const text = ts.isExpressionStatement(statement)
995
+ ? mapped`${this.updateText(statement.expression)};`
996
+ : this.rewrite(statement);
997
+ return this.state(
998
+ mapped`${text} ${this.self("step")} = ${next};`,
999
+ statement,
1000
+ "statement",
1001
+ { yields: false },
1002
+ );
1003
+ }
1004
+
1005
+ /**
1006
+ * A loop that suspends runs as steps: its test, its body's steps and its update, which leads back to
1007
+ * the test. Each scan takes a bounded number of steps, so its iterations spread across scans.
1008
+ */
1009
+ private loop(
1010
+ statement: ts.IterationStatement,
1011
+ next: number,
1012
+ reject: Reject,
1013
+ ): number {
1014
+ const test = this.reserve(statement, "statement");
1015
+ const update = this.loopUpdate(statement, test);
1016
+ this.loops.push({ breakStep: next, continueStep: update });
1017
+ const body = this.block([statement.statement], update, reject);
1018
+ this.loops.pop();
1019
+ this.fill(test, statement, this.loopTest(statement, body, next));
1020
+ if (ts.isDoStatement(statement)) {
1021
+ return body;
1022
+ }
1023
+ if (ts.isForStatement(statement) && statement.initializer) {
1024
+ const start = ts.isVariableDeclarationList(statement.initializer)
1025
+ ? statement.initializer.declarations.reduceRight(
1026
+ (following, declaration) =>
1027
+ this.localInitializer(declaration, following, reject),
1028
+ test,
1029
+ )
1030
+ : this.state(
1031
+ mapped`${this.rewrite(statement.initializer)}; ${this.self("step")} = ${test};`,
1032
+ statement.initializer,
1033
+ "statement",
1034
+ { yields: false },
1035
+ );
1036
+ return start;
1037
+ }
1038
+ return test;
1039
+ }
1040
+
1041
+ /** The step that moves a loop on to its next iteration, then back to its test. */
1042
+ private loopUpdate(statement: ts.IterationStatement, test: number): number {
1043
+ if (ts.isForStatement(statement) && statement.incrementor) {
1044
+ return this.state(
1045
+ mapped`${this.updateText(statement.incrementor)}; ${this.self("step")} = ${test};`,
1046
+ statement.incrementor,
1047
+ "statement",
1048
+ { yields: false },
1049
+ );
1050
+ }
1051
+ return test;
1052
+ }
1053
+
1054
+ /** An update as an assignment, the one form a step's statement takes: `i++` is `i = i + 1`. */
1055
+ private updateText(incrementor: ts.Expression): Mapped {
1056
+ if (
1057
+ (ts.isPrefixUnaryExpression(incrementor) ||
1058
+ ts.isPostfixUnaryExpression(incrementor)) &&
1059
+ (incrementor.operator === ts.SyntaxKind.PlusPlusToken ||
1060
+ incrementor.operator === ts.SyntaxKind.MinusMinusToken)
1061
+ ) {
1062
+ const target = this.rewrite(incrementor.operand);
1063
+ return mapped`${target} = ${target} ${incrementor.operator === ts.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`;
1064
+ }
1065
+ const compound =
1066
+ ts.isBinaryExpression(incrementor) &&
1067
+ compoundSteps.get(incrementor.operatorToken.kind);
1068
+ if (ts.isBinaryExpression(incrementor) && compound) {
1069
+ const target = this.rewrite(incrementor.left);
1070
+ return mapped`${target} = ${target} ${compound} ${this.rewrite(incrementor.right)}`;
1071
+ }
1072
+ return this.rewrite(incrementor);
1073
+ }
1074
+
1075
+ /** The step a loop takes before each iteration: into its body while it goes on, else past it. */
1076
+ private loopTest(
1077
+ statement: ts.IterationStatement,
1078
+ body: number,
1079
+ next: number,
1080
+ ): Mapped {
1081
+ const condition = loopCondition(statement);
1082
+ if (!condition) {
1083
+ return mapped`${this.self("step")} = ${body};`;
1084
+ }
1085
+ return mapped`if (${this.rewrite(condition)}) ${this.self("step")} = ${body}; else ${this.self("step")} = ${next};`;
1086
+ }
1087
+
1088
+ /** A step whose body is written once what follows it is known, as a loop's test is. */
1089
+ private reserve(origin: ts.Node, kind: Step["kind"]): number {
1090
+ return this.state("", origin, kind, { yields: false });
1091
+ }
1092
+
1093
+ private fill(step: number, origin: ts.Node, body: Part): void {
1094
+ this.states.set(step, from(origin, body));
1095
+ }
1096
+
1097
+ /** The field `collect` gave a local or caught error. */
1098
+ private local(declaration: ts.VariableDeclaration): Field {
1099
+ const field = this.fields.get(this.declared(declaration.name));
1100
+ if (!field) {
1101
+ throw new Error("Every async local is collected onto the block.");
1102
+ }
1103
+ return field;
1104
+ }
1105
+
1106
+ /** A failure inside `try` moves to the catch steps with the error code; a cancel still fails. */
1107
+ private tryStatement(
1108
+ statement: ts.TryStatement,
1109
+ next: number,
1110
+ reject: Reject,
1111
+ ): number {
1112
+ const clause = statement.catchClause;
1113
+ if (!clause) {
1114
+ throw new Error("Control-flow lowering gives every async try a catch.");
1115
+ }
1116
+ const caught = this.block(clause.block.statements, next, reject);
1117
+ const declaration = clause.variableDeclaration;
1118
+ const field = declaration && this.local(declaration);
1119
+ return this.block(
1120
+ statement.tryBlock.statements,
1121
+ next,
1122
+ (error, { cancellable }) => {
1123
+ const recover = mapped`${field ? mapped`${this.self(field.name)} = ${error};` : ""}${this.self("step")} = ${caught};`;
1124
+ return cancellable
1125
+ ? mapped`if(${error} === ${jobError.cancelled} || ${error} === ${jobError.codeChanged}) {${this.failure(error)}} else {${recover}}`
1126
+ : recover;
1127
+ },
1128
+ );
1129
+ }
1130
+
1131
+ private returnStatement(
1132
+ statement: ts.ReturnStatement,
1133
+ reject: Reject,
1134
+ ): number {
1135
+ const { checker } = this.context;
1136
+ if (!statement.expression) {
1137
+ if (!this.returnsVoid) {
1138
+ this.context.fail(statement, "Async routines must return a value.");
1139
+ }
1140
+ return this.state(this.finish("true"), statement, "return", {
1141
+ yields: false,
1142
+ });
1143
+ }
1144
+ // Returning another routine's promise waits for it, as an await would.
1145
+ const adopted =
1146
+ ts.isCallExpression(statement.expression) &&
1147
+ checker.getAwaitedType(
1148
+ checker.getTypeAtLocation(statement.expression),
1149
+ ) !== checker.getTypeAtLocation(statement.expression)
1150
+ ? statement.expression
1151
+ : undefined;
1152
+ const suspension = ts.isAwaitExpression(statement.expression)
1153
+ ? statement.expression
1154
+ : adopted;
1155
+ if (!suspension) {
1156
+ return this.state(
1157
+ this.finish(this.rewrite(statement.expression)),
1158
+ statement,
1159
+ "return",
1160
+ { yields: false },
1161
+ );
1162
+ }
1163
+ return this.awaitState(
1164
+ suspension,
1165
+ this.returnsVoid ? undefined : this.self("value"),
1166
+ this.state(
1167
+ this.finish(this.returnsVoid ? "true" : this.self("value")),
1168
+ statement,
1169
+ "return",
1170
+ { yields: false },
1171
+ ),
1172
+ reject,
1173
+ );
1174
+ }
1175
+
1176
+ private localInitializer(
1177
+ declaration: ts.VariableDeclaration,
1178
+ next: number,
1179
+ reject: Reject,
1180
+ ): number {
1181
+ const field = this.local(declaration);
1182
+ const { initializer } = declaration;
1183
+ if (!initializer) {
1184
+ throw new Error("Every async local has an initializer.");
1185
+ }
1186
+ const target = this.self(field.name);
1187
+ return ts.isAwaitExpression(initializer)
1188
+ ? this.awaitState(initializer, target, next, reject)
1189
+ : this.state(
1190
+ mapped`${target} = ${copyValue(this.rewrite(initializer), field.aggregate)}; ${this.self("step")} = ${next};`,
1191
+ declaration,
1192
+ "statement",
1193
+ { yields: false },
1194
+ );
1195
+ }
1196
+
1197
+ /** The code digest: the block's fields, its parameters, its steps and how it resets and cancels. */
1198
+ digest(): number {
1199
+ return codeDigest(
1200
+ [
1201
+ this.fieldText(),
1202
+ this.parameters.map((p) => `${p.field}:${p.type}`).join(","),
1203
+ this.entry,
1204
+ this.table().text,
1205
+ this.resets.join(" "),
1206
+ this.cancels.join(" "),
1207
+ [...this.yielding].join(","),
1208
+ ].join("\n"),
1209
+ );
1210
+ }
1211
+
1212
+ /** An async function's block: its exported type aliases, then a class of its members. */
1213
+ blockClass(code: number): Mapped {
1214
+ const { fn, parameters } = this;
1215
+ const returnType = this.returnType;
1216
+ const exported = hasModifier(fn, ts.SyntaxKind.ExportKeyword)
1217
+ ? "export "
1218
+ : "";
1219
+ const aliases = this.context.aliases(fn);
1220
+ const [start, reset, snapshot, execute] = this.methods(code);
1221
+ return mapped`export type ${aliases.result} = ${returnType};\n${parameters.map((p, i) => `export type ${aliases.argument(i)} = ${p.type};`).join("\n")}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
1222
+ ${this.fieldText()}
1223
+ ${this.codeFields().join(" ")}
1224
+ ${start}
1225
+ ${reset}
1226
+ ${snapshot}
1227
+ ${execute}
1228
+
1229
+ }`;
1230
+ }
1231
+
1232
+ /** An async method's members, one per line, for its own class. */
1233
+ members(code: number): Part[] {
1234
+ return [
1235
+ ...Object.values(this.fieldGroups()).flat(),
1236
+ ...this.codeFields(),
1237
+ ...this.methods(code),
1238
+ ];
1239
+ }
1240
+
1241
+ /** The state the steps keep, the routine's locals and its children. */
1242
+ private fieldGroups(): {
1243
+ state: string[];
1244
+ locals: string[];
1245
+ children: string[];
1246
+ } {
1247
+ const returnType = this.returnType;
1248
+ const field = (name: string, rest: string) =>
1249
+ `private ${this.naming.member(name)}${rest}`;
1250
+ return {
1251
+ state: [
1252
+ ...Object.entries(jobStateFields).map(([name, type]) =>
1253
+ field(name, `:${type}=${type === "BOOL" ? "false" : "0"};`),
1254
+ ),
1255
+ field("value", `:${returnType}=defaultValue<${returnType}>();`),
1256
+ ],
1257
+ locals: [...this.fields.values()].map((local) =>
1258
+ field(local.name, `:${local.type}=defaultValue<${local.type}>();`),
1259
+ ),
1260
+ children: this.children,
1261
+ };
1262
+ }
1263
+
1264
+ /**
1265
+ * The fields as a function's block declares them: the state on one line, then one per line.
1266
+ * The empty line before the children is where loops once kept their positions; it stays, as
1267
+ * the code digest is taken over this text.
1268
+ */
1269
+ private fieldText(): string {
1270
+ const { state, locals, children } = this.fieldGroups();
1271
+ return `${state.join(" ")}\n${locals.join("\n")}\n\n${children.join("\n")}`;
1272
+ }
1273
+
1274
+ /** The digest of the code a job started with, and the error a job stops with. */
1275
+ private codeFields(): string[] {
1276
+ return [
1277
+ `private ${this.naming.member("tsplcCode")}:UDINT=0;`,
1278
+ `private ${this.naming.member("tsplcPending")}:UDINT=0;`,
1279
+ ];
1280
+ }
1281
+
1282
+ /** Start, reset and snapshot, and the method that runs steps until one yields. */
1283
+ private methods(code: number): [string, string, string, Mapped] {
1284
+ const { parameters, naming } = this;
1285
+ const returnType = this.returnType;
1286
+ const busy = this.self("busy");
1287
+ const done = this.self("done");
1288
+ const error = this.self("error");
1289
+ const step = this.self("step");
1290
+ const cancelling = this.self("cancelling");
1291
+ const pending = this.self("tsplcPending");
1292
+ const started = this.self("tsplcCode");
1293
+ const resets = this.resets.join(" ");
1294
+ const { cancelled, codeChanged } = jobError;
1295
+ const table = this.table();
1296
+ return [
1297
+ `${naming.entry("start")}(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(${busy} || ${done})return false; ${parameters.map((p) => `${this.self(p.field)} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${resets} ${this.self("value")} = defaultValue<${returnType}>(); ${error}=0;${cancelling}=false;${pending}=0;${started}=${code};${busy}=true;${done}=false;${step}=${this.entry};return true;}`,
1298
+ `${naming.entry("reset")}():void {${resets} ${busy}=false;${cancelling}=false;${pending}=0;${done}=false;${error}=0;${step}=0;}`,
1299
+ `${naming.entry("snapshot")}():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {if(${done}&&${started}!==${code}){return {busy:false,done:true,error:${codeChanged},result:defaultValue<${returnType}>()};}return {busy:${busy},done:${done},error:${error},result:${copyValue(this.self("value"), this.resultAggregate)}};}`,
1300
+ mapped`${naming.entry("advance")}(input:{cancel:BOOL}):void {if(!${busy})return;if(${started}!==${code}&&!${cancelling}){${pending}=${codeChanged};${cancelling}=true;}if(input.cancel)${cancelling}=true;if(${cancelling}){${this.cancels.map((cancel) => `{${cancel}}`).join(" ")}if(${pending}===0)${pending}=${cancelled};${this.failure(pending)}return;}for(let transition:DINT=0;transition<${this.states.size + 1};transition++){const previous:UINT=${step};switch(${step}){${table}
1301
+ default: {${pending}=${codeChanged};${cancelling}=true;return;} }if(!${busy}||${step}===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}`,
1302
+ ];
1303
+ }
1304
+
1305
+ /** The steps, each a case of the block's state machine. */
1306
+ private table(): Mapped {
1307
+ return joined(
1308
+ [...this.states].map(
1309
+ ([id, body]) => mapped`case ${id}: {${body}} break;`,
1310
+ ),
1311
+ "\n",
1312
+ );
1313
+ }
1314
+ }
1315
+
1316
+ /** The condition a loop tests before each iteration; undefined when it has none. */
1317
+ const loopCondition = (
1318
+ statement: ts.IterationStatement,
1319
+ ): ts.Expression | undefined => {
1320
+ if (ts.isForStatement(statement)) {
1321
+ return statement.condition;
1322
+ }
1323
+ if (ts.isWhileStatement(statement) || ts.isDoStatement(statement)) {
1324
+ return statement.expression;
1325
+ }
1326
+ return undefined;
1327
+ };
1328
+
1329
+ /** An awaited call and where its result goes. */
1330
+ interface Awaiting {
1331
+ awaited: ts.AwaitExpression | ts.CallExpression;
1332
+ call: ts.CallExpression;
1333
+ target: string | undefined;
1334
+ next: number;
1335
+ reject: Reject;
1336
+ }