@tsplc/tmp-compiler 0.0.0-stage → 0.6.3

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 (185) 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 +6563 -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 +16198 -0
  12. package/dist/index.js.map +62 -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 +1090 -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-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,871 @@
1
+ import {
2
+ aggregate,
3
+ type Constant,
4
+ type Expression,
5
+ type IntegerInterval,
6
+ integerRange,
7
+ loopBounds,
8
+ maxLoopIterations,
9
+ type PlcFunction,
10
+ type PlcType,
11
+ type Statement,
12
+ type Variable,
13
+ } from "@tsplc/compiler/ir";
14
+ import ts from "typescript";
15
+ import type { AnalysisContext, ExpressionLowering } from "./expressions";
16
+ import type { Positions } from "./positions";
17
+ import { telemetryStatement } from "./telemetry";
18
+ import { type Fail, inferredStorageType, type TypeResolver } from "./types";
19
+
20
+ type IterationForm = "elements" | "entries" | "recordValues" | "recordEntries";
21
+
22
+ /** The counter a for header initializes, and where the header stands. */
23
+ interface LoopHeader {
24
+ header: ts.ForInitializer;
25
+ counter: Variable;
26
+ initializer: ts.Expression;
27
+ existing: boolean;
28
+ }
29
+
30
+ /**
31
+ * A case's statements, out of the braces that scope its declarations, as control-flow lowering
32
+ * writes every case: they end where the braces do, and blocks lower without a scope of their own.
33
+ */
34
+ const unbraced = (
35
+ statements: readonly ts.Statement[],
36
+ ): readonly ts.Statement[] => {
37
+ const [only] = statements;
38
+ return statements.length === 1 && only && ts.isBlock(only)
39
+ ? unbraced(only.statements)
40
+ : statements;
41
+ };
42
+
43
+ const caseEndMessage = (last: ts.Statement | undefined): string => {
44
+ if (last && ts.isThrowStatement(last)) {
45
+ return "A switch case cannot end in throw; end it with break or return.";
46
+ }
47
+ if (last && ts.isContinueStatement(last)) {
48
+ return "A switch case cannot end in continue; end it with break or return.";
49
+ }
50
+ return "The last switch case must end with break or return.";
51
+ };
52
+
53
+ /**
54
+ * Lowers one routine's statements. Expressions, and the scope facts that
55
+ * declarations, branches and loops establish, go through its ExpressionLowering.
56
+ */
57
+ export class StatementLowering {
58
+ private readonly resolver: TypeResolver;
59
+ private readonly positions: Positions;
60
+ private readonly fail: Fail;
61
+ private readonly breakTargets: ("loop" | "switch")[] = [];
62
+ private readonly locals: Variable[] = [];
63
+
64
+ constructor(
65
+ context: AnalysisContext,
66
+ private readonly expressions: ExpressionLowering,
67
+ private readonly routine: PlcFunction,
68
+ ) {
69
+ this.resolver = context.resolver;
70
+ this.positions = context.positions;
71
+ this.fail = context.fail;
72
+ }
73
+
74
+ /** Lowers a routine's statements, collecting the locals they declare. */
75
+ lowerRoutine(body: ts.Block): { locals: Variable[]; body: Statement[] } {
76
+ return { locals: this.locals, body: this.statements(body.statements) };
77
+ }
78
+
79
+ private statements(nodes: readonly ts.Statement[]): Statement[] {
80
+ return nodes.flatMap((node) => this.statement(node));
81
+ }
82
+
83
+ private body(node: ts.Statement): Statement[] {
84
+ return ts.isBlock(node)
85
+ ? this.statements(node.statements)
86
+ : this.statement(node);
87
+ }
88
+
89
+ private statement(node: ts.Statement): Statement[] {
90
+ const origin = { span: this.positions.node(node) };
91
+ if (ts.isBlock(node)) {
92
+ return this.statements(node.statements);
93
+ }
94
+ if (ts.isEmptyStatement(node)) {
95
+ return [];
96
+ }
97
+ if (ts.isIfStatement(node)) {
98
+ const condition = this.expressions.expression(node.expression, "BOOL");
99
+ const branch = (body: ts.Statement | undefined, truth: boolean) =>
100
+ this.expressions.narrowed(condition, truth, () =>
101
+ body ? this.body(body) : [],
102
+ );
103
+ return [
104
+ {
105
+ ...origin,
106
+ kind: "if",
107
+ condition,
108
+ // biome-ignore lint/suspicious/noThenProperty: This is the IR branch field, not a Promise method.
109
+ then: branch(node.thenStatement, true),
110
+ else: branch(node.elseStatement, false),
111
+ },
112
+ ];
113
+ }
114
+ if (ts.isReturnStatement(node)) {
115
+ const result = this.routine.result;
116
+ if (!result && node.expression) {
117
+ this.fail(
118
+ node,
119
+ "PLC2001",
120
+ "Void helpers and program entries cannot return a value.",
121
+ );
122
+ }
123
+ if (result && !node.expression) {
124
+ this.fail(
125
+ node,
126
+ "PLC2001",
127
+ "Typed helpers must return their declared PLC result.",
128
+ );
129
+ }
130
+ const value =
131
+ node.expression && result
132
+ ? this.expressions.implicitCopy(
133
+ this.expressions.expression(node.expression, result),
134
+ )
135
+ : undefined;
136
+ return [{ ...origin, kind: "return", ...(value && { value }) }];
137
+ }
138
+ if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) {
139
+ // Control-flow lowering has turned every jump Structured Text cannot make into flags; what
140
+ // is left here is a jump TypeScript rejects too.
141
+ if (
142
+ node.label ||
143
+ !this.breakTargets.includes("loop") ||
144
+ (ts.isBreakStatement(node) && this.breakTargets.at(-1) === "switch")
145
+ ) {
146
+ this.fail(
147
+ node,
148
+ "PLC1001",
149
+ "break and continue must leave an enclosing loop.",
150
+ );
151
+ }
152
+ return [
153
+ { ...origin, kind: ts.isBreakStatement(node) ? "break" : "continue" },
154
+ ];
155
+ }
156
+ if (ts.isVariableStatement(node)) {
157
+ return this.localDeclarations(node);
158
+ }
159
+ if (ts.isForStatement(node)) {
160
+ return this.loop(node);
161
+ }
162
+ if (ts.isForOfStatement(node)) {
163
+ return this.forOf(node);
164
+ }
165
+ if (ts.isSwitchStatement(node)) {
166
+ return this.switchStatement(node);
167
+ }
168
+ if (ts.isExpressionStatement(node)) {
169
+ const expression = node.expression;
170
+ if (ts.isCallExpression(expression)) {
171
+ const telemetry = telemetryStatement(this.expressions, expression);
172
+ if (telemetry) {
173
+ return [telemetry];
174
+ }
175
+ const update = this.expressions.update(expression);
176
+ if (update) {
177
+ return [update];
178
+ }
179
+ const call = this.expressions.call(expression);
180
+ return [
181
+ {
182
+ ...origin,
183
+ kind: "invoke",
184
+ function: call.fn.id,
185
+ arguments: call.arguments,
186
+ ...(call.instance && { instance: call.instance }),
187
+ ...(call.index && { index: call.index }),
188
+ },
189
+ ];
190
+ }
191
+ if (ts.isBinaryExpression(expression)) {
192
+ const variable = this.expressions.target(expression.left);
193
+ if (expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken) {
194
+ this.fail(
195
+ expression,
196
+ "PLC2001",
197
+ "Use explicit assignment and arithmetic policies.",
198
+ );
199
+ }
200
+ const value = this.expressions.expression(
201
+ expression.right,
202
+ variable.type,
203
+ );
204
+ this.expressions.recordCopySource(value);
205
+ return [
206
+ {
207
+ ...origin,
208
+ kind: "assign",
209
+ destination: variable.place,
210
+ value: this.expressions.implicitCopy(value),
211
+ },
212
+ ];
213
+ }
214
+ }
215
+ this.fail(
216
+ node,
217
+ "PLC1001",
218
+ `${ts.SyntaxKind[node.kind]} is not supported in PLC scan code.`,
219
+ );
220
+ }
221
+
222
+ /** A routine-local variable, declared where `declaration` stands. */
223
+ private local(
224
+ declaration: ts.Node,
225
+ name: string,
226
+ type: string,
227
+ { mutable }: { mutable: boolean },
228
+ ): Variable {
229
+ const variable: Variable = {
230
+ id: this.expressions.storageId(declaration, name),
231
+ name,
232
+ type,
233
+ storage: "local",
234
+ mutable,
235
+ retention: "none",
236
+ span: this.positions.node(declaration),
237
+ };
238
+ this.locals.push(variable);
239
+ return variable;
240
+ }
241
+
242
+ /** Grouped labels share the body of the clause that ends them; a default label's body is the fallback. */
243
+ private switchStatement(node: ts.SwitchStatement): Statement[] {
244
+ const origin = { span: this.positions.node(node) };
245
+ this.breakTargets.push("switch");
246
+ try {
247
+ const value = this.expressions.expression(node.expression);
248
+ const { clauses } = node.caseBlock;
249
+ const cases: { values: Constant[]; body: Statement[] }[] = [];
250
+ const labels: Constant[] = [];
251
+ const bodies = clauses.map((clause) => {
252
+ if (!ts.isDefaultClause(clause)) {
253
+ labels.push(this.caseValue(clause, value.type));
254
+ }
255
+ const statements = unbraced(clause.statements);
256
+ const body = statements.length
257
+ ? this.caseBody(clause, statements)
258
+ : undefined;
259
+ if (body && labels.length) {
260
+ cases.push({ values: labels.splice(0), body });
261
+ }
262
+ return body;
263
+ });
264
+ if (labels.length) {
265
+ cases.push({ values: labels, body: [] });
266
+ }
267
+ // The default label shares the body of the clause that ends its group.
268
+ const fallbackIndex = clauses.findIndex(ts.isDefaultClause);
269
+ const fallback =
270
+ fallbackIndex < 0
271
+ ? []
272
+ : (bodies.slice(fallbackIndex).find((body) => body !== undefined) ??
273
+ []);
274
+ return [{ ...origin, kind: "switch", value, cases, fallback }];
275
+ } finally {
276
+ this.breakTargets.pop();
277
+ }
278
+ }
279
+
280
+ private caseValue(clause: ts.CaseClause, type: string): Constant {
281
+ const constant = this.expressions.constant(
282
+ this.expressions.expression(clause.expression, type),
283
+ );
284
+ if (!constant) {
285
+ this.fail(
286
+ clause,
287
+ "PLC2001",
288
+ "Case values must be compile-time constants.",
289
+ );
290
+ }
291
+ return constant;
292
+ }
293
+
294
+ /** A case's statements without the break that ends it. */
295
+ private caseBody(
296
+ clause: ts.CaseOrDefaultClause,
297
+ statements: readonly ts.Statement[],
298
+ ): Statement[] {
299
+ const last = statements.at(-1);
300
+ if (last && ts.isBreakStatement(last) && !last.label) {
301
+ return this.statements(statements.slice(0, -1));
302
+ }
303
+ if (last && ts.isReturnStatement(last)) {
304
+ return this.statements(statements);
305
+ }
306
+ // Control-flow lowering gives a case that runs on into the next its own break, so only the
307
+ // last case can still run off the end.
308
+ this.fail(clause, "PLC1001", caseEndMessage(last));
309
+ }
310
+
311
+ private localDeclarations(node: ts.VariableStatement): Statement[] {
312
+ const origin = { span: this.positions.node(node) };
313
+ if (
314
+ !(node.declarationList.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const))
315
+ ) {
316
+ this.fail(node, "PLC1001", "Use let or const for invocation locals.");
317
+ }
318
+ const immutable = Boolean(node.declarationList.flags & ts.NodeFlags.Const);
319
+ return node.declarationList.declarations.flatMap((declaration) => {
320
+ if (!ts.isIdentifier(declaration.name)) {
321
+ this.fail(declaration, "PLC1001", "Destructuring is not supported.");
322
+ }
323
+ if (!declaration.initializer) {
324
+ this.fail(
325
+ declaration,
326
+ "PLC3001",
327
+ "Initialize invocation-local PLC variables explicitly.",
328
+ );
329
+ }
330
+ const annotation = declaration.type
331
+ ? this.expressions.type(declaration.type)
332
+ : undefined;
333
+ if (annotation && !this.resolver.isValue(annotation)) {
334
+ this.fail(
335
+ declaration,
336
+ "PLC2001",
337
+ "Invocation locals require value types, not instances or borrow schemas.",
338
+ );
339
+ }
340
+ if (annotation?.io) {
341
+ this.fail(
342
+ declaration,
343
+ "PLC4002",
344
+ "Logical I/O cannot be invocation-local.",
345
+ );
346
+ }
347
+ if (
348
+ !annotation &&
349
+ !immutable &&
350
+ inferredStorageType(declaration.initializer) === undefined
351
+ ) {
352
+ this.fail(
353
+ declaration,
354
+ "PLC2001",
355
+ "Annotate mutable numeric storage explicitly.",
356
+ );
357
+ }
358
+ const initial = this.expressions.expression(
359
+ declaration.initializer,
360
+ annotation?.type,
361
+ );
362
+ if (
363
+ immutable &&
364
+ initial.kind === "load" &&
365
+ aggregate(this.resolver.types.get(initial.type))
366
+ ) {
367
+ for (const segment of initial.place.path) {
368
+ if (
369
+ segment.kind === "index" &&
370
+ !this.expressions.unchanging(segment.value)
371
+ ) {
372
+ this.fail(
373
+ declaration,
374
+ "PLC3003",
375
+ "An alias index must keep its value while the alias is in scope; use copy(value) for a snapshot.",
376
+ );
377
+ }
378
+ }
379
+ this.expressions.alias(
380
+ this.resolver.symbol(declaration.name),
381
+ initial.place,
382
+ );
383
+ return [];
384
+ }
385
+ this.expressions.recordCopySource(initial);
386
+ const value = this.expressions.implicitCopy(initial);
387
+ const variable = this.local(
388
+ declaration,
389
+ declaration.name.text,
390
+ value.type,
391
+ { mutable: !immutable },
392
+ );
393
+ this.expressions.bind(this.resolver.symbol(declaration.name), variable);
394
+ if (!variable.mutable) {
395
+ this.expressions.holdRange(variable.id, value);
396
+ }
397
+ return {
398
+ ...origin,
399
+ kind: "assign",
400
+ destination: { root: variable.id, path: [] },
401
+ value,
402
+ };
403
+ });
404
+ }
405
+
406
+ private loop(node: ts.ForStatement): Statement[] {
407
+ const { header, counter, initializer, existing } = this.loopHeader(node);
408
+ const type = counter.type;
409
+ const plcType = this.resolver.types.get(type);
410
+ if (plcType?.kind !== "integer") {
411
+ this.fail(header, "PLC2001", "Loop counters require integer types.");
412
+ }
413
+ const startExpression = this.expressions.expression(initializer, type);
414
+ const start = this.expressions.constant(startExpression);
415
+ const isCounter = (expression: ts.Expression): boolean => {
416
+ const place = this.expressions.place(expression);
417
+ return place.root === counter.id && place.path.length === 0;
418
+ };
419
+ const condition = node.condition;
420
+ if (
421
+ !condition ||
422
+ !ts.isBinaryExpression(condition) ||
423
+ !isCounter(condition.left)
424
+ ) {
425
+ this.fail(
426
+ node,
427
+ "PLC1001",
428
+ "Loop condition must compare its counter to a bounded integer.",
429
+ );
430
+ }
431
+ const boundExpression = this.expressions.expression(condition.right, type);
432
+ const bound = this.expressions.constant(boundExpression);
433
+ const step = this.loopStep(node, type, isCounter);
434
+ const operator = condition.operatorToken.kind;
435
+ const ascending = step > 0n;
436
+ const comparisons = ascending
437
+ ? [ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken]
438
+ : [ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken];
439
+ if (!comparisons.includes(operator)) {
440
+ this.fail(
441
+ condition,
442
+ "PLC2001",
443
+ "Loop direction and comparison must agree.",
444
+ );
445
+ }
446
+ const exclusive =
447
+ operator === ts.SyntaxKind.LessThanToken ||
448
+ operator === ts.SyntaxKind.GreaterThanToken;
449
+ if (start?.kind !== "integer" || bound?.kind !== "integer") {
450
+ const startRange = this.expressions.interval(startExpression);
451
+ const limitRange = this.expressions.interval(boundExpression);
452
+ if (!startRange || !limitRange) {
453
+ this.fail(
454
+ node,
455
+ "PLC2001",
456
+ "Loop bounds require finite integer ranges.",
457
+ );
458
+ }
459
+ const proof = loopBounds(startRange, limitRange, step, exclusive);
460
+ this.checkIterations(node, proof.count);
461
+ if (existing && proof.count > 0n) {
462
+ this.checkFinalIncrement(node, plcType, proof.terminal);
463
+ }
464
+ return this.inLoop([counter.id], counter.id, proof.range, () => [
465
+ {
466
+ span: this.positions.node(node),
467
+ kind: "for",
468
+ counter: counter.id,
469
+ ...(existing && { counterScope: "existing" as const }),
470
+ start: startExpression,
471
+ limit: boundExpression,
472
+ step: String(step),
473
+ ...(exclusive && { exclusive: true as const }),
474
+ maxIterations: Number(proof.count),
475
+ body: this.body(node.statement),
476
+ },
477
+ ]);
478
+ }
479
+ const first = BigInt(start.value);
480
+ const limit = BigInt(bound.value);
481
+ const { last, count, range, terminal } = loopBounds(
482
+ [first, first],
483
+ [limit, limit],
484
+ step,
485
+ exclusive,
486
+ );
487
+ this.checkIterations(node, count);
488
+ if (existing) {
489
+ this.checkFinalIncrement(node, plcType, terminal);
490
+ }
491
+ const body = this.inLoop([counter.id], counter.id, range, () =>
492
+ this.body(node.statement),
493
+ );
494
+ const startConstant: Expression = {
495
+ kind: "constant",
496
+ type,
497
+ value: start,
498
+ span: this.positions.node(initializer),
499
+ };
500
+ if (!count) {
501
+ // The body never runs, but an existing counter still takes its start value.
502
+ return existing
503
+ ? [
504
+ {
505
+ kind: "assign",
506
+ destination: { root: counter.id, path: [] },
507
+ value: startConstant,
508
+ span: this.positions.node(header),
509
+ },
510
+ ]
511
+ : [];
512
+ }
513
+ return [
514
+ {
515
+ span: this.positions.node(node),
516
+ kind: "for",
517
+ counter: counter.id,
518
+ ...(existing && { counterScope: "existing" as const }),
519
+ start: startConstant,
520
+ limit: {
521
+ kind: "constant",
522
+ type,
523
+ value: { kind: "integer", value: String(last) },
524
+ span: this.positions.node(condition.right),
525
+ },
526
+ step: String(step),
527
+ maxIterations: Number(count),
528
+ body,
529
+ },
530
+ ];
531
+ }
532
+
533
+ /** A new `let` counter, or an assigned local, module variable or private block field. */
534
+ private loopHeader(node: ts.ForStatement): LoopHeader {
535
+ const header = node.initializer;
536
+ if (header && ts.isVariableDeclarationList(header)) {
537
+ const [declaration, ...others] = header.declarations;
538
+ if (!(header.flags & ts.NodeFlags.Let) || !declaration || others.length) {
539
+ this.fail(
540
+ node,
541
+ "PLC1001",
542
+ "A bounded for loop requires one let counter or an existing counter assignment.",
543
+ );
544
+ }
545
+ if (!ts.isIdentifier(declaration.name) || !declaration.initializer) {
546
+ this.fail(node, "PLC2001", "Initialize the integer loop counter.");
547
+ }
548
+ const annotation = declaration.type
549
+ ? this.expressions.type(declaration.type)
550
+ : { type: "DINT" };
551
+ if (annotation.io) {
552
+ this.fail(
553
+ declaration,
554
+ "PLC4002",
555
+ "Loop counters cannot use I/O wrappers.",
556
+ );
557
+ }
558
+ const counter = this.local(
559
+ declaration,
560
+ declaration.name.text,
561
+ annotation.type,
562
+ { mutable: true },
563
+ );
564
+ this.expressions.bind(this.resolver.symbol(declaration.name), counter);
565
+ return {
566
+ header,
567
+ counter,
568
+ initializer: declaration.initializer,
569
+ existing: false,
570
+ };
571
+ }
572
+ if (
573
+ header &&
574
+ ts.isBinaryExpression(header) &&
575
+ header.operatorToken.kind === ts.SyntaxKind.EqualsToken
576
+ ) {
577
+ const target = this.expressions.target(header.left);
578
+ const counter = this.expressions.byId().get(target.place.root);
579
+ if (
580
+ !counter ||
581
+ target.place.path.length ||
582
+ !["local", "module", "field"].includes(counter.storage)
583
+ ) {
584
+ this.fail(
585
+ header,
586
+ "PLC1001",
587
+ "An existing loop counter must be a local, module variable or private block field.",
588
+ );
589
+ }
590
+ return { header, counter, initializer: header.right, existing: true };
591
+ }
592
+ this.fail(
593
+ node,
594
+ "PLC1001",
595
+ "Initialize one let counter or assign an existing counter in the for header.",
596
+ );
597
+ }
598
+
599
+ /** The header's constant step: `i++`, `i--`, `i += step` or `i -= step`. */
600
+ private loopStep(
601
+ node: ts.ForStatement,
602
+ type: string,
603
+ isCounter: (expression: ts.Expression) => boolean,
604
+ ): bigint {
605
+ const increment = node.incrementor;
606
+ if (
607
+ increment &&
608
+ (ts.isPostfixUnaryExpression(increment) ||
609
+ ts.isPrefixUnaryExpression(increment)) &&
610
+ isCounter(increment.operand) &&
611
+ [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(
612
+ increment.operator,
613
+ )
614
+ ) {
615
+ return increment.operator === ts.SyntaxKind.PlusPlusToken ? 1n : -1n;
616
+ }
617
+ if (
618
+ increment &&
619
+ ts.isBinaryExpression(increment) &&
620
+ isCounter(increment.left) &&
621
+ [ts.SyntaxKind.PlusEqualsToken, ts.SyntaxKind.MinusEqualsToken].includes(
622
+ increment.operatorToken.kind,
623
+ )
624
+ ) {
625
+ const amount = this.expressions.constant(
626
+ this.expressions.expression(increment.right, type),
627
+ );
628
+ if (amount?.kind !== "integer" || BigInt(amount.value) <= 0n) {
629
+ this.fail(
630
+ increment,
631
+ "PLC2001",
632
+ "Loop step must be a positive constant integer.",
633
+ );
634
+ }
635
+ const magnitude = BigInt(amount.value);
636
+ return increment.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken
637
+ ? magnitude
638
+ : -magnitude;
639
+ }
640
+ this.fail(
641
+ node,
642
+ "PLC1001",
643
+ "Use i++, i--, i += step or i -= step in the for header.",
644
+ );
645
+ }
646
+
647
+ private checkIterations(node: ts.ForStatement, count: bigint): void {
648
+ if (count > maxLoopIterations) {
649
+ this.fail(
650
+ node,
651
+ "PLC2001",
652
+ `A scan loop cannot exceed ${maxLoopIterations.toLocaleString("en-US")} iterations.`,
653
+ );
654
+ }
655
+ }
656
+
657
+ /** An existing counter keeps its value after the loop, so its final increment must fit. */
658
+ private checkFinalIncrement(
659
+ node: ts.ForStatement,
660
+ type: Extract<PlcType, { kind: "integer" }>,
661
+ terminal: bigint,
662
+ ): void {
663
+ const [minimum, maximum] = integerRange(type);
664
+ if (terminal < minimum || terminal > maximum) {
665
+ this.fail(
666
+ node,
667
+ "PLC2001",
668
+ "The existing loop counter would overflow on its final increment.",
669
+ );
670
+ }
671
+ }
672
+
673
+ /**
674
+ * `for (const element of array)` is a bounded FOR over the array's declared bounds whose
675
+ * element binding aliases `array[counter]`. `array.entries()` also binds the counter. An
676
+ * enum-keyed Record iterates with `Object.values(record)`, or SDK `entries(record)` for its key.
677
+ */
678
+ private forOf(node: ts.ForOfStatement): Statement[] {
679
+ const list = node.initializer;
680
+ const [declaration, ...others] = ts.isVariableDeclarationList(list)
681
+ ? list.declarations
682
+ : [];
683
+ if (
684
+ node.awaitModifier ||
685
+ !ts.isVariableDeclarationList(list) ||
686
+ !(list.flags & ts.NodeFlags.Const) ||
687
+ !declaration ||
688
+ others.length
689
+ ) {
690
+ this.fail(
691
+ node,
692
+ "PLC1001",
693
+ "for…of binds one const element of a PLC array.",
694
+ );
695
+ }
696
+ const { form, iterated } = this.iteration(node.expression);
697
+ const binding = declaration.name;
698
+ const keyed = form === "entries" || form === "recordEntries";
699
+ const names = ts.isArrayBindingPattern(binding)
700
+ ? binding.elements.map((element) =>
701
+ ts.isBindingElement(element) &&
702
+ !element.dotDotDotToken &&
703
+ !element.initializer &&
704
+ ts.isIdentifier(element.name)
705
+ ? element.name
706
+ : undefined,
707
+ )
708
+ : [undefined, ts.isIdentifier(binding) ? binding : undefined];
709
+ const [indexName, elementName] = names;
710
+ if (names.length !== 2 || !elementName || Boolean(indexName) !== keyed) {
711
+ this.fail(
712
+ binding,
713
+ "PLC1001",
714
+ "Bind one element, or destructure [index, element] from array.entries() or entries(record).",
715
+ );
716
+ }
717
+ const place = this.expressions.place(iterated);
718
+ const iteratedType = this.expressions.placeType(place).type;
719
+ const array =
720
+ iteratedType === undefined
721
+ ? undefined
722
+ : this.resolver.types.get(iteratedType);
723
+ if (
724
+ array?.kind !== "array" ||
725
+ Boolean(array.index) !== form.startsWith("record")
726
+ ) {
727
+ this.fail(
728
+ node.expression,
729
+ "PLC2001",
730
+ "for…of iterates a FixedArray, array.entries(), or an enum-keyed Record through Object.values(record) or entries(record).",
731
+ );
732
+ }
733
+ for (const segment of place.path) {
734
+ if (
735
+ segment.kind === "index" &&
736
+ !this.expressions.unchanging(segment.value)
737
+ ) {
738
+ this.fail(
739
+ node.expression,
740
+ "PLC3003",
741
+ "An iterated array's index must keep its value.",
742
+ );
743
+ }
744
+ }
745
+
746
+ const origin = { span: this.positions.node(node) };
747
+ const constant = (type: string, value: string): Expression => ({
748
+ ...origin,
749
+ kind: "constant",
750
+ type,
751
+ value: { kind: "integer", value },
752
+ });
753
+ const counter = this.local(
754
+ node,
755
+ form === "entries" && indexName ? indexName.text : "index",
756
+ "DINT",
757
+ { mutable: true },
758
+ );
759
+ const index: Expression = {
760
+ ...origin,
761
+ kind: "load",
762
+ type: "DINT",
763
+ place: { root: counter.id, path: [] },
764
+ };
765
+ const before: Statement[] = [];
766
+ const prefix: Statement[] = [];
767
+ const counters = [counter.id];
768
+ const enumeration = array.index
769
+ ? this.resolver.types.get(array.index)
770
+ : undefined;
771
+ if (indexName && enumeration?.kind === "enum") {
772
+ const key = this.local(indexName, indexName.text, enumeration.id, {
773
+ mutable: true,
774
+ });
775
+ const assign = (value: string): Statement => ({
776
+ ...origin,
777
+ kind: "assign",
778
+ destination: { root: key.id, path: [] },
779
+ value: constant(key.type, value),
780
+ });
781
+ before.push(assign(String(array.lowerBound)));
782
+ prefix.push({
783
+ ...origin,
784
+ kind: "switch",
785
+ value: index,
786
+ cases: enumeration.members.map((member) => ({
787
+ values: [{ kind: "integer", value: member.value }],
788
+ body: [assign(member.value)],
789
+ })),
790
+ fallback: [],
791
+ });
792
+ counters.push(key.id);
793
+ this.expressions.bind(this.resolver.symbol(indexName), key);
794
+ } else if (indexName) {
795
+ this.expressions.bind(this.resolver.symbol(indexName), counter);
796
+ }
797
+ this.expressions.alias(this.resolver.symbol(elementName), {
798
+ root: place.root,
799
+ path: [...place.path, { kind: "index", value: index }],
800
+ });
801
+
802
+ const upper = array.lowerBound + array.length - 1;
803
+ return this.inLoop(
804
+ counters,
805
+ counter.id,
806
+ [BigInt(array.lowerBound), BigInt(upper)],
807
+ () => [
808
+ ...before,
809
+ {
810
+ ...origin,
811
+ kind: "for",
812
+ counter: counter.id,
813
+ start: constant("DINT", String(array.lowerBound)),
814
+ limit: constant("DINT", String(upper)),
815
+ step: "1",
816
+ maxIterations: array.length,
817
+ body: [...prefix, ...this.body(node.statement)],
818
+ },
819
+ ],
820
+ );
821
+ }
822
+
823
+ /** What a for…of iterates: an array's elements or `entries()`, or a record's `Object.values` or SDK `entries`. */
824
+ private iteration(expression: ts.Expression): {
825
+ form: IterationForm;
826
+ iterated: ts.Expression;
827
+ } {
828
+ if (!ts.isCallExpression(expression)) {
829
+ return { form: "elements", iterated: expression };
830
+ }
831
+ const callee = expression.expression;
832
+ if (
833
+ ts.isPropertyAccessExpression(callee) &&
834
+ callee.name.text === "entries" &&
835
+ !expression.arguments.length
836
+ ) {
837
+ return { form: "entries", iterated: callee.expression };
838
+ }
839
+ const [record, ...rest] = expression.arguments;
840
+ if (!record || rest.length) {
841
+ return { form: "elements", iterated: expression };
842
+ }
843
+ if (this.expressions.sdkCall(expression) === "entries") {
844
+ return { form: "recordEntries", iterated: record };
845
+ }
846
+ if (
847
+ ts.isPropertyAccessExpression(callee) &&
848
+ callee.name.text === "values" &&
849
+ ts.isIdentifier(callee.expression) &&
850
+ this.resolver.standardLibrary(this.resolver.symbol(callee.expression))
851
+ ) {
852
+ return { form: "recordValues", iterated: record };
853
+ }
854
+ return { form: "elements", iterated: expression };
855
+ }
856
+
857
+ /** Lowers a loop body as `counting` does, inside a loop that break and continue leave. */
858
+ private inLoop<T>(
859
+ counters: readonly string[],
860
+ counter: string,
861
+ range: IntegerInterval,
862
+ lower: () => T,
863
+ ): T {
864
+ this.breakTargets.push("loop");
865
+ try {
866
+ return this.expressions.counting(counters, counter, range, lower);
867
+ } finally {
868
+ this.breakTargets.pop();
869
+ }
870
+ }
871
+ }