@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,787 @@
1
+ import ts from "typescript";
2
+ import { copiedWhole } from "./coroutines";
3
+ import { plcSources } from "./module-graph";
4
+ import {
5
+ copied,
6
+ copiedRange,
7
+ type Edit,
8
+ edited,
9
+ from,
10
+ joined,
11
+ type Mapped,
12
+ mapped,
13
+ type Part,
14
+ } from "./positions";
15
+ import { promiseCallback } from "./promise-chains";
16
+ import { sdkModules } from "./sdk";
17
+ import { hasModifier, promisedType } from "./types";
18
+
19
+ /**
20
+ * Structured Text exits a loop with EXIT and leaves a CASE at its end only, and has no labels and no
21
+ * finally. Jumps it can't express become flags: the jump sets its flag, the statements after it run
22
+ * only while the flag is clear, and the statement the jump targets clears it.
23
+ */
24
+
25
+ type JumpKind = "break" | "continue" | "return";
26
+
27
+ /** A statement a jump can leave or target. */
28
+ interface Target {
29
+ kind: "loop" | "switch" | "labelled" | "finally";
30
+ labels: readonly string[];
31
+ /**
32
+ * The coroutine runs it inside one step of an async routine, so a jump from it to the steps around
33
+ * it, written as is, would leave the step without moving the job on.
34
+ */
35
+ withinStep: boolean;
36
+ breakFlag?: string;
37
+ continueFlag?: string;
38
+ /** Of a try with finally: which of its blocks the statements being lowered sit in. */
39
+ region?: "try" | "catch" | "finally";
40
+ }
41
+
42
+ /** A jump that left its statement with its flag set; undefined `target` is the routine, for a return. */
43
+ interface Pending {
44
+ kind: JumpKind;
45
+ flag: string;
46
+ target: Target | undefined;
47
+ }
48
+
49
+ /** A statement as lowered; `changed` when its text differs from the source's. */
50
+ interface Lowered {
51
+ text: Part;
52
+ pending: readonly Pending[];
53
+ changed: boolean;
54
+ }
55
+
56
+ interface List {
57
+ parts: readonly Part[];
58
+ pending: readonly Pending[];
59
+ changed: boolean;
60
+ }
61
+
62
+ /** One statement of a list, lowered when its turn comes, so guards can wrap the statements after it. */
63
+ interface Item {
64
+ origin: ts.Node;
65
+ lower: () => Lowered;
66
+ }
67
+
68
+ interface RoutineScope {
69
+ source: ts.SourceFile;
70
+ async: boolean;
71
+ stack: Target[];
72
+ /** The routine's result type as written, or undefined when it returns nothing. */
73
+ resultType: string | undefined;
74
+ result?: { flag: string; value: string | undefined };
75
+ name: (base: string) => string;
76
+ /** The SDK functions the lowered routine calls, which its module imports. */
77
+ uses: Set<keyof typeof sdkNames>;
78
+ }
79
+
80
+ const unique = (pending: readonly Pending[]): Pending[] => [
81
+ ...new Map(pending.map((item) => [item.flag, item])).values(),
82
+ ];
83
+
84
+ const anyOf = (pending: readonly Pending[]): string =>
85
+ unique(pending)
86
+ .map((item) => item.flag)
87
+ .join(" || ");
88
+
89
+ /** A case's or block's statements, looking through the one block a braced case holds. */
90
+ const unbraced = (
91
+ statements: readonly ts.Statement[],
92
+ ): readonly ts.Statement[] => {
93
+ const [only, ...others] = statements;
94
+ return only && !others.length && ts.isBlock(only)
95
+ ? only.statements
96
+ : statements;
97
+ };
98
+
99
+ const isJump = (statement: ts.Statement | undefined): boolean =>
100
+ statement !== undefined &&
101
+ (ts.isBreakStatement(statement) ||
102
+ ts.isContinueStatement(statement) ||
103
+ ts.isReturnStatement(statement) ||
104
+ ts.isThrowStatement(statement));
105
+
106
+ const containsAwaitOrThrow = (node: ts.Node): boolean =>
107
+ ts.isAwaitExpression(node) ||
108
+ ts.isThrowStatement(node) ||
109
+ (!ts.isFunctionLike(node) &&
110
+ (ts.forEachChild(node, containsAwaitOrThrow) ?? false));
111
+
112
+ /** Whether Structured Text can make the jump as written, from inside `crossing` to `target`. */
113
+ const isNative = (
114
+ kind: JumpKind,
115
+ target: Target | undefined,
116
+ crossing: readonly Target[],
117
+ ): boolean => {
118
+ if (
119
+ crossing.some(
120
+ (item) => item.kind === "finally" && item.region !== "finally",
121
+ )
122
+ ) {
123
+ return false;
124
+ }
125
+ if (!target?.withinStep && crossing.some((item) => item.withinStep)) {
126
+ return false;
127
+ }
128
+ if (kind === "return" || !target) {
129
+ return true;
130
+ }
131
+ if (target.kind !== "loop") {
132
+ return false;
133
+ }
134
+ return kind === "break"
135
+ ? !crossing.some((item) => item.kind === "loop" || item.kind === "switch")
136
+ : !crossing.some((item) => item.kind === "loop");
137
+ };
138
+
139
+ /** The innermost statement a native `break` would leave, past labelled blocks. */
140
+ const innermostExit = (
141
+ crossing: readonly Target[],
142
+ ): Target["kind"] | undefined =>
143
+ [...crossing].reverse().find((item) => item.kind !== "labelled")?.kind;
144
+
145
+ const targetIndex = (
146
+ kind: JumpKind,
147
+ label: string | undefined,
148
+ stack: readonly Target[],
149
+ ): number | undefined => {
150
+ if (kind === "return") {
151
+ return -1;
152
+ }
153
+ const found = [...stack.entries()]
154
+ .reverse()
155
+ .find(([, item]) =>
156
+ label === undefined
157
+ ? item.kind === "loop" || (kind === "break" && item.kind === "switch")
158
+ : item.labels.includes(label),
159
+ );
160
+ return found?.[0];
161
+ };
162
+
163
+ const lowerItems = (items: readonly Item[], loop: Target | undefined): List => {
164
+ const [first, ...others] = items;
165
+ if (!first) {
166
+ return { parts: [], pending: [], changed: false };
167
+ }
168
+ const head = first.lower();
169
+ const tail = lowerItems(others, loop);
170
+ const changed = head.changed || tail.changed;
171
+ if (!head.pending.length) {
172
+ return {
173
+ parts: [head.text, ...tail.parts],
174
+ pending: tail.pending,
175
+ changed,
176
+ };
177
+ }
178
+ // Directly in a loop's body, a jump past the loop leaves it with EXIT; one continuing it skips the rest.
179
+ const continuing = loop
180
+ ? head.pending.filter(
181
+ (item) => item.target === loop && item.kind === "continue",
182
+ )
183
+ : head.pending;
184
+ const leaving = loop
185
+ ? head.pending.filter(
186
+ (item) => !(item.target === loop && item.kind === "continue"),
187
+ )
188
+ : [];
189
+ const parts: Part[] = [head.text];
190
+ if (leaving.length) {
191
+ parts.push(from(first.origin, `if (${anyOf(leaving)}) { break; }`));
192
+ }
193
+ if (tail.parts.length) {
194
+ parts.push(
195
+ continuing.length
196
+ ? from(
197
+ first.origin,
198
+ mapped`if (!(${anyOf(continuing)})) { ${joined(tail.parts, " ")} }`,
199
+ )
200
+ : joined(tail.parts, " "),
201
+ );
202
+ }
203
+ return {
204
+ parts,
205
+ pending: unique([...head.pending, ...tail.pending]),
206
+ changed,
207
+ };
208
+ };
209
+
210
+ const statementItems = (
211
+ statements: readonly ts.Statement[],
212
+ routine: RoutineScope,
213
+ ): Item[] =>
214
+ statements.map((statement) => ({
215
+ origin: statement,
216
+ lower: () => lower(statement, routine),
217
+ }));
218
+
219
+ const lowerList = (
220
+ statements: readonly ts.Statement[],
221
+ loop: Target | undefined,
222
+ routine: RoutineScope,
223
+ ): List => lowerItems(statementItems(statements, routine), loop);
224
+
225
+ const settled = (pending: readonly Pending[], target: Target): Pending[] =>
226
+ pending.filter((item) => item.target !== target);
227
+
228
+ /** Declares the flags jumps to `target` set, before it runs, so each run of it starts with them clear. */
229
+ const declared = (target: Target, node: ts.Node, text: Part): Part => {
230
+ const flags = [target.breakFlag, target.continueFlag].filter(
231
+ (flag) => flag !== undefined,
232
+ );
233
+ if (!flags.length) {
234
+ return text;
235
+ }
236
+ return from(
237
+ node,
238
+ mapped`{ ${flags.map((flag) => `let ${flag}: boolean = false;`).join(" ")} ${text} }`,
239
+ );
240
+ };
241
+
242
+ const withinStep = (node: ts.Statement, routine: RoutineScope): boolean =>
243
+ routine.async &&
244
+ (routine.stack.some((item) => item.withinStep) ||
245
+ copiedWhole(node, routine.source));
246
+
247
+ const unchanged = (node: ts.Node): Lowered => ({
248
+ text: copied(node),
249
+ pending: [],
250
+ changed: false,
251
+ });
252
+
253
+ const lower = (node: ts.Statement, routine: RoutineScope): Lowered => {
254
+ const lowered = lowerStatement(node, routine);
255
+ return lowered.changed ? lowered : unchanged(node);
256
+ };
257
+
258
+ const lowerStatement = (node: ts.Statement, routine: RoutineScope): Lowered => {
259
+ if (ts.isLabeledStatement(node)) {
260
+ return labelled(node, routine);
261
+ }
262
+ if (ts.isIterationStatement(node, false)) {
263
+ return loop(node, [], routine);
264
+ }
265
+ if (ts.isSwitchStatement(node)) {
266
+ return switchStatement(node, [], routine);
267
+ }
268
+ if (ts.isBlock(node)) {
269
+ const list = lowerList(node.statements, undefined, routine);
270
+ return {
271
+ text: from(node, mapped`{ ${joined(list.parts, " ")} }`),
272
+ pending: list.pending,
273
+ changed: list.changed,
274
+ };
275
+ }
276
+ if (ts.isIfStatement(node)) {
277
+ return ifStatement(node, routine);
278
+ }
279
+ if (ts.isTryStatement(node)) {
280
+ return node.finallyBlock
281
+ ? finallyStatement(node, node.finallyBlock, routine)
282
+ : tryStatement(node, routine);
283
+ }
284
+ if (
285
+ ts.isBreakStatement(node) ||
286
+ ts.isContinueStatement(node) ||
287
+ ts.isReturnStatement(node)
288
+ ) {
289
+ return jump(node, routine);
290
+ }
291
+ return unchanged(node);
292
+ };
293
+
294
+ /** Structured Text has no labels, so a labelled statement always changes. */
295
+ const labelled = (
296
+ node: ts.LabeledStatement,
297
+ routine: RoutineScope,
298
+ ): Lowered => {
299
+ const { labels, inner } = unlabelled(node);
300
+ if (ts.isIterationStatement(inner, false)) {
301
+ return { ...loop(inner, labels, routine), changed: true };
302
+ }
303
+ if (ts.isSwitchStatement(inner)) {
304
+ return { ...switchStatement(inner, labels, routine), changed: true };
305
+ }
306
+ const target: Target = {
307
+ kind: "labelled",
308
+ labels,
309
+ withinStep: withinStep(inner, routine),
310
+ };
311
+ routine.stack.push(target);
312
+ const body = lower(inner, routine);
313
+ routine.stack.pop();
314
+ return {
315
+ text: declared(target, node, body.text),
316
+ pending: settled(body.pending, target),
317
+ changed: true,
318
+ };
319
+ };
320
+
321
+ /** The statement under a run of labels, and the labels. */
322
+ const unlabelled = (
323
+ node: ts.LabeledStatement,
324
+ ): { labels: string[]; inner: ts.Statement } => {
325
+ if (!ts.isLabeledStatement(node.statement)) {
326
+ return { labels: [node.label.text], inner: node.statement };
327
+ }
328
+ const nested = unlabelled(node.statement);
329
+ return { labels: [node.label.text, ...nested.labels], inner: nested.inner };
330
+ };
331
+
332
+ const loop = (
333
+ node: ts.IterationStatement,
334
+ labels: readonly string[],
335
+ routine: RoutineScope,
336
+ ): Lowered => {
337
+ const target: Target = {
338
+ kind: "loop",
339
+ labels,
340
+ withinStep: withinStep(node, routine),
341
+ };
342
+ routine.stack.push(target);
343
+ const body = node.statement;
344
+ const list = lowerList(
345
+ ts.isBlock(body) ? body.statements : [body],
346
+ target,
347
+ routine,
348
+ );
349
+ routine.stack.pop();
350
+ if (!list.changed) {
351
+ return unchanged(node);
352
+ }
353
+ const { source } = routine;
354
+ const reset = target.continueFlag ? `${target.continueFlag} = false; ` : "";
355
+ const text = mapped`${copiedRange(source, node.getStart(source), body.getStart(source))}${from(body, mapped`{ ${reset}${joined(list.parts, " ")} }`)}${copiedRange(source, body.end, node.end)}`;
356
+ return {
357
+ text: declared(target, node, text),
358
+ pending: settled(list.pending, target),
359
+ changed: true,
360
+ };
361
+ };
362
+
363
+ const ifStatement = (node: ts.IfStatement, routine: RoutineScope): Lowered => {
364
+ const yes = lower(node.thenStatement, routine);
365
+ const no = node.elseStatement && lower(node.elseStatement, routine);
366
+ if (!yes.changed && !no?.changed) {
367
+ return unchanged(node);
368
+ }
369
+ const { source } = routine;
370
+ const head = copiedRange(
371
+ source,
372
+ node.getStart(source),
373
+ node.thenStatement.getStart(source),
374
+ );
375
+ const otherwise =
376
+ node.elseStatement && no
377
+ ? mapped`${copiedRange(source, node.thenStatement.end, node.elseStatement.getStart(source))}${no.text}`
378
+ : "";
379
+ return {
380
+ text: mapped`${head}${yes.text}${otherwise}`,
381
+ pending: unique([...yes.pending, ...(no?.pending ?? [])]),
382
+ changed: true,
383
+ };
384
+ };
385
+
386
+ /**
387
+ * A case that doesn't end in a jump runs on into the next, so its body is the chain of bodies up to
388
+ * one that does. Each case ends with the break Structured Text's CASE implies, or its return.
389
+ */
390
+ const switchStatement = (
391
+ node: ts.SwitchStatement,
392
+ labels: readonly string[],
393
+ routine: RoutineScope,
394
+ ): Lowered => {
395
+ const target: Target = {
396
+ kind: "switch",
397
+ labels,
398
+ withinStep: withinStep(node, routine),
399
+ };
400
+ routine.stack.push(target);
401
+ const { source } = routine;
402
+ const bodies = node.caseBlock.clauses.map((clause) =>
403
+ unbraced(clause.statements),
404
+ );
405
+ const clauses = node.caseBlock.clauses.map((clause, index): Lowered => {
406
+ const label = ts.isCaseClause(clause)
407
+ ? mapped`case ${copied(clause.expression)}:`
408
+ : "default:";
409
+ if (!bodies[index]?.length) {
410
+ return { text: from(clause, label), pending: [], changed: false };
411
+ }
412
+ const chain: (readonly ts.Statement[])[] = [];
413
+ for (const body of bodies.slice(index)) {
414
+ if (!body.length) {
415
+ continue;
416
+ }
417
+ chain.push(body);
418
+ if (isJump(body.at(-1))) {
419
+ break;
420
+ }
421
+ }
422
+ const last = chain.at(-1) ?? [];
423
+ const end = last.at(-1);
424
+ const ending =
425
+ end && ts.isBreakStatement(end) && !end.label ? last.slice(0, -1) : last;
426
+ const pieces = [...chain.slice(0, -1), ending];
427
+ const items: Item[] =
428
+ pieces.length === 1
429
+ ? statementItems(ending, routine)
430
+ : pieces.map((piece) => ({
431
+ origin: piece[0] ?? clause,
432
+ lower: () => {
433
+ const list = lowerList(piece, undefined, routine);
434
+ return {
435
+ text: from(clause, mapped`{ ${joined(list.parts, " ")} }`),
436
+ pending: list.pending,
437
+ changed: list.changed,
438
+ };
439
+ },
440
+ }));
441
+ const list = lowerItems(items, undefined);
442
+ const returns =
443
+ end !== undefined &&
444
+ (ts.isReturnStatement(end) || ts.isThrowStatement(end)) &&
445
+ !list.pending.length;
446
+ const body = joined(list.parts, " ");
447
+ return {
448
+ text: from(
449
+ clause,
450
+ returns
451
+ ? mapped`${label} { ${body} }`
452
+ : mapped`${label} { ${body} } break;`,
453
+ ),
454
+ pending: list.pending,
455
+ // A case that runs on into the next one is a change in itself.
456
+ changed: chain.length > 1 || list.changed,
457
+ };
458
+ });
459
+ routine.stack.pop();
460
+ if (!clauses.some((clause) => clause.changed)) {
461
+ return unchanged(node);
462
+ }
463
+ const text = mapped`${copiedRange(source, node.getStart(source), node.caseBlock.getStart(source))}{ ${joined(
464
+ clauses.map((clause) => clause.text),
465
+ " ",
466
+ )} }`;
467
+ return {
468
+ text: declared(target, node, text),
469
+ pending: settled(
470
+ unique(clauses.flatMap((clause) => clause.pending)),
471
+ target,
472
+ ),
473
+ changed: true,
474
+ };
475
+ };
476
+
477
+ const tryStatement = (
478
+ node: ts.TryStatement,
479
+ routine: RoutineScope,
480
+ ): Lowered => {
481
+ const attempt = lower(node.tryBlock, routine);
482
+ const caught = node.catchClause && lower(node.catchClause.block, routine);
483
+ if (!attempt.changed && !caught?.changed) {
484
+ return unchanged(node);
485
+ }
486
+ const { source } = routine;
487
+ const recovery =
488
+ node.catchClause && caught
489
+ ? mapped`${copiedRange(source, node.tryBlock.end, node.catchClause.block.getStart(source))}${caught.text}`
490
+ : "";
491
+ return {
492
+ text: mapped`${copiedRange(source, node.getStart(source), node.tryBlock.getStart(source))}${attempt.text}${recovery}`,
493
+ pending: unique([...attempt.pending, ...(caught?.pending ?? [])]),
494
+ changed: true,
495
+ };
496
+ };
497
+
498
+ /**
499
+ * The finally block runs after the try and catch blocks however they end. A jump out of them is held
500
+ * until it has run; in an async routine a failure is caught, held and raised again after it.
501
+ */
502
+ const finallyStatement = (
503
+ node: ts.TryStatement,
504
+ finallyBlock: ts.Block,
505
+ routine: RoutineScope,
506
+ ): Lowered => {
507
+ const target: Target = {
508
+ kind: "finally",
509
+ labels: [],
510
+ withinStep: withinStep(node, routine),
511
+ region: "try",
512
+ };
513
+ routine.stack.push(target);
514
+ const attempt = lowerList(node.tryBlock.statements, undefined, routine);
515
+ target.region = "catch";
516
+ const caught =
517
+ node.catchClause &&
518
+ lowerList(node.catchClause.block.statements, undefined, routine);
519
+ target.region = "finally";
520
+ const final = lowerList(finallyBlock.statements, undefined, routine);
521
+ routine.stack.pop();
522
+
523
+ const held = unique([...attempt.pending, ...(caught?.pending ?? [])]);
524
+ const guarded = routine.async
525
+ ? caughtAttempt(node, attempt, caught, routine)
526
+ : // Synchronous scan code can't fail, so its catch block never runs.
527
+ {
528
+ parts: [mapped`{ ${joined(attempt.parts, " ")} }`],
529
+ rethrow: undefined,
530
+ };
531
+ const parts: Part[] = [...guarded.parts];
532
+ parts.push(mapped`{ ${joined(final.parts, " ")} }`);
533
+
534
+ const resumed: string[] = guarded.rethrow ? [guarded.rethrow] : [];
535
+ const still: Pending[] = [];
536
+ for (const item of held) {
537
+ const index = item.target ? routine.stack.indexOf(item.target) : -1;
538
+ const crossing = routine.stack.slice(index + 1);
539
+ if (!isNative(item.kind, item.target, crossing)) {
540
+ still.push(item);
541
+ continue;
542
+ }
543
+ if (item.kind === "return") {
544
+ const value = routine.result?.value;
545
+ resumed.push(`if (${item.flag}) { return${value ? ` ${value}` : ""}; }`);
546
+ continue;
547
+ }
548
+ resumed.push(`if (${item.flag}) { ${item.kind}; }`);
549
+ }
550
+ if (resumed.length) {
551
+ parts.push(
552
+ final.pending.length
553
+ ? `if (!(${anyOf(final.pending)})) { ${resumed.join(" ")} }`
554
+ : resumed.join(" "),
555
+ );
556
+ }
557
+ return {
558
+ text: from(node, mapped`{ ${joined(parts, " ")} }`),
559
+ pending: unique([...still, ...final.pending]),
560
+ changed: true,
561
+ };
562
+ };
563
+
564
+ /** An async try whose failures, in its try block or its catch block, are held until finally has run. */
565
+ const caughtAttempt = (
566
+ node: ts.TryStatement,
567
+ attempt: List,
568
+ caught: List | undefined,
569
+ routine: RoutineScope,
570
+ ): { parts: Part[]; rethrow: string } => {
571
+ const throwing = routine.name("tsplcThrowing");
572
+ const error = routine.name("tsplcError");
573
+ routine.uses.add("errorCode");
574
+ const hold = (caught: string) =>
575
+ `${throwing} = true; ${error} = ${sdkNames.errorCode}(${caught});`;
576
+ const fallback = routine.name("tsplcCaught");
577
+ const clause = node.catchClause;
578
+ const binding = clause?.variableDeclaration
579
+ ? copied(clause.variableDeclaration)
580
+ : fallback;
581
+ const recovery = (): Part => {
582
+ if (!clause || !caught) {
583
+ return hold(fallback);
584
+ }
585
+ // A failure in the catch block still runs finally, so it is caught again.
586
+ if (!containsAwaitOrThrow(clause.block)) {
587
+ return joined(caught.parts, " ");
588
+ }
589
+ const again = routine.name("tsplcCaught");
590
+ return mapped`try { ${joined(caught.parts, " ")} } catch (${again}) { ${hold(again)} }`;
591
+ };
592
+ return {
593
+ parts: [
594
+ `let ${throwing}: boolean = false; let ${error}: UDINT = 0;`,
595
+ mapped`try { ${joined(attempt.parts, " ")} } catch (${binding}) { ${recovery()} }`,
596
+ ],
597
+ rethrow: `if (${throwing}) { throw ${error}; }`,
598
+ };
599
+ };
600
+
601
+ const jump = (
602
+ node: ts.BreakStatement | ts.ContinueStatement | ts.ReturnStatement,
603
+ routine: RoutineScope,
604
+ ): Lowered => {
605
+ const { kind, label } = jumpOf(node);
606
+ const index = targetIndex(kind, label, routine.stack);
607
+ if (index === undefined) {
608
+ return unchanged(node);
609
+ }
610
+ const target = index >= 0 ? routine.stack[index] : undefined;
611
+ const crossing = routine.stack.slice(index + 1);
612
+ if (isNative(kind, target, crossing) && label === undefined) {
613
+ return unchanged(node);
614
+ }
615
+ if (isNative(kind, target, crossing)) {
616
+ return { text: from(node, `${kind};`), pending: [], changed: true };
617
+ }
618
+ const flag = flagFor(kind, target, routine);
619
+ const value =
620
+ ts.isReturnStatement(node) && node.expression && routine.result?.value
621
+ ? mapped`${routine.result.value} = ${copied(node.expression)}; `
622
+ : "";
623
+ const exit = innermostExit(crossing) === "loop" ? " break;" : "";
624
+ return {
625
+ text: from(node, mapped`{ ${flag} = true; ${value}${exit} }`),
626
+ pending: [{ kind, flag, target }],
627
+ changed: true,
628
+ };
629
+ };
630
+
631
+ const jumpOf = (
632
+ node: ts.BreakStatement | ts.ContinueStatement | ts.ReturnStatement,
633
+ ): { kind: JumpKind; label: string | undefined } => {
634
+ if (ts.isBreakStatement(node)) {
635
+ return { kind: "break", label: node.label?.text };
636
+ }
637
+ if (ts.isContinueStatement(node)) {
638
+ return { kind: "continue", label: node.label?.text };
639
+ }
640
+ return { kind: "return", label: undefined };
641
+ };
642
+
643
+ const flagFor = (
644
+ kind: JumpKind,
645
+ target: Target | undefined,
646
+ routine: RoutineScope,
647
+ ): string => {
648
+ if (!target) {
649
+ routine.result ??= {
650
+ flag: routine.name("tsplcReturning"),
651
+ value: routine.resultType ? routine.name("tsplcResult") : undefined,
652
+ };
653
+ return routine.result.flag;
654
+ }
655
+ if (kind === "continue") {
656
+ target.continueFlag ??= routine.name("tsplcContinue");
657
+ return target.continueFlag;
658
+ }
659
+ target.breakFlag ??= routine.name("tsplcBreak");
660
+ return target.breakFlag;
661
+ };
662
+
663
+ type RoutineNode =
664
+ | ts.FunctionDeclaration
665
+ | ts.MethodDeclaration
666
+ | ts.GetAccessorDeclaration
667
+ | ts.SetAccessorDeclaration
668
+ | ts.ConstructorDeclaration
669
+ | ts.ArrowFunction
670
+ | ts.FunctionExpression;
671
+
672
+ const isRoutine = (node: ts.Node): node is RoutineNode =>
673
+ ts.isFunctionDeclaration(node) ||
674
+ ts.isMethodDeclaration(node) ||
675
+ ts.isGetAccessorDeclaration(node) ||
676
+ ts.isSetAccessorDeclaration(node) ||
677
+ ts.isConstructorDeclaration(node) ||
678
+ ts.isArrowFunction(node) ||
679
+ ts.isFunctionExpression(node);
680
+
681
+ /** The result type a return statement's value is held as, as written, or undefined for a routine returning nothing. */
682
+ const resultType = (
683
+ node: RoutineNode,
684
+ checker: ts.TypeChecker,
685
+ ): string | undefined => {
686
+ if (ts.isConstructorDeclaration(node) || ts.isSetAccessorDeclaration(node)) {
687
+ return undefined;
688
+ }
689
+ const annotation = node.type;
690
+ const isAsync = hasModifier(node, ts.SyntaxKind.AsyncKeyword);
691
+ if (annotation) {
692
+ const inner = isAsync ? promisedType(annotation) : annotation;
693
+ if (!inner || inner.kind === ts.SyntaxKind.VoidKeyword) {
694
+ return undefined;
695
+ }
696
+ return inner.getText();
697
+ }
698
+ const signature = checker.getSignatureFromDeclaration(node);
699
+ if (!signature) {
700
+ return undefined;
701
+ }
702
+ const returns = checker.getReturnTypeOfSignature(signature);
703
+ const awaited = isAsync ? checker.getAwaitedType(returns) : returns;
704
+ if (!awaited || awaited.flags & ts.TypeFlags.Void) {
705
+ return undefined;
706
+ }
707
+ return checker.typeToString(awaited);
708
+ };
709
+
710
+ /** The SDK functions lowered code calls, by the names their imports give them. */
711
+ const sdkNames = {
712
+ defaultValue: "tsplcHeldDefault",
713
+ errorCode: "tsplcHeldErrorCode",
714
+ } as const;
715
+
716
+ const sdkNameModules: Record<keyof typeof sdkNames, string> = {
717
+ defaultValue: sdkModules.types,
718
+ errorCode: sdkModules.async,
719
+ };
720
+
721
+ /** Lowers the jumps, labels, fallthrough and finally blocks Structured Text can't express in every routine. */
722
+ export const lowerControlFlow = (program: ts.Program) => {
723
+ const checker = program.getTypeChecker();
724
+ const sources = new Map<string, Mapped>();
725
+ for (const source of plcSources(program)) {
726
+ const edits: Edit[] = [];
727
+ let counter = 0;
728
+ const uses = new Set<keyof typeof sdkNames>();
729
+ const name = (base: string) => `${base}${++counter}`;
730
+ const visit = (node: ts.Node): void => {
731
+ if (!isRoutine(node) || !node.body || !ts.isBlock(node.body)) {
732
+ ts.forEachChild(node, visit);
733
+ return;
734
+ }
735
+ const body = node.body;
736
+ const routine: RoutineScope = {
737
+ source,
738
+ async:
739
+ hasModifier(node, ts.SyntaxKind.AsyncKeyword) ||
740
+ promiseCallback(node),
741
+ stack: [],
742
+ resultType: resultType(node, checker),
743
+ name,
744
+ uses,
745
+ };
746
+ const list = lowerList(body.statements, undefined, routine);
747
+ if (!list.changed) {
748
+ ts.forEachChild(node, visit);
749
+ return;
750
+ }
751
+ const declarations: string[] = [];
752
+ if (routine.result) {
753
+ declarations.push(`let ${routine.result.flag}: boolean = false;`);
754
+ if (routine.result.value && routine.resultType) {
755
+ uses.add("defaultValue");
756
+ declarations.push(
757
+ `let ${routine.result.value}: ${routine.resultType} = ${sdkNames.defaultValue}<${routine.resultType}>();`,
758
+ );
759
+ }
760
+ }
761
+ // Only a return can still be held here, and every other path through the routine returns.
762
+ const value = list.pending.length ? routine.result?.value : undefined;
763
+ const resumed = value ? [`return ${value};`] : [];
764
+ edits.push({
765
+ start: body.getStart(source),
766
+ end: body.end,
767
+ text: from(
768
+ body,
769
+ mapped`{ ${declarations.join(" ")} ${joined([...list.parts, ...resumed], "\n")} }`,
770
+ ),
771
+ });
772
+ };
773
+ visit(source);
774
+ if (!edits.length) {
775
+ continue;
776
+ }
777
+ for (const used of uses) {
778
+ edits.push({
779
+ start: 0,
780
+ end: 0,
781
+ text: `import { ${used} as ${sdkNames[used]} } from "${sdkNameModules[used]}";\n`,
782
+ });
783
+ }
784
+ sources.set(source.fileName, edited(source, edits));
785
+ }
786
+ return { sources, diagnostics: [] };
787
+ };