@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,1220 @@
1
+ import { loopIterations } from "@tsplc/iec/arithmetic";
2
+ import ts from "typescript";
3
+ import { copied, mapped, type Part } from "../positions";
4
+ import { namesSdk, sdkModules } from "../sdk";
5
+ import { unparenthesized } from "../types";
6
+ import { parameterDefault } from "./declarations";
7
+ import type { DialectText } from "./dialect";
8
+ import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
9
+ import { type Frame, looping } from "./frame";
10
+ import type { Initializers } from "./initializers";
11
+ import type { GeneratorCall, Jumps, Traversal } from "./iterators";
12
+ import { arrayLayout, type Layouts } from "./layouts";
13
+ import {
14
+ constant,
15
+ type FunctionLike,
16
+ isStoredState,
17
+ known,
18
+ SpecializeError,
19
+ type Value,
20
+ } from "./values";
21
+ import {
22
+ assignsName,
23
+ isAssignment,
24
+ isUpdate,
25
+ occursOutsideFunctions,
26
+ } from "./writes";
27
+
28
+ /**
29
+ * A statement break and continue can reach. One emitted as written keeps its user's labels; one setup
30
+ * unrolled or folded is a labelled block, which a jump leaves by its emitted label.
31
+ */
32
+ interface JumpScope {
33
+ kind: "loop" | "switch" | "labelled";
34
+ labels: readonly string[];
35
+ breakLabel?: string;
36
+ continueLabel?: string;
37
+ }
38
+
39
+ /** Specializes one routine's statements; expressions in them go through its ExpressionSpecializer. */
40
+ export class StatementSpecializer {
41
+ private readonly scopes: JumpScope[] = [];
42
+ /** Statements that couldn't be specialized, each once, so one run reports every one. */
43
+ readonly failures: SpecializeError[] = [];
44
+ /** The generators running in place, outermost first, so one can't recurse into itself. */
45
+ private readonly generators: FunctionLike[] = [];
46
+
47
+ constructor(
48
+ private readonly context: SpecializeContext,
49
+ private readonly expressions: ExpressionSpecializer,
50
+ ) {
51
+ expressions.iterators.attach({
52
+ run: (generator, frame, at, each) =>
53
+ this.runGenerator(generator, frame, [], at, each),
54
+ });
55
+ }
56
+
57
+ body(node: ts.ConciseBody, frame: Frame): void {
58
+ if (ts.isBlock(node)) {
59
+ this.statements(node.statements, frame);
60
+ } else {
61
+ frame.emitter.origin = node;
62
+ frame.emitter.line(
63
+ mapped`${this.dialect.code(this.expressions.expression(node, frame), undefined)};`,
64
+ );
65
+ }
66
+ }
67
+
68
+ /** Statements after one that always jumps are unreachable, and may read what setup left undefined on that path. */
69
+ private statements(
70
+ nodes: ReadonlyArray<ts.Statement>,
71
+ frame: Frame,
72
+ ): boolean {
73
+ for (const [index, statement] of nodes.entries()) {
74
+ const rest = nodes.slice(index + 1);
75
+ if (
76
+ ts.isIfStatement(statement) &&
77
+ !statement.elseStatement &&
78
+ rest.length
79
+ ) {
80
+ return this.recorded(statement, frame, () =>
81
+ this.guard(statement, rest, frame),
82
+ );
83
+ }
84
+ if (this.statement(statement, frame)) {
85
+ return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+
91
+ /**
92
+ * An `if` without `else`, then the statements after it. When its branch always jumps, as a loop's
93
+ * `if (i >= count) break;` does, they run only when the condition is false: they are its `else`,
94
+ * where the PLC's range proofs know the condition is false, as they know it inside an `else`.
95
+ */
96
+ private guard(
97
+ node: ts.IfStatement,
98
+ rest: ReadonlyArray<ts.Statement>,
99
+ frame: Frame,
100
+ ): boolean {
101
+ const condition = this.expressions.expression(node.expression, frame);
102
+ if (
103
+ condition.kind === "const" ||
104
+ condition.kind === "static" ||
105
+ condition.kind === "function"
106
+ ) {
107
+ const truthy =
108
+ condition.kind === "const" ? Boolean(condition.value) : true;
109
+ return (
110
+ (truthy && this.statement(node.thenStatement, frame)) ||
111
+ this.statements(rest, frame)
112
+ );
113
+ }
114
+ frame.emitter.open(
115
+ mapped`if (${this.dialect.condition(condition, node.expression)}) {`,
116
+ );
117
+ if (!this.inner(node.thenStatement, frame)) {
118
+ frame.emitter.close();
119
+ return this.statements(rest, frame);
120
+ }
121
+ frame.emitter.reopen("} else {");
122
+ const restJumps = this.statements(rest, frame);
123
+ frame.emitter.close();
124
+ return restJumps;
125
+ }
126
+
127
+ private get checker(): ts.TypeChecker {
128
+ return this.context.checker;
129
+ }
130
+
131
+ private get dialect(): DialectText {
132
+ return this.context.dialect;
133
+ }
134
+
135
+ private get layouts(): Layouts {
136
+ return this.context.layouts;
137
+ }
138
+
139
+ private get initializers(): Initializers {
140
+ return this.context.initializers;
141
+ }
142
+
143
+ /** True when control never continues past the statement: it returns, throws, breaks or continues on every path. */
144
+ private statement(node: ts.Statement, frame: Frame): boolean {
145
+ return this.recorded(node, frame, () =>
146
+ this.specializeStatement(node, frame),
147
+ );
148
+ }
149
+
150
+ /** Specializes a statement, recording a failure in it and skipping it, so the build reports every failure. */
151
+ private recorded(
152
+ node: ts.Statement,
153
+ frame: Frame,
154
+ specialize: () => boolean,
155
+ ): boolean {
156
+ const enclosing = frame.emitter.origin;
157
+ frame.emitter.origin = node;
158
+ try {
159
+ return specialize();
160
+ } catch (cause) {
161
+ if (
162
+ !(cause instanceof SpecializeError) ||
163
+ ts.isBlock(node) ||
164
+ node.getChildren().some((child) => ts.isBlock(child))
165
+ ) {
166
+ throw cause;
167
+ }
168
+ if (
169
+ !this.failures.some(
170
+ (failure) =>
171
+ failure.node === cause.node && failure.message === cause.message,
172
+ )
173
+ ) {
174
+ this.failures.push(cause);
175
+ }
176
+ return false;
177
+ } finally {
178
+ frame.emitter.origin = enclosing;
179
+ }
180
+ }
181
+
182
+ private specializeStatement(node: ts.Statement, frame: Frame): boolean {
183
+ const { emitter } = frame;
184
+ if (ts.isBlock(node)) {
185
+ emitter.open("{");
186
+ const jumps = this.statements(node.statements, frame);
187
+ emitter.close();
188
+ return jumps;
189
+ }
190
+ if (ts.isVariableStatement(node)) {
191
+ const mutable = !(node.declarationList.flags & ts.NodeFlags.Const);
192
+ for (const declaration of node.declarationList.declarations) {
193
+ this.declare(declaration, mutable, frame);
194
+ }
195
+ return false;
196
+ }
197
+ if (ts.isExpressionStatement(node)) {
198
+ if (ts.isYieldExpression(node.expression)) {
199
+ this.yieldStatement(node.expression, frame);
200
+ return false;
201
+ }
202
+ this.effect(node.expression, frame);
203
+ return false;
204
+ }
205
+ if (ts.isIfStatement(node)) {
206
+ return this.ifStatement(node, frame);
207
+ }
208
+ if (ts.isReturnStatement(node)) {
209
+ this.returnStatement(node, frame);
210
+ return true;
211
+ }
212
+ if (ts.isIterationStatement(node, false) || ts.isSwitchStatement(node)) {
213
+ this.loopOrSwitch(node, [], frame);
214
+ return false;
215
+ }
216
+ if (ts.isTryStatement(node)) {
217
+ this.tryStatement(node, frame);
218
+ return false;
219
+ }
220
+ if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) {
221
+ emitter.line(this.jumpText(node));
222
+ return true;
223
+ }
224
+ if (ts.isLabeledStatement(node)) {
225
+ this.labelled(node, frame);
226
+ return false;
227
+ }
228
+ if (ts.isEmptyStatement(node)) {
229
+ return false;
230
+ }
231
+ if (ts.isThrowStatement(node) && frame.async) {
232
+ // An async routine fails with an error code, which its caller's catch block receives.
233
+ const code = this.expressions.expression(node.expression, frame);
234
+ emitter.line(mapped`throw ${this.dialect.code(code, undefined)};`);
235
+ return true;
236
+ }
237
+ throw unsupported(node);
238
+ }
239
+
240
+ /** A loop or switch, which jumps reach by the labels written on it. */
241
+ private loopOrSwitch(
242
+ node: ts.IterationStatement | ts.SwitchStatement,
243
+ labels: readonly string[],
244
+ frame: Frame,
245
+ ): void {
246
+ if (ts.isForOfStatement(node)) {
247
+ this.forOf(node, labels, frame);
248
+ return;
249
+ }
250
+ if (ts.isSwitchStatement(node)) {
251
+ this.switch(node, labels, frame);
252
+ return;
253
+ }
254
+ if (ts.isForStatement(node)) {
255
+ this.forLoop(node, labels, frame);
256
+ return;
257
+ }
258
+ if (!ts.isWhileStatement(node) && !ts.isDoStatement(node)) {
259
+ throw unsupported(node);
260
+ }
261
+ if (
262
+ frame.async &&
263
+ occursOutsideFunctions(node.statement, ts.isAwaitExpression)
264
+ ) {
265
+ this.suspendingLoop(node, labels, frame);
266
+ return;
267
+ }
268
+ throw new SpecializeError(
269
+ node,
270
+ "Use a counted for loop or for…of; while loops have no bound to prove.",
271
+ );
272
+ }
273
+
274
+ /** A jump as written, or out of the labelled block standing for a loop or switch setup unrolled or folded. */
275
+ private jumpText(node: ts.BreakStatement | ts.ContinueStatement): Part {
276
+ const label = node.label?.text;
277
+ const scope = [...this.scopes].reverse().find((item) => {
278
+ if (label !== undefined) {
279
+ return item.labels.includes(label);
280
+ }
281
+ return (
282
+ item.kind === "loop" ||
283
+ (ts.isBreakStatement(node) && item.kind === "switch")
284
+ );
285
+ });
286
+ const emitted = ts.isBreakStatement(node)
287
+ ? scope?.breakLabel
288
+ : scope?.continueLabel;
289
+ return emitted ? `break ${emitted};` : copied(node);
290
+ }
291
+
292
+ /** Gives the labels on the statement to the loop or switch it labels; a labelled block keeps them as written. */
293
+ private labelled(node: ts.LabeledStatement, frame: Frame): void {
294
+ const labels: string[] = [];
295
+ const inner = innermostLabelled(node, labels);
296
+ if (ts.isIterationStatement(inner, false) || ts.isSwitchStatement(inner)) {
297
+ this.recorded(inner, frame, () => {
298
+ this.loopOrSwitch(inner, labels, frame);
299
+ return false;
300
+ });
301
+ return;
302
+ }
303
+ frame.emitter.open(`${labelText(labels)}{`);
304
+ this.scoped({ kind: "labelled", labels }, () => this.inner(inner, frame));
305
+ frame.emitter.close();
306
+ }
307
+
308
+ private scoped<T>(scope: JumpScope, run: () => T): T {
309
+ this.scopes.push(scope);
310
+ try {
311
+ return run();
312
+ } finally {
313
+ this.scopes.pop();
314
+ }
315
+ }
316
+
317
+ /** An if on a value setup fixed keeps only the branch it takes. */
318
+ private ifStatement(node: ts.IfStatement, frame: Frame): boolean {
319
+ const condition = this.expressions.expression(node.expression, frame);
320
+ if (
321
+ condition.kind === "const" ||
322
+ condition.kind === "static" ||
323
+ condition.kind === "function"
324
+ ) {
325
+ const truthy =
326
+ condition.kind === "const" ? Boolean(condition.value) : true;
327
+ if (truthy) {
328
+ return this.statement(node.thenStatement, frame);
329
+ }
330
+ return node.elseStatement !== undefined
331
+ ? this.statement(node.elseStatement, frame)
332
+ : false;
333
+ }
334
+ frame.emitter.open(
335
+ mapped`if (${this.dialect.condition(condition, node.expression)}) {`,
336
+ );
337
+ const thenJumps = this.inner(node.thenStatement, frame);
338
+ const elseJumps =
339
+ node.elseStatement !== undefined &&
340
+ this.elseBranch(node.elseStatement, frame);
341
+ frame.emitter.close();
342
+ return thenJumps && elseJumps;
343
+ }
344
+
345
+ private elseBranch(node: ts.Statement, frame: Frame): boolean {
346
+ frame.emitter.reopen("} else {");
347
+ return this.inner(node, frame);
348
+ }
349
+
350
+ /** `return x satisfies never` marks an unreachable end, which returns the result type's default. */
351
+ private returnStatement(node: ts.ReturnStatement, frame: Frame): void {
352
+ if (frame.generator) {
353
+ frame.emitter.line(`break ${frame.generator.exit};`);
354
+ return;
355
+ }
356
+ if (!node.expression) {
357
+ frame.emitter.line("return;");
358
+ return;
359
+ }
360
+ if (unreachableEnd(node)) {
361
+ frame.emitter.line(
362
+ `return ${this.initializers.defaultOf(frame.returns)};`,
363
+ );
364
+ return;
365
+ }
366
+ const value = this.expressions.expression(
367
+ node.expression,
368
+ frame,
369
+ frame.returns,
370
+ );
371
+ this.expressions.references.returned(value, node.expression, frame);
372
+ if (isStoredState(value)) {
373
+ frame.returnsStored = true;
374
+ }
375
+ // An array's length is what is returned, as its type names none.
376
+ const element =
377
+ frame.returns &&
378
+ this.checker.getIndexTypeOfType(frame.returns, ts.IndexKind.Number);
379
+ if (element && value.kind === "virtual" && value.items) {
380
+ frame.resultLayout = arrayLayout(
381
+ this.layouts.text(element),
382
+ value.items.length,
383
+ );
384
+ frame.resultLength = value.items.length;
385
+ } else if (element && value.kind === "code" && value.layout) {
386
+ frame.resultLayout = value.layout;
387
+ frame.resultLength = value.length;
388
+ }
389
+ // A return stores into the result as an assignment does: wrapped as an optional, converted to its width.
390
+ frame.emitter.line(
391
+ mapped`return ${this.dialect.returnText(value, frame.returns, this.resultIec(frame))};`,
392
+ );
393
+ }
394
+
395
+ /** The IEC width a routine's result is declared with, as `(): UINT` gives it. */
396
+ private resultIec(frame: Frame): string | undefined {
397
+ const declaration = frame.emitter.origin;
398
+ return this.layouts.iecName(
399
+ ts.findAncestor(declaration, ts.isFunctionLike),
400
+ );
401
+ }
402
+
403
+ /** A try keeps its blocks, for the service calls in it. */
404
+ private tryStatement(node: ts.TryStatement, frame: Frame): void {
405
+ // Synchronous scan code can't fail, so its catch block never runs, with or without finally.
406
+ if (!frame.async && !node.finallyBlock) {
407
+ frame.emitter.open("{");
408
+ this.statements(node.tryBlock.statements, frame);
409
+ frame.emitter.close();
410
+ return;
411
+ }
412
+ frame.emitter.open("try {");
413
+ this.statements(node.tryBlock.statements, frame);
414
+ if (node.catchClause && frame.async) {
415
+ const binding = node.catchClause.variableDeclaration?.name;
416
+ frame.emitter.reopen(
417
+ `} catch${binding ? ` (${binding.getText()})` : ""} {`,
418
+ );
419
+ // The binding holds the error code, which a catch block can only pass on as it is.
420
+ if (binding && ts.isIdentifier(binding)) {
421
+ this.bindLocal(binding, binding.text, frame, undefined);
422
+ }
423
+ this.statements(node.catchClause.block.statements, frame);
424
+ }
425
+ if (node.finallyBlock) {
426
+ frame.emitter.reopen("} finally {");
427
+ this.statements(node.finallyBlock.statements, frame);
428
+ }
429
+ frame.emitter.close();
430
+ }
431
+
432
+ /** A branch body: blocks keep their statements without another brace level. */
433
+ private inner(node: ts.Statement, frame: Frame): boolean {
434
+ return ts.isBlock(node)
435
+ ? this.statements(node.statements, frame)
436
+ : this.statement(node, frame);
437
+ }
438
+
439
+ /** Binds a name to the PLC local that holds it, which scan code may assign. */
440
+ private bindLocal(
441
+ name: ts.Identifier,
442
+ local: string,
443
+ frame: Frame,
444
+ iec: string | undefined,
445
+ ): void {
446
+ const symbol = this.checker.getSymbolAtLocation(name);
447
+ if (!symbol) {
448
+ throw new SpecializeError(name, `${name.text} names nothing.`);
449
+ }
450
+ frame.env.set(symbol, {
451
+ kind: "code",
452
+ text: local,
453
+ declared: this.checker.getTypeAtLocation(name),
454
+ place: true,
455
+ ...(iec && { iec }),
456
+ });
457
+ }
458
+
459
+ private declare(
460
+ declaration: ts.VariableDeclaration,
461
+ mutable: boolean,
462
+ frame: Frame,
463
+ ): void {
464
+ const initializer = declaration.initializer;
465
+ const declared = this.checker.getTypeAtLocation(declaration.name);
466
+ // TypeScript proves a local assigned before it is read, so one declared bare starts at its type's default.
467
+ const value = initializer
468
+ ? this.expressions.expression(
469
+ initializer,
470
+ frame,
471
+ declaration.type && this.checker.getTypeAtLocation(declaration.type),
472
+ )
473
+ : this.bareValue(declared);
474
+ this.expressions.bind(declaration.name, value, frame, declared, {
475
+ mutable,
476
+ iec: this.layouts.iecName(declaration),
477
+ });
478
+ }
479
+
480
+ /** What a local declared without a value holds until it is assigned. */
481
+ private bareValue(declared: ts.Type): Value {
482
+ if (this.checker.getNonNullableType(declared) !== declared) {
483
+ return constant(undefined);
484
+ }
485
+ return {
486
+ kind: "code",
487
+ text: this.initializers.defaultOf(declared),
488
+ declared,
489
+ };
490
+ }
491
+
492
+ private forOf(
493
+ node: ts.ForOfStatement,
494
+ labels: readonly string[],
495
+ frame: Frame,
496
+ ): void {
497
+ const generator = this.expressions.iterators.generator(
498
+ node.expression,
499
+ frame,
500
+ );
501
+ // Over a generator, each yield runs the loop's body in a labelled block its continue leaves;
502
+ // break or the generator's return leave the block around the whole generator.
503
+ if (generator) {
504
+ this.runGenerator(
505
+ generator,
506
+ frame,
507
+ labels,
508
+ node,
509
+ this.loopBody(node, labels, frame),
510
+ );
511
+ return;
512
+ }
513
+ const iterated = this.expressions.iterators.iterated(
514
+ node.expression,
515
+ frame,
516
+ );
517
+ if (iterated) {
518
+ this.overTraversal(node, iterated, labels, frame);
519
+ return;
520
+ }
521
+ const call = node.expression;
522
+ if (
523
+ ts.isCallExpression(call) &&
524
+ ts.isPropertyAccessExpression(call.expression) &&
525
+ call.expression.name.text === "entries" &&
526
+ !call.arguments.length
527
+ ) {
528
+ const array = this.expressions.expression(
529
+ call.expression.expression,
530
+ frame,
531
+ );
532
+ if (array.kind === "code") {
533
+ this.forEntries(node, mapped`${array.text}.entries()`, labels, frame);
534
+ return;
535
+ }
536
+ }
537
+ // The SDK's entries(record) over stored state stays a loop over the record's enum keys.
538
+ if (
539
+ ts.isCallExpression(call) &&
540
+ namesSdk(this.checker, this.context.sdkFile, call.expression, "entries")
541
+ ) {
542
+ const [argument] = call.arguments;
543
+ const record = argument && this.expressions.expression(argument, frame);
544
+ if (record?.kind === "code") {
545
+ this.context.imports.addSdk(sdkModules.types, "entries");
546
+ this.forEntries(node, mapped`entries(${record.text})`, labels, frame);
547
+ return;
548
+ }
549
+ // A record setup built unrolls over its keys, each its enum member.
550
+ if (record?.kind === "static" && record.node.captured.kind === "object") {
551
+ const holder = record.node;
552
+ const pairs = Object.entries(record.node.captured.fields).map(
553
+ ([key, field]): Value => ({
554
+ kind: "virtual",
555
+ items: [
556
+ constant(Number(key)),
557
+ this.context.storage.fromCaptured(field, holder, {
558
+ kind: "field",
559
+ name: key,
560
+ }),
561
+ ],
562
+ }),
563
+ );
564
+ const name = loopDeclaration(node).name;
565
+ const declared = this.checker.getTypeAtLocation(name);
566
+ this.unrolled(node.statement, labels, pairs, frame, (pair) =>
567
+ this.expressions.bind(name, pair, frame, declared, {
568
+ mutable: false,
569
+ iec: undefined,
570
+ }),
571
+ );
572
+ return;
573
+ }
574
+ }
575
+ const iterable = this.expressions.expression(node.expression, frame);
576
+ if (iterable.kind === "counted") {
577
+ this.overTraversal(
578
+ node,
579
+ this.expressions.iterators.over(iterable),
580
+ labels,
581
+ frame,
582
+ );
583
+ return;
584
+ }
585
+ const items = this.expressions.items(iterable);
586
+ const name = loopDeclaration(node).name;
587
+ const declared = this.checker.getTypeAtLocation(name);
588
+ if (items) {
589
+ this.unrolled(node.statement, labels, items, frame, (item) =>
590
+ this.expressions.bind(name, item, frame, declared, {
591
+ mutable: false,
592
+ iec: undefined,
593
+ }),
594
+ );
595
+ return;
596
+ }
597
+ if (iterable.kind !== "code") {
598
+ throw new SpecializeError(node.expression, "for…of needs an array.");
599
+ }
600
+ if (!ts.isIdentifier(name)) {
601
+ throw new SpecializeError(
602
+ name,
603
+ "Destructure a runtime element inside the loop.",
604
+ );
605
+ }
606
+ const local = frame.emitter.local(name.text);
607
+ frame.emitter.open(
608
+ mapped`${labelText(labels)}for (const ${local} of ${iterable.text}) {`,
609
+ );
610
+ this.bindLocal(name, local, frame, undefined);
611
+ this.loop(node.statement, labels, undefined, frame);
612
+ frame.emitter.close();
613
+ }
614
+
615
+ /** The body of a loop that stays a loop in the PLC, which runs up to `runs` times when that is known. */
616
+ private loop(
617
+ body: ts.Statement,
618
+ labels: readonly string[],
619
+ runs: number | undefined,
620
+ frame: Frame,
621
+ ): void {
622
+ looping(frame, runs, () =>
623
+ this.scoped({ kind: "loop", labels }, () => this.inner(body, frame)),
624
+ );
625
+ }
626
+
627
+ /** A for…of over an iterator read through helpers, or over an array whose length is decided at run time. */
628
+ private overTraversal(
629
+ node: ts.ForOfStatement,
630
+ traversal: Traversal,
631
+ labels: readonly string[],
632
+ frame: Frame,
633
+ ): void {
634
+ const body = this.loopBody(node, labels, frame);
635
+ traversal.run(frame, (element) => body(element.value, element));
636
+ }
637
+
638
+ /**
639
+ * What a for…of does with each value it is given where the value is produced: binds its name
640
+ * and runs its body, whose break and continue leave the labelled statements around it.
641
+ */
642
+ private loopBody(
643
+ node: ts.ForOfStatement,
644
+ labels: readonly string[],
645
+ frame: Frame,
646
+ ): (value: Value, jumps: Jumps) => void {
647
+ const declaration = loopDeclaration(node);
648
+ const declared = this.checker.getTypeAtLocation(declaration.name);
649
+ const loop: Frame = { ...frame, env: new Map(frame.env) };
650
+ return (value, jumps) => {
651
+ this.expressions.bind(declaration.name, value, loop, declared, {
652
+ mutable: false,
653
+ iec: undefined,
654
+ });
655
+ this.scoped(
656
+ {
657
+ kind: "loop",
658
+ labels,
659
+ breakLabel: jumps.whole,
660
+ continueLabel: jumps.label,
661
+ },
662
+ () => this.inner(node.statement, loop),
663
+ );
664
+ };
665
+ }
666
+
667
+ /** Runs a generator's body in place, calling `each` for every value it yields. */
668
+ private runGenerator(
669
+ generator: GeneratorCall,
670
+ frame: Frame,
671
+ labels: readonly string[],
672
+ at: ts.Node,
673
+ each: (value: Value, jumps: Jumps) => void,
674
+ ): void {
675
+ const { declaration } = generator;
676
+ if (this.generators.includes(declaration)) {
677
+ throw new SpecializeError(
678
+ at,
679
+ "A generator runs in place, so it can't yield from itself.",
680
+ );
681
+ }
682
+ const body = declaration.body;
683
+ if (!body || !ts.isBlock(body)) {
684
+ throw new SpecializeError(at, "A generator needs a body.");
685
+ }
686
+ const whole = frame.emitter.local("tsplcGenerator");
687
+ const outside = this.generators.length;
688
+ const inner: Frame = {
689
+ ...frame,
690
+ env: new Map(),
691
+ self: generator.self,
692
+ returns: undefined,
693
+ generator: {
694
+ exit: whole,
695
+ yields: (value) => {
696
+ const label = frame.emitter.local("tsplcStep");
697
+ frame.emitter.open(`${label}: {`);
698
+ // What reads the value is outside this generator, so it may run the same generator itself.
699
+ const running = this.generators.splice(outside);
700
+ try {
701
+ each(value, { whole, label });
702
+ } finally {
703
+ this.generators.push(...running);
704
+ }
705
+ frame.emitter.close();
706
+ },
707
+ },
708
+ };
709
+ if (!ts.isGetAccessorDeclaration(declaration)) {
710
+ declaration.parameters.forEach((parameter, index) => {
711
+ const given = generator.args[index] ?? constant(undefined);
712
+ const fallback = parameterDefault(this.checker, given, parameter);
713
+ const value = fallback
714
+ ? this.expressions.expression(fallback, inner)
715
+ : given;
716
+ // A parameter the generator never assigns keeps what was passed, which can be known now.
717
+ this.expressions.bind(
718
+ parameter.name,
719
+ value,
720
+ inner,
721
+ this.checker.getTypeAtLocation(parameter),
722
+ {
723
+ mutable: assignsName(body, parameter.name, this.checker),
724
+ iec: this.layouts.iecName(parameter),
725
+ },
726
+ );
727
+ });
728
+ }
729
+ frame.emitter.open(`${labelText(labels)}${whole}: {`);
730
+ this.generators.push(declaration);
731
+ try {
732
+ this.statements(body.statements, inner);
733
+ } finally {
734
+ this.generators.pop();
735
+ }
736
+ frame.emitter.close();
737
+ }
738
+
739
+ /** A yield statement runs the loop over the generator on its value; `yield*` runs another generator in place. */
740
+ private yieldStatement(node: ts.YieldExpression, frame: Frame): void {
741
+ const generator = frame.generator;
742
+ if (!generator) {
743
+ throw new SpecializeError(
744
+ node,
745
+ "A generator runs only where a for…of or an iterator helper reads it.",
746
+ );
747
+ }
748
+ if (!node.expression) {
749
+ generator.yields(constant(undefined));
750
+ return;
751
+ }
752
+ if (node.asteriskToken) {
753
+ const delegated = this.expressions.iterators.generator(
754
+ node.expression,
755
+ frame,
756
+ );
757
+ if (!delegated) {
758
+ throw new SpecializeError(
759
+ node.expression,
760
+ "yield* runs another generator in place; pass it a generator call.",
761
+ );
762
+ }
763
+ this.runGenerator(delegated, frame, [], node, (value) =>
764
+ generator.yields(value),
765
+ );
766
+ return;
767
+ }
768
+ generator.yields(this.expressions.expression(node.expression, frame));
769
+ }
770
+
771
+ /**
772
+ * A loop over what setup built runs its body once per item. A body that breaks or continues runs
773
+ * inside labelled blocks, the whole loop's and each step's, which its jumps leave.
774
+ */
775
+ private unrolled(
776
+ body: ts.Statement,
777
+ labels: readonly string[],
778
+ items: readonly Value[],
779
+ frame: Frame,
780
+ bindStep: (item: Value) => void,
781
+ ): void {
782
+ const jumps = containsJump(body);
783
+ const whole = jumps ? frame.emitter.local("tsplcLoop") : undefined;
784
+ if (whole) {
785
+ frame.emitter.open(`${whole}: {`);
786
+ }
787
+ for (const item of items) {
788
+ const step = jumps ? frame.emitter.local("tsplcStep") : undefined;
789
+ frame.emitter.open(step ? `${step}: {` : "{");
790
+ bindStep(item);
791
+ this.scoped(
792
+ { kind: "loop", labels, breakLabel: whole, continueLabel: step },
793
+ () => this.inner(body, frame),
794
+ );
795
+ frame.emitter.close();
796
+ }
797
+ if (whole) {
798
+ frame.emitter.close();
799
+ }
800
+ }
801
+
802
+ /** `for (const [index, item] of array.entries())` over a runtime array stays a loop, as the backend lowers it. */
803
+ private forEntries(
804
+ node: ts.ForOfStatement,
805
+ iterated: Part,
806
+ labels: readonly string[],
807
+ frame: Frame,
808
+ ): void {
809
+ const binding = onlyDeclaration(node.initializer)?.name;
810
+ const names =
811
+ binding && ts.isArrayBindingPattern(binding)
812
+ ? binding.elements.map((element) =>
813
+ ts.isBindingElement(element) && ts.isIdentifier(element.name)
814
+ ? element.name
815
+ : undefined,
816
+ )
817
+ : [];
818
+ const [indexName, itemName] = names;
819
+ if (names.length !== 2 || !indexName || !itemName) {
820
+ throw new SpecializeError(
821
+ node.initializer,
822
+ "Destructure [index, item] from array.entries().",
823
+ );
824
+ }
825
+ const [index, item] = [indexName, itemName].map((name) => {
826
+ const local = frame.emitter.local(name.text);
827
+ this.bindLocal(name, local, frame, undefined);
828
+ return local;
829
+ });
830
+ frame.emitter.open(
831
+ mapped`${labelText(labels)}for (const [${[index, item].join(", ")}] of ${iterated}) {`,
832
+ );
833
+ this.loop(node.statement, labels, undefined, frame);
834
+ frame.emitter.close();
835
+ }
836
+
837
+ /**
838
+ * A while or do loop that awaits, in an async routine: each wait ends a scan's share of it, so it
839
+ * needs no bound for a scan to finish.
840
+ */
841
+ private suspendingLoop(
842
+ node: ts.WhileStatement | ts.DoStatement,
843
+ labels: readonly string[],
844
+ frame: Frame,
845
+ ): void {
846
+ const test = () =>
847
+ this.dialect.condition(
848
+ this.expressions.expression(node.expression, frame),
849
+ node.expression,
850
+ );
851
+ if (ts.isWhileStatement(node)) {
852
+ frame.emitter.open(mapped`${labelText(labels)}while (${test()}) {`);
853
+ } else {
854
+ frame.emitter.open(`${labelText(labels)}do {`);
855
+ }
856
+ this.loop(node.statement, labels, undefined, frame);
857
+ if (ts.isWhileStatement(node)) {
858
+ frame.emitter.close();
859
+ return;
860
+ }
861
+ frame.emitter.close(mapped`} while (${test()});`);
862
+ }
863
+
864
+ /** A counted loop stays a loop, in the header shape the backend proves bounded: `let i = start; i < bound; i++`. */
865
+ private forLoop(
866
+ node: ts.ForStatement,
867
+ labels: readonly string[],
868
+ frame: Frame,
869
+ ): void {
870
+ const { condition, incrementor, initializer } = node;
871
+ const declaration = onlyDeclaration(initializer);
872
+ if (!declaration || !(declaration.parent.flags & ts.NodeFlags.Let)) {
873
+ throw new SpecializeError(
874
+ node,
875
+ "Declare one let counter in the for header.",
876
+ );
877
+ }
878
+ const name = declaration.name;
879
+ if (!ts.isIdentifier(name) || !declaration.initializer) {
880
+ throw new SpecializeError(declaration, "Initialize the loop counter.");
881
+ }
882
+ if (!condition || !ts.isBinaryExpression(condition) || !incrementor) {
883
+ throw new SpecializeError(
884
+ node,
885
+ "Compare the counter to a bound and step it in the for header.",
886
+ );
887
+ }
888
+ if (assignsName(node.statement, name, this.checker)) {
889
+ throw new SpecializeError(
890
+ node,
891
+ `The loop changes its counter ${name.text} in its body, and a PLC FOR loop's counter is stepped only by its header: step it in the header, or count with a separate let.`,
892
+ );
893
+ }
894
+ const declared = this.checker.getTypeAtLocation(name);
895
+ // An annotation such as UINT keeps the counter's width, to index alongside unsigned fields.
896
+ const iec = this.layouts.iecName(declaration);
897
+ const first = this.expressions.expression(
898
+ declaration.initializer,
899
+ frame,
900
+ declared,
901
+ );
902
+ const start = this.dialect.code(first, declared);
903
+ const local = frame.emitter.local(name.text);
904
+ this.bindLocal(name, local, frame, iec);
905
+ const compared = this.expressions.expression(condition.left, frame);
906
+ const limit = this.expressions.expression(condition.right, frame);
907
+ const test = mapped`${this.dialect.code(compared, declared)} ${condition.operatorToken.getText()} ${this.dialect.code(limit, declared)}`;
908
+ const step = this.loopStep(incrementor, name, local, declared, frame);
909
+ frame.emitter.open(
910
+ mapped`${labelText(labels)}for (let ${local}: ${iec ?? this.expressions.localType(declared)} = ${start}; ${test}; ${step}) {`,
911
+ );
912
+ // How often the body runs is known when the header compares the counter itself with a bound setup fixed.
913
+ const runs =
914
+ compared.kind === "code" && String(compared.text) === local
915
+ ? iterationCount(
916
+ first,
917
+ condition.operatorToken.kind,
918
+ limit,
919
+ incrementor,
920
+ )
921
+ : undefined;
922
+ this.loop(node.statement, labels, runs, frame);
923
+ frame.emitter.close();
924
+ }
925
+
926
+ /** The step in a counted loop's header, as `i++` or `i += n` on the counter's local. */
927
+ private loopStep(
928
+ incrementor: ts.Expression,
929
+ counter: ts.Identifier,
930
+ local: string,
931
+ declared: ts.Type,
932
+ frame: Frame,
933
+ ): Part {
934
+ const counterSymbol = this.checker.getSymbolAtLocation(counter);
935
+ const isCounter = (target: ts.Expression): boolean =>
936
+ this.checker.getSymbolAtLocation(unparenthesized(target)) ===
937
+ counterSymbol;
938
+ if (
939
+ (ts.isPrefixUnaryExpression(incrementor) ||
940
+ ts.isPostfixUnaryExpression(incrementor)) &&
941
+ unitSteps.has(incrementor.operator) &&
942
+ isCounter(incrementor.operand)
943
+ ) {
944
+ return `${local}${ts.tokenToString(incrementor.operator)}`;
945
+ }
946
+ if (
947
+ ts.isBinaryExpression(incrementor) &&
948
+ compoundSteps.has(incrementor.operatorToken.kind) &&
949
+ isCounter(incrementor.left)
950
+ ) {
951
+ return mapped`${local} ${incrementor.operatorToken.getText()} ${this.dialect.code(this.expressions.expression(incrementor.right, frame), declared)}`;
952
+ }
953
+ throw new SpecializeError(
954
+ incrementor,
955
+ "Use i++, i--, i += step or i -= step in the for header.",
956
+ );
957
+ }
958
+
959
+ private switch(
960
+ node: ts.SwitchStatement,
961
+ labels: readonly string[],
962
+ frame: Frame,
963
+ ): void {
964
+ const subject = this.expressions.expression(node.expression, frame);
965
+ const declared = subject.kind === "code" ? subject.declared : undefined;
966
+ if (subject.kind === "const") {
967
+ this.constantSwitch(node, subject, labels, frame);
968
+ return;
969
+ }
970
+ frame.emitter.open(
971
+ mapped`${labelText(labels)}switch (${this.dialect.code(subject, declared)}) {`,
972
+ );
973
+ this.scoped({ kind: "switch", labels }, () =>
974
+ this.switchClauses(node, declared, frame),
975
+ );
976
+ frame.emitter.close();
977
+ }
978
+
979
+ private switchClauses(
980
+ node: ts.SwitchStatement,
981
+ declared: ts.Type | undefined,
982
+ frame: Frame,
983
+ ): void {
984
+ for (const clause of node.caseBlock.clauses) {
985
+ if (ts.isDefaultClause(clause)) {
986
+ frame.emitter.open("default: {");
987
+ if (clause.statements.some(unreachableEnd)) {
988
+ frame.emitter.line(
989
+ frame.returns && !(frame.returns.flags & ts.TypeFlags.Void)
990
+ ? `return ${this.initializers.defaultOf(frame.returns)};`
991
+ : "break;",
992
+ );
993
+ } else {
994
+ this.statements(clause.statements, frame);
995
+ }
996
+ frame.emitter.close();
997
+ continue;
998
+ }
999
+ const label = this.expressions.expression(
1000
+ clause.expression,
1001
+ frame,
1002
+ declared,
1003
+ );
1004
+ frame.emitter.open(mapped`case ${this.dialect.code(label, declared)}: {`);
1005
+ this.statements(clause.statements, frame);
1006
+ frame.emitter.close();
1007
+ }
1008
+ }
1009
+
1010
+ /**
1011
+ * A switch on a value setup fixed runs the clause it matches, falling through as JavaScript does. A
1012
+ * break nested in it leaves the labelled block standing for the switch.
1013
+ */
1014
+ private constantSwitch(
1015
+ node: ts.SwitchStatement,
1016
+ subject: Value & { kind: "const" },
1017
+ labels: readonly string[],
1018
+ frame: Frame,
1019
+ ): void {
1020
+ const nested = node.caseBlock.clauses.some((clause) =>
1021
+ clause.statements.some(
1022
+ (statement) =>
1023
+ !ts.isBreakStatement(statement) && containsJump(statement),
1024
+ ),
1025
+ );
1026
+ const label = nested ? frame.emitter.local("tsplcSwitch") : undefined;
1027
+ if (label) {
1028
+ frame.emitter.open(`${label}: {`);
1029
+ }
1030
+ this.scoped({ kind: "switch", labels, breakLabel: label }, () =>
1031
+ this.matchedClauses(node, subject, labels, frame),
1032
+ );
1033
+ if (label) {
1034
+ frame.emitter.close();
1035
+ }
1036
+ }
1037
+
1038
+ private matchedClauses(
1039
+ node: ts.SwitchStatement,
1040
+ subject: Value & { kind: "const" },
1041
+ labels: readonly string[],
1042
+ frame: Frame,
1043
+ ): void {
1044
+ const clauses = node.caseBlock.clauses;
1045
+ const start = clauses.findIndex((clause) => {
1046
+ if (ts.isDefaultClause(clause)) {
1047
+ return true;
1048
+ }
1049
+ const label = this.expressions.expression(clause.expression, frame);
1050
+ return label.kind === "const" && label.value === subject.value;
1051
+ });
1052
+ if (start < 0) {
1053
+ return;
1054
+ }
1055
+ for (const clause of clauses.slice(start)) {
1056
+ for (const statement of clause.statements) {
1057
+ if (
1058
+ ts.isBreakStatement(statement) &&
1059
+ (!statement.label || labels.includes(statement.label.text))
1060
+ ) {
1061
+ return;
1062
+ }
1063
+ if (this.statement(statement, frame)) {
1064
+ return;
1065
+ }
1066
+ }
1067
+ }
1068
+ }
1069
+
1070
+ /** An expression evaluated for its effect. */
1071
+ private effect(node: ts.Expression, frame: Frame): void {
1072
+ if (ts.isVoidExpression(node)) {
1073
+ const value = this.expressions.expression(node.expression, frame);
1074
+ if (value.kind === "code") {
1075
+ frame.emitter.line(mapped`void ${value.text};`);
1076
+ }
1077
+ return;
1078
+ }
1079
+ if (ts.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
1080
+ this.expressions.assignments.assign(node, frame);
1081
+ return;
1082
+ }
1083
+ if (isUpdate(node)) {
1084
+ this.expressions.assignments.step(node, frame, { used: false });
1085
+ return;
1086
+ }
1087
+ const value = this.expressions.expression(node, frame);
1088
+ if (value.kind === "code" && String(value.text).includes("(")) {
1089
+ frame.emitter.line(mapped`${value.text};`);
1090
+ }
1091
+ }
1092
+ }
1093
+
1094
+ /** The one const a for…of declares. */
1095
+ const loopDeclaration = (node: ts.ForOfStatement): ts.VariableDeclaration => {
1096
+ const declaration = onlyDeclaration(node.initializer);
1097
+ if (!declaration) {
1098
+ throw new SpecializeError(node.initializer, "Declare one const in for…of.");
1099
+ }
1100
+ return declaration;
1101
+ };
1102
+
1103
+ /** The one variable a loop header declares; undefined when it declares none or several. */
1104
+ const onlyDeclaration = (
1105
+ initializer: ts.ForInitializer | undefined,
1106
+ ): ts.VariableDeclaration | undefined => {
1107
+ if (!initializer || !ts.isVariableDeclarationList(initializer)) {
1108
+ return undefined;
1109
+ }
1110
+ const [declaration, ...others] = initializer.declarations;
1111
+ return others.length ? undefined : declaration;
1112
+ };
1113
+
1114
+ /**
1115
+ * How many times a counted loop's body can run: from its start, the bound its counter is compared
1116
+ * with and its step, when setup fixed them all. Undefined for a header that doesn't say.
1117
+ */
1118
+ const iterationCount = (
1119
+ start: Value,
1120
+ comparison: ts.SyntaxKind,
1121
+ limit: Value,
1122
+ incrementor: ts.Expression,
1123
+ ): number | undefined => {
1124
+ const first = known(start);
1125
+ const last = known(limit);
1126
+ const step = stepOf(incrementor);
1127
+ if (
1128
+ first === undefined ||
1129
+ last === undefined ||
1130
+ step === undefined ||
1131
+ !Number.isInteger(first) ||
1132
+ !Number.isInteger(last)
1133
+ ) {
1134
+ return undefined;
1135
+ }
1136
+ const rising = step > 0;
1137
+ const exclusive = rising
1138
+ ? ts.SyntaxKind.LessThanToken
1139
+ : ts.SyntaxKind.GreaterThanToken;
1140
+ const inclusive = rising
1141
+ ? ts.SyntaxKind.LessThanEqualsToken
1142
+ : ts.SyntaxKind.GreaterThanEqualsToken;
1143
+ if (comparison !== exclusive && comparison !== inclusive) {
1144
+ return undefined;
1145
+ }
1146
+ return Number(
1147
+ loopIterations(
1148
+ BigInt(first),
1149
+ BigInt(last),
1150
+ comparison === exclusive,
1151
+ BigInt(step),
1152
+ ),
1153
+ );
1154
+ };
1155
+
1156
+ /** A counted loop's step, as `i++`, `i--`, `i += 2` or `i -= 2` writes it. */
1157
+ const stepOf = (incrementor: ts.Expression): number | undefined => {
1158
+ if (
1159
+ ts.isPrefixUnaryExpression(incrementor) ||
1160
+ ts.isPostfixUnaryExpression(incrementor)
1161
+ ) {
1162
+ return unitSteps.get(incrementor.operator);
1163
+ }
1164
+ if (
1165
+ !ts.isBinaryExpression(incrementor) ||
1166
+ !ts.isNumericLiteral(incrementor.right)
1167
+ ) {
1168
+ return undefined;
1169
+ }
1170
+ const size = Number(incrementor.right.text);
1171
+ if (!Number.isInteger(size) || size <= 0) {
1172
+ return undefined;
1173
+ }
1174
+ const sign = compoundSteps.get(incrementor.operatorToken.kind);
1175
+ return sign === undefined ? undefined : sign * size;
1176
+ };
1177
+
1178
+ const unitSteps = new Map<ts.SyntaxKind, number>([
1179
+ [ts.SyntaxKind.PlusPlusToken, 1],
1180
+ [ts.SyntaxKind.MinusMinusToken, -1],
1181
+ ]);
1182
+
1183
+ const compoundSteps = new Map<ts.SyntaxKind, number>([
1184
+ [ts.SyntaxKind.PlusEqualsToken, 1],
1185
+ [ts.SyntaxKind.MinusEqualsToken, -1],
1186
+ ]);
1187
+
1188
+ const labelText = (labels: readonly string[]): string =>
1189
+ labels.map((label) => `${label}: `).join("");
1190
+
1191
+ /** The statement under a run of labels, collecting them. */
1192
+ const innermostLabelled = (
1193
+ node: ts.LabeledStatement,
1194
+ labels: string[],
1195
+ ): ts.Statement => {
1196
+ labels.push(node.label.text);
1197
+ return ts.isLabeledStatement(node.statement)
1198
+ ? innermostLabelled(node.statement, labels)
1199
+ : node.statement;
1200
+ };
1201
+
1202
+ /** Whether a break or continue sits in the statement, outside functions it declares. */
1203
+ const containsJump = (node: ts.Node): boolean =>
1204
+ occursOutsideFunctions(
1205
+ node,
1206
+ (inner) => ts.isBreakStatement(inner) || ts.isContinueStatement(inner),
1207
+ );
1208
+
1209
+ /** `return x satisfies never`, which marks an end the program never reaches. */
1210
+ const unreachableEnd = (statement: ts.Statement): boolean =>
1211
+ ts.isReturnStatement(statement) &&
1212
+ statement.expression !== undefined &&
1213
+ ts.isSatisfiesExpression(statement.expression) &&
1214
+ statement.expression.type.kind === ts.SyntaxKind.NeverKeyword;
1215
+
1216
+ const unsupported = (node: ts.Statement): SpecializeError =>
1217
+ new SpecializeError(
1218
+ node,
1219
+ `${ts.SyntaxKind[node.kind]} is not supported in scan code.`,
1220
+ );