@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,1116 @@
1
+ import { aggregate, expressionIssue, placeType, valueFits } from "./aggregates";
2
+ import {
3
+ type CoreExpression,
4
+ type CoreFunction,
5
+ type CoreFunctionBlock,
6
+ type CorePath,
7
+ type CoreStatement,
8
+ isBlockRoutine,
9
+ temporaryId,
10
+ } from "./core-model";
11
+ import type { ModuleDeclarations } from "./declarations";
12
+ import type { SourceSpan } from "./diagnostics";
13
+ import { fold } from "./fold";
14
+ import type {
15
+ Expression,
16
+ FunctionBlock,
17
+ Place,
18
+ PlcFunction,
19
+ Statement,
20
+ Variable,
21
+ } from "./model";
22
+ import { reject } from "./normalization-error";
23
+ import { admits, canonicalInteger, type IntegerInterval } from "./numeric";
24
+ import {
25
+ interval,
26
+ loopBounds,
27
+ maxLoopIterations,
28
+ narrowRanges,
29
+ } from "./ranges";
30
+ import { type BranchOperand, lowerLogical, lowerSelect } from "./short-circuit";
31
+ import { lookup } from "./tables";
32
+ import { instancedBlock, integerRange, isValueType } from "./types";
33
+
34
+ type Flow = "fallthrough" | "return" | "loop" | "mixed";
35
+ interface FlowState {
36
+ flow: Flow;
37
+ initialized: Set<string>;
38
+ }
39
+ interface BodyResult extends FlowState {
40
+ body: CoreStatement[];
41
+ }
42
+
43
+ // Only paths that reach the next statement participate in a join. A local is
44
+ // definitely initialized when every such path initialized it; branches that
45
+ // return or leave the loop do not constrain it.
46
+ const join = (
47
+ branches: readonly [BodyResult, ...BodyResult[]],
48
+ initialized: Set<string>,
49
+ ): FlowState => {
50
+ const [falling, ...others] = branches.filter(
51
+ (branch) => branch.flow === "fallthrough",
52
+ );
53
+ if (falling) {
54
+ return {
55
+ flow: "fallthrough",
56
+ initialized: new Set(
57
+ [...falling.initialized].filter((id) =>
58
+ others.every((branch) => branch.initialized.has(id)),
59
+ ),
60
+ ),
61
+ };
62
+ }
63
+ const [{ flow }] = branches;
64
+ return {
65
+ flow: branches.every((branch) => branch.flow === flow) ? flow : "mixed",
66
+ initialized,
67
+ };
68
+ };
69
+
70
+ export class RoutineNormalizer {
71
+ private readonly parameters: readonly Variable[];
72
+
73
+ private readonly owner: FunctionBlock | undefined;
74
+
75
+ /** The storage the routine's source may name; temporaries are not in it, so a place the source names can't reach one. */
76
+ private readonly scope: Map<string, Variable>;
77
+
78
+ private readonly locals: Variable[];
79
+
80
+ private readonly ranges = new Map<string, IntegerInterval>();
81
+
82
+ private readonly counters = new Set<string>();
83
+
84
+ private readonly callees = new Set<string>();
85
+
86
+ private temporaryCount = 0;
87
+
88
+ constructor(
89
+ private readonly routine: PlcFunction | FunctionBlock,
90
+ private readonly declarations: ModuleDeclarations,
91
+ ) {
92
+ if (isBlockRoutine(routine)) {
93
+ this.owner = routine;
94
+ this.parameters = routine.inputs;
95
+ } else {
96
+ this.owner = routine.owner
97
+ ? declarations.blocks.get(routine.owner.block)
98
+ : undefined;
99
+ this.parameters = routine.parameters;
100
+ }
101
+ this.scope = new Map(declarations.globals);
102
+ for (const item of [
103
+ ...this.parameters,
104
+ ...(this.owner ? [...this.owner.state, ...this.owner.outputs] : []),
105
+ ...routine.locals,
106
+ ]) {
107
+ this.scope.set(item.id, item);
108
+ }
109
+ this.locals = [...routine.locals];
110
+ }
111
+
112
+ normalize(): {
113
+ routine: CoreFunction | CoreFunctionBlock;
114
+ callees: ReadonlySet<string>;
115
+ } {
116
+ const { routine } = this;
117
+ // A standard block has no body: the vendor library implements it.
118
+ if (isBlockRoutine(routine) && routine.standard) {
119
+ return { routine: { ...routine, body: [] }, callees: this.callees };
120
+ }
121
+ return {
122
+ routine: { ...routine, locals: this.locals, body: this.routineBody() },
123
+ callees: this.callees,
124
+ };
125
+ }
126
+
127
+ private routineBody(): CoreStatement[] {
128
+ const normalized = this.body(
129
+ this.routine.body,
130
+ new Set(this.parameters.map((item) => item.id)),
131
+ );
132
+ if (this.routine.result && normalized.flow !== "return") {
133
+ reject("A typed helper must return on every path.", this.routine.span);
134
+ }
135
+ return normalized.body;
136
+ }
137
+
138
+ private temporary(type: string, span: SourceSpan): Variable {
139
+ const id = this.unclaimedTemporaryId();
140
+ this.declarations.claimId(id);
141
+ const item: Variable = {
142
+ id,
143
+ name: `temporary_${this.temporaryCount}`,
144
+ type,
145
+ storage: "local",
146
+ mutable: true,
147
+ retention: "none",
148
+ span,
149
+ };
150
+ this.locals.push(item);
151
+ return item;
152
+ }
153
+
154
+ private unclaimedTemporaryId(): string {
155
+ const id = temporaryId(this.routine.id, this.temporaryCount++);
156
+ return this.declarations.hasId(id) ? this.unclaimedTemporaryId() : id;
157
+ }
158
+
159
+ private load(variable: Variable, span: SourceSpan): CoreExpression {
160
+ return { kind: "load", root: variable.id, type: variable.type, span };
161
+ }
162
+
163
+ /** The block a method or update receiver instantiates: a static instance, or an InOut reference to one. */
164
+ private receiverBlock(id: string): string | undefined {
165
+ const variable = this.scope.get(id);
166
+ if (variable?.storage !== "instance" && variable?.mode !== "inOut") {
167
+ return undefined;
168
+ }
169
+ return instancedBlock(variable.type, this.declarations.types)?.block;
170
+ }
171
+
172
+ private verifyCall(
173
+ id: string,
174
+ arguments_: readonly Expression[],
175
+ span: SourceSpan,
176
+ instance: string | undefined,
177
+ ): PlcFunction {
178
+ const called = this.declarations.signatures.get(id);
179
+ if (!called || called.parameters.length !== arguments_.length) {
180
+ reject("Unknown helper or wrong argument count.", span);
181
+ }
182
+ if (called.owner) {
183
+ if (instance) {
184
+ if (this.receiverBlock(instance) !== called.owner.block) {
185
+ reject(
186
+ "Method calls require a matching static block instance.",
187
+ span,
188
+ );
189
+ }
190
+ } else if (this.owner?.id !== called.owner.block) {
191
+ reject(
192
+ "An implicit method call requires its owning block scope.",
193
+ span,
194
+ );
195
+ }
196
+ if (
197
+ called.owner.access !== "public" &&
198
+ this.owner?.id !== called.owner.block
199
+ ) {
200
+ reject(
201
+ "Private and protected methods require their owning block scope.",
202
+ span,
203
+ );
204
+ }
205
+ } else if (instance) {
206
+ reject("Ordinary functions cannot have an instance receiver.", span);
207
+ }
208
+ this.callees.add(id);
209
+ arguments_.forEach((argument, index) => {
210
+ if (argument.type !== called.parameters[index]?.type) {
211
+ reject("Helper argument has the wrong PLC type.", argument.span);
212
+ }
213
+ });
214
+ return called;
215
+ }
216
+
217
+ private expression(
218
+ value: Expression,
219
+ initialized: Set<string>,
220
+ output: CoreStatement[],
221
+ { allowAggregateLoad }: { allowAggregateLoad?: true } = {},
222
+ ): CoreExpression {
223
+ const type = this.declarations.types.get(value.type);
224
+ if (!type || !isValueType(value.type, this.declarations.types)) {
225
+ reject("Unknown or non-value expression type.", value.span);
226
+ }
227
+ if (value.kind === "borrow") {
228
+ reject(
229
+ "Borrowed places are only valid in block update arguments.",
230
+ value.span,
231
+ );
232
+ }
233
+ const common = { type: value.type, span: value.span };
234
+ if (value.kind === "length") {
235
+ const array = this.declarations.types.get(value.operand.type);
236
+ if (array?.kind !== "array" || value.type !== "DINT") {
237
+ reject("Length requires a fixed array and DINT result.", value.span);
238
+ }
239
+ if (value.operand.kind === "load") {
240
+ const source = this.scope.get(value.operand.place.root);
241
+ const checked = placeType(
242
+ value.operand.place,
243
+ this.declarations.types,
244
+ this.scope,
245
+ this.ranges,
246
+ );
247
+ if (
248
+ !source ||
249
+ checked.issue ||
250
+ checked.type !== value.operand.type ||
251
+ (source.storage === "local" && !initialized.has(source.id))
252
+ ) {
253
+ reject(checked.issue ?? "Invalid array receiver.", value.span);
254
+ }
255
+ this.normalizePath(value.operand.place, initialized, output);
256
+ } else {
257
+ this.expression(value.operand, initialized, output, {
258
+ allowAggregateLoad: true,
259
+ });
260
+ }
261
+ return {
262
+ ...common,
263
+ kind: "constant",
264
+ value: { kind: "integer", value: String(array.length) },
265
+ };
266
+ }
267
+ if (value.kind === "conditional") {
268
+ if (
269
+ value.condition.type !== "BOOL" ||
270
+ value.then.type !== value.type ||
271
+ value.else.type !== value.type
272
+ ) {
273
+ reject("Invalid conditional types.", value.span);
274
+ }
275
+ const condition = this.expression(value.condition, initialized, output);
276
+ const result = this.temporary(value.type, value.span);
277
+ const whenTrue = this.branchOperand(value.then, initialized);
278
+ const whenFalse = this.branchOperand(value.else, initialized);
279
+ output.push(
280
+ lowerSelect({
281
+ result: { root: result.id, type: result.type },
282
+ condition,
283
+ whenTrue,
284
+ whenFalse,
285
+ span: value.span,
286
+ }),
287
+ );
288
+ initialized.add(result.id);
289
+ return this.load(result, value.span);
290
+ }
291
+ if (value.kind === "call") {
292
+ const called = this.verifyCall(
293
+ value.function,
294
+ value.arguments,
295
+ value.span,
296
+ value.instance,
297
+ );
298
+ if (called.result !== value.type) {
299
+ reject("Expression call requires a matching result type.", value.span);
300
+ }
301
+ const index =
302
+ value.instance &&
303
+ this.instanceIndex(
304
+ value.instance,
305
+ value.index,
306
+ initialized,
307
+ output,
308
+ value.span,
309
+ );
310
+ const arguments_ = this.arguments(
311
+ called.parameters,
312
+ value.arguments,
313
+ initialized,
314
+ output,
315
+ );
316
+ const result = this.temporary(value.type, value.span);
317
+ output.push({
318
+ kind: "invoke",
319
+ function: value.function,
320
+ ...(value.instance && { instance: value.instance }),
321
+ ...(index && { index }),
322
+ arguments: arguments_,
323
+ destination: result.id,
324
+ span: value.span,
325
+ });
326
+ initialized.add(result.id);
327
+ return this.load(result, value.span);
328
+ }
329
+ const issue = expressionIssue(
330
+ value,
331
+ this.declarations.types,
332
+ this.scope,
333
+ this.ranges,
334
+ );
335
+ if (issue) {
336
+ reject(issue, value.span);
337
+ }
338
+ switch (value.kind) {
339
+ case "copy":
340
+ return this.expression(value.operand, initialized, output, {
341
+ allowAggregateLoad: true,
342
+ });
343
+ case "record":
344
+ case "array": {
345
+ const result = this.temporary(value.type, value.span);
346
+ if (value.kind === "record") {
347
+ for (const [name, operand] of Object.entries(value.fields)) {
348
+ output.push({
349
+ kind: "assign",
350
+ root: result.id,
351
+ path: [{ kind: "field", name }],
352
+ value: this.expression(operand, initialized, output),
353
+ span: operand.span,
354
+ });
355
+ }
356
+ } else {
357
+ if (type.kind !== "array") {
358
+ reject("Invalid array construction.", value.span);
359
+ }
360
+ value.items.forEach((operand, index) => {
361
+ output.push({
362
+ kind: "assign",
363
+ root: result.id,
364
+ path: [
365
+ {
366
+ kind: "index",
367
+ value: {
368
+ kind: "constant",
369
+ type: "DINT",
370
+ value: {
371
+ kind: "integer",
372
+ value: String(type.lowerBound + index),
373
+ },
374
+ span: operand.span,
375
+ },
376
+ },
377
+ ],
378
+ value: this.expression(operand, initialized, output),
379
+ span: operand.span,
380
+ });
381
+ });
382
+ }
383
+ initialized.add(result.id);
384
+ return this.load(result, value.span);
385
+ }
386
+ case "constant": {
387
+ if (!aggregate(type)) {
388
+ return { ...common, kind: "constant", value: value.value };
389
+ }
390
+ const result = this.temporary(value.type, value.span);
391
+ output.push({
392
+ kind: "assign",
393
+ root: result.id,
394
+ value: { ...common, kind: "constant", value: value.value },
395
+ span: value.span,
396
+ });
397
+ initialized.add(result.id);
398
+ return this.load(result, value.span);
399
+ }
400
+ case "load": {
401
+ const source = this.scope.get(value.place.root);
402
+ const checked = placeType(
403
+ value.place,
404
+ this.declarations.types,
405
+ this.scope,
406
+ this.ranges,
407
+ );
408
+ if (!source || checked.issue || checked.type !== value.type) {
409
+ reject(checked.issue ?? "Invalid PLC load.", value.span);
410
+ }
411
+ if (aggregate(type) && !allowAggregateLoad) {
412
+ reject(
413
+ "Aggregate loads require explicit copy or a readonly value argument.",
414
+ value.span,
415
+ );
416
+ }
417
+ if (source.storage === "local" && !initialized.has(source.id)) {
418
+ reject("Local read before initialization.", value.span);
419
+ }
420
+ // The virtual .out view is not a vendor record value. Snapshot its
421
+ // declared fields, rather than copying the whole FB instance.
422
+ const first = value.place.path[0];
423
+ if (
424
+ source.storage === "instance" &&
425
+ value.place.path.length === 1 &&
426
+ first?.kind === "field" &&
427
+ first.name === "out" &&
428
+ type.kind === "record"
429
+ ) {
430
+ const result = this.temporary(value.type, value.span);
431
+ for (const field of type.fields) {
432
+ const selected: Expression = {
433
+ kind: "load",
434
+ type: field.type,
435
+ place: {
436
+ root: source.id,
437
+ path: [
438
+ ...value.place.path,
439
+ { kind: "field", name: field.name },
440
+ ],
441
+ },
442
+ span: value.span,
443
+ };
444
+ const captured = this.expression(selected, initialized, output, {
445
+ allowAggregateLoad: true,
446
+ });
447
+ output.push({
448
+ kind: "assign",
449
+ root: result.id,
450
+ path: [{ kind: "field", name: field.name }],
451
+ value: captured,
452
+ span: value.span,
453
+ });
454
+ }
455
+ initialized.add(result.id);
456
+ return this.load(result, value.span);
457
+ }
458
+ const path = this.normalizePath(value.place, initialized, output);
459
+ if (source.storage === "constant" && source.initial && !path.length) {
460
+ return { ...common, kind: "constant", value: source.initial };
461
+ }
462
+ // Capture now, before a later operand can invoke an effectful helper.
463
+ const result = this.temporary(value.type, value.span);
464
+ output.push({
465
+ kind: "assign",
466
+ root: result.id,
467
+ value: {
468
+ ...common,
469
+ kind: "load",
470
+ root: source.id,
471
+ ...(path.length && { path }),
472
+ },
473
+ span: value.span,
474
+ });
475
+ const bound = interval(
476
+ value,
477
+ this.declarations.types,
478
+ this.scope,
479
+ this.ranges,
480
+ );
481
+ if (bound) {
482
+ this.ranges.set(result.id, bound);
483
+ }
484
+ initialized.add(result.id);
485
+ return this.load(result, value.span);
486
+ }
487
+ case "unary": {
488
+ const operand = this.expression(value.operand, initialized, output);
489
+ const constant = fold(value, this.scope, this.declarations.types);
490
+ return constant
491
+ ? { ...common, kind: "constant", value: constant }
492
+ : { ...common, kind: "unary", operator: value.operator, operand };
493
+ }
494
+ case "convert": {
495
+ const operand = this.expression(value.operand, initialized, output);
496
+ if (value.type === value.operand.type) {
497
+ return operand;
498
+ }
499
+ const constant = fold(value, this.scope, this.declarations.types);
500
+ return constant
501
+ ? { ...common, kind: "constant", value: constant }
502
+ : { ...common, kind: "convert", operand, policy: value.policy };
503
+ }
504
+ case "binary": {
505
+ const left = this.expression(value.left, initialized, output);
506
+ if (value.operator === "and" || value.operator === "or") {
507
+ const result = this.temporary("BOOL", value.span);
508
+ const right = this.branchOperand(value.right, initialized);
509
+ output.push(
510
+ ...lowerLogical({
511
+ operator: value.operator,
512
+ result: { root: result.id, type: result.type },
513
+ left,
514
+ right,
515
+ span: value.span,
516
+ }),
517
+ );
518
+ initialized.add(result.id);
519
+ return this.load(result, value.span);
520
+ }
521
+ const right = this.expression(value.right, initialized, output);
522
+ const constant = fold(value, this.scope, this.declarations.types);
523
+ if (constant) {
524
+ return { ...common, kind: "constant", value: constant };
525
+ }
526
+ return {
527
+ ...common,
528
+ kind: "binary",
529
+ operator: value.operator,
530
+ left,
531
+ right,
532
+ ...(value.policy && { policy: value.policy }),
533
+ };
534
+ }
535
+ }
536
+ }
537
+
538
+ /** An operand that runs only on one branch, so what it initializes stays there. */
539
+ private branchOperand(
540
+ operand: Expression,
541
+ initialized: Set<string>,
542
+ ): BranchOperand {
543
+ const statements: CoreStatement[] = [];
544
+ const value = this.expression(operand, new Set(initialized), statements);
545
+ return { statements, value };
546
+ }
547
+
548
+ private normalizePath(
549
+ place: Place,
550
+ initialized: Set<string>,
551
+ output: CoreStatement[],
552
+ ): CorePath {
553
+ // An index is evaluated and captured once, before later arguments can change
554
+ // its source storage. The resulting path denotes that selected cell.
555
+ return place.path.map((segment) =>
556
+ segment.kind === "field"
557
+ ? segment
558
+ : {
559
+ kind: "index",
560
+ value: this.expression(segment.value, initialized, output),
561
+ },
562
+ );
563
+ }
564
+
565
+ private destination(
566
+ place: Place,
567
+ type: string,
568
+ initialized: Set<string>,
569
+ span: SourceSpan,
570
+ ): Variable {
571
+ const target = this.scope.get(place.root);
572
+ const initializing =
573
+ target?.storage === "local" &&
574
+ !initialized.has(place.root) &&
575
+ !place.path.length;
576
+ const checked = placeType(
577
+ place,
578
+ this.declarations.types,
579
+ this.scope,
580
+ this.ranges,
581
+ !initializing,
582
+ );
583
+ if (
584
+ !target ||
585
+ checked.issue ||
586
+ checked.type !== type ||
587
+ this.counters.has(place.root)
588
+ ) {
589
+ reject(checked.issue ?? "Invalid assignment destination.", span);
590
+ }
591
+ if (
592
+ place.path.length &&
593
+ target.storage === "local" &&
594
+ !initialized.has(target.id)
595
+ ) {
596
+ reject("Initialize the whole aggregate before assigning fields.", span);
597
+ }
598
+ return target;
599
+ }
600
+
601
+ private instanceIndex(
602
+ instance: string,
603
+ index: Expression | undefined,
604
+ initialized: Set<string>,
605
+ output: CoreStatement[],
606
+ span: SourceSpan,
607
+ ): CoreExpression | undefined {
608
+ if (!index) {
609
+ return undefined;
610
+ }
611
+ const checked = placeType(
612
+ { root: instance, path: [{ kind: "index", value: index }] },
613
+ this.declarations.types,
614
+ this.scope,
615
+ this.ranges,
616
+ );
617
+ if (checked.issue) {
618
+ reject(checked.issue, span);
619
+ }
620
+ return this.expression(index, initialized, output);
621
+ }
622
+
623
+ private blockUpdate(
624
+ item: Extract<Statement, { kind: "blockUpdate" }>,
625
+ initialized: Set<string>,
626
+ output: CoreStatement[],
627
+ ): void {
628
+ const block = this.receiverBlock(item.instance);
629
+ const called = block && this.declarations.blocks.get(block);
630
+ if (!called) {
631
+ reject(
632
+ "Updates require a statically allocated block instance.",
633
+ item.span,
634
+ );
635
+ }
636
+ const index = this.instanceIndex(
637
+ item.instance,
638
+ item.index,
639
+ initialized,
640
+ output,
641
+ item.span,
642
+ );
643
+ // Input names are unique, so a matching count means every input appears exactly once.
644
+ const supplied = Object.entries(item.inputs).flatMap(([name, value]) => {
645
+ const input = called.inputs.find((port) => port.name === name);
646
+ return input ? [{ input, value }] : [];
647
+ });
648
+ if (
649
+ Object.keys(item.inputs).length !== called.inputs.length ||
650
+ supplied.length !== called.inputs.length
651
+ ) {
652
+ reject(
653
+ "Block update must supply every named input exactly once.",
654
+ item.span,
655
+ );
656
+ }
657
+ this.callees.add(called.id);
658
+ // Inputs evaluate in source property order.
659
+ const inputs = Object.fromEntries(
660
+ supplied.map(({ input, value }) => [
661
+ input.name,
662
+ this.argument(input, value, initialized, output),
663
+ ]),
664
+ );
665
+ output.push({
666
+ kind: "blockUpdate",
667
+ instance: item.instance,
668
+ ...(index && { index }),
669
+ inputs,
670
+ span: item.span,
671
+ });
672
+ }
673
+
674
+ private arguments(
675
+ parameters: readonly Variable[],
676
+ values: readonly Expression[],
677
+ initialized: Set<string>,
678
+ output: CoreStatement[],
679
+ ): CoreExpression[] {
680
+ return values.map((value, index) => {
681
+ const parameter = parameters[index];
682
+ if (!parameter) {
683
+ throw new Error(
684
+ "A call passes more arguments than its callee declares.",
685
+ );
686
+ }
687
+ return this.argument(parameter, value, initialized, output);
688
+ });
689
+ }
690
+
691
+ private argument(
692
+ input: Variable,
693
+ value: Expression,
694
+ initialized: Set<string>,
695
+ output: CoreStatement[],
696
+ ): CoreExpression {
697
+ if (value.type !== input.type) {
698
+ reject("Block input differs from its concrete PLC type.", value.span);
699
+ }
700
+ if (input.mode === "inOut" && value.kind === "borrow") {
701
+ return this.borrow(value, initialized, output);
702
+ }
703
+ if (input.mode === "inOut") {
704
+ if (this.declarations.types.get(value.type)?.kind === "block") {
705
+ reject("Pass a block instance by name.", value.span);
706
+ }
707
+ const temporary = this.temporary(value.type, value.span);
708
+ output.push({
709
+ kind: "assign",
710
+ root: temporary.id,
711
+ value: this.expression(value, initialized, output),
712
+ span: value.span,
713
+ });
714
+ initialized.add(temporary.id);
715
+ return {
716
+ kind: "borrow",
717
+ type: value.type,
718
+ place: { root: temporary.id, path: [] },
719
+ span: value.span,
720
+ };
721
+ }
722
+ if (value.kind === "borrow") {
723
+ reject(
724
+ "Readonly value inputs cannot receive borrowed references.",
725
+ value.span,
726
+ );
727
+ }
728
+ return this.expression(value, initialized, output, {
729
+ allowAggregateLoad: true,
730
+ });
731
+ }
732
+
733
+ private borrow(
734
+ value: Extract<Expression, { kind: "borrow" }>,
735
+ initialized: Set<string>,
736
+ output: CoreStatement[],
737
+ ): CoreExpression {
738
+ const block = this.declarations.types.get(value.type)?.kind === "block";
739
+ const root = this.scope.get(value.place.root);
740
+ const checked = placeType(
741
+ value.place,
742
+ this.declarations.types,
743
+ this.scope,
744
+ this.ranges,
745
+ !block,
746
+ );
747
+ if (
748
+ !root ||
749
+ checked.issue ||
750
+ checked.type !== value.type ||
751
+ (!block && !isValueType(value.type, this.declarations.types)) ||
752
+ this.counters.has(root.id) ||
753
+ (root.storage === "local" && !initialized.has(root.id))
754
+ ) {
755
+ reject(
756
+ checked.issue ??
757
+ "Borrow requires initialized mutable value storage of the exact type.",
758
+ value.span,
759
+ );
760
+ }
761
+ return {
762
+ kind: "borrow",
763
+ type: value.type,
764
+ place: {
765
+ root: value.place.root,
766
+ path: this.normalizePath(value.place, initialized, output),
767
+ },
768
+ span: value.span,
769
+ };
770
+ }
771
+
772
+ private body(
773
+ statements: readonly Statement[],
774
+ initialized: Set<string>,
775
+ ): BodyResult {
776
+ const output: CoreStatement[] = [];
777
+ const state = statements.reduce<FlowState>(
778
+ (reached, item) =>
779
+ reached.flow === "fallthrough"
780
+ ? this.statement(item, reached.initialized, output)
781
+ : reached,
782
+ { flow: "fallthrough", initialized },
783
+ );
784
+ return { body: output, ...state };
785
+ }
786
+
787
+ private statement(
788
+ item: Statement,
789
+ initialized: Set<string>,
790
+ output: CoreStatement[],
791
+ ): FlowState {
792
+ switch (item.kind) {
793
+ case "assign":
794
+ this.assign(item, initialized, output);
795
+ return { flow: "fallthrough", initialized };
796
+ case "blockUpdate":
797
+ this.blockUpdate(item, initialized, output);
798
+ return { flow: "fallthrough", initialized };
799
+ case "invoke":
800
+ this.invoke(item, initialized, output);
801
+ return { flow: "fallthrough", initialized };
802
+ case "if":
803
+ return this.ifStatement(item, initialized, output);
804
+ case "switch":
805
+ return this.switchStatement(item, initialized, output);
806
+ case "for":
807
+ this.forStatement(item, initialized, output);
808
+ return { flow: "fallthrough", initialized };
809
+ case "return": {
810
+ if (item.value?.type !== this.routine.result) {
811
+ reject("Return differs from the function signature.", item.span);
812
+ }
813
+ const value =
814
+ item.value && this.expression(item.value, initialized, output);
815
+ output.push({
816
+ kind: "return",
817
+ span: item.span,
818
+ ...(value && { value }),
819
+ });
820
+ return { flow: "return", initialized };
821
+ }
822
+ case "telemetry":
823
+ this.telemetry(item, initialized, output);
824
+ return { flow: "fallthrough", initialized };
825
+ case "break":
826
+ case "continue":
827
+ if (!this.counters.size) {
828
+ reject("Loop control appears outside a bounded loop.", item.span);
829
+ }
830
+ output.push({ kind: item.kind, span: item.span });
831
+ return { flow: "loop", initialized };
832
+ }
833
+ }
834
+
835
+ private assign(
836
+ item: Extract<Statement, { kind: "assign" }>,
837
+ initialized: Set<string>,
838
+ output: CoreStatement[],
839
+ ): void {
840
+ this.destination(item.destination, item.value.type, initialized, item.span);
841
+ const path = this.normalizePath(item.destination, initialized, output);
842
+ // A const is assigned once, so its initializer's range holds wherever it is read.
843
+ const bound =
844
+ !path.length &&
845
+ this.scope.get(item.destination.root)?.mutable === false &&
846
+ interval(item.value, this.declarations.types, this.scope, this.ranges);
847
+ const value = this.expression(item.value, initialized, output);
848
+ if (bound) {
849
+ this.ranges.set(item.destination.root, bound);
850
+ }
851
+ if (!path.length) {
852
+ initialized.add(item.destination.root);
853
+ }
854
+ output.push({
855
+ kind: "assign",
856
+ root: item.destination.root,
857
+ ...(path.length && { path }),
858
+ value,
859
+ span: item.span,
860
+ });
861
+ }
862
+
863
+ private invoke(
864
+ item: Extract<Statement, { kind: "invoke" }>,
865
+ initialized: Set<string>,
866
+ output: CoreStatement[],
867
+ ): void {
868
+ const called = this.verifyCall(
869
+ item.function,
870
+ item.arguments,
871
+ item.span,
872
+ item.instance,
873
+ );
874
+ if (item.destination) {
875
+ if (item.destination.path.length || !called.result) {
876
+ reject("Invalid helper destination.", item.span);
877
+ }
878
+ this.destination(item.destination, called.result, initialized, item.span);
879
+ }
880
+ const index =
881
+ item.instance &&
882
+ this.instanceIndex(
883
+ item.instance,
884
+ item.index,
885
+ initialized,
886
+ output,
887
+ item.span,
888
+ );
889
+ // Each argument snapshots its reads before the next argument can invoke
890
+ // a helper that mutates shared state.
891
+ const arguments_ = this.arguments(
892
+ called.parameters,
893
+ item.arguments,
894
+ initialized,
895
+ output,
896
+ );
897
+ output.push({
898
+ kind: "invoke",
899
+ function: item.function,
900
+ ...(item.instance && { instance: item.instance }),
901
+ ...(index && { index }),
902
+ arguments: arguments_,
903
+ span: item.span,
904
+ ...(item.destination && { destination: item.destination.root }),
905
+ });
906
+ if (item.destination) {
907
+ initialized.add(item.destination.root);
908
+ }
909
+ }
910
+
911
+ private ifStatement(
912
+ item: Extract<Statement, { kind: "if" }>,
913
+ initialized: Set<string>,
914
+ output: CoreStatement[],
915
+ ): FlowState {
916
+ if (item.condition.type !== "BOOL") {
917
+ reject("Conditions require BOOL.", item.span);
918
+ }
919
+ const condition = this.expression(item.condition, initialized, output);
920
+ const originalRanges = new Map(this.ranges);
921
+ const branch = (statements: readonly Statement[], truth: boolean) => {
922
+ this.ranges.clear();
923
+ for (const [root, range] of narrowRanges(
924
+ item.condition,
925
+ truth,
926
+ this.declarations.types,
927
+ this.scope,
928
+ originalRanges,
929
+ )) {
930
+ this.ranges.set(root, range);
931
+ }
932
+ try {
933
+ return this.body(statements, new Set(initialized));
934
+ } finally {
935
+ this.ranges.clear();
936
+ for (const [root, range] of originalRanges) {
937
+ this.ranges.set(root, range);
938
+ }
939
+ }
940
+ };
941
+ const yes = branch(item.then, true);
942
+ const no = branch(item.else, false);
943
+ output.push({
944
+ kind: "if",
945
+ condition,
946
+ // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
947
+ then: yes.body,
948
+ else: no.body,
949
+ span: item.span,
950
+ });
951
+ return join([yes, no], initialized);
952
+ }
953
+
954
+ private switchStatement(
955
+ item: Extract<Statement, { kind: "switch" }>,
956
+ initialized: Set<string>,
957
+ output: CoreStatement[],
958
+ ): FlowState {
959
+ const value = this.expression(item.value, initialized, output);
960
+ const type = lookup(this.declarations.types, item.value.type, "type");
961
+ const seen = new Set<string>();
962
+ const cases = item.cases.map((branch) => {
963
+ for (const constant of branch.values) {
964
+ if (!valueFits(constant, type, this.declarations.types)) {
965
+ reject("Invalid case constant.", item.span);
966
+ }
967
+ const key = JSON.stringify(constant);
968
+ if (seen.has(key)) {
969
+ reject("Duplicate case constant.", item.span);
970
+ }
971
+ seen.add(key);
972
+ }
973
+ return {
974
+ values: branch.values,
975
+ result: this.body(branch.body, new Set(initialized)),
976
+ };
977
+ });
978
+ const fallback = this.body(item.fallback, new Set(initialized));
979
+ output.push({
980
+ kind: "switch",
981
+ value,
982
+ cases: cases.map((branch) => ({
983
+ values: branch.values,
984
+ body: branch.result.body,
985
+ })),
986
+ fallback: fallback.body,
987
+ span: item.span,
988
+ });
989
+ return join(
990
+ [fallback, ...cases.map((branch) => branch.result)],
991
+ initialized,
992
+ );
993
+ }
994
+
995
+ private forStatement(
996
+ item: Extract<Statement, { kind: "for" }>,
997
+ initialized: Set<string>,
998
+ output: CoreStatement[],
999
+ ): void {
1000
+ const counter = this.scope.get(item.counter);
1001
+ const counterType = counter && this.declarations.types.get(counter.type);
1002
+ const storage =
1003
+ item.counterScope === "existing"
1004
+ ? ["local", "module", "field"]
1005
+ : ["local"];
1006
+ if (
1007
+ !counter ||
1008
+ !storage.includes(counter.storage) ||
1009
+ !counter.mutable ||
1010
+ counterType?.kind !== "integer" ||
1011
+ this.counters.has(counter.id) ||
1012
+ item.start.type !== counter.type ||
1013
+ item.limit.type !== counter.type ||
1014
+ !canonicalInteger.test(item.step) ||
1015
+ item.step === "0"
1016
+ ) {
1017
+ reject("Invalid bounded loop.", item.span);
1018
+ }
1019
+ const start = fold(item.start, this.scope, this.declarations.types);
1020
+ const limit = fold(item.limit, this.scope, this.declarations.types);
1021
+ const startRange = interval(
1022
+ item.start,
1023
+ this.declarations.types,
1024
+ this.scope,
1025
+ this.ranges,
1026
+ );
1027
+ const limitRange = interval(
1028
+ item.limit,
1029
+ this.declarations.types,
1030
+ this.scope,
1031
+ this.ranges,
1032
+ );
1033
+ if (!startRange || !limitRange) {
1034
+ reject("Loop bounds require finite integer ranges.", item.span);
1035
+ }
1036
+ const step = BigInt(item.step);
1037
+ const { first, last, count, range, terminal } = loopBounds(
1038
+ startRange,
1039
+ limitRange,
1040
+ step,
1041
+ item.exclusive,
1042
+ );
1043
+ const dynamic = start?.kind !== "integer" || limit?.kind !== "integer";
1044
+ if (count > maxLoopIterations || Number(count) !== item.maxIterations) {
1045
+ reject("Loop iteration proof differs from its bounds.", item.span);
1046
+ }
1047
+ if (item.counterScope === "existing") {
1048
+ if (count > 0n && !admits(integerRange(counterType), terminal)) {
1049
+ reject(
1050
+ "The existing loop counter overflows on termination.",
1051
+ item.span,
1052
+ );
1053
+ }
1054
+ }
1055
+ const evaluatedStart = this.expression(item.start, initialized, output);
1056
+ const evaluatedLimit = this.expression(item.limit, initialized, output);
1057
+ initialized.add(counter.id);
1058
+ this.counters.add(counter.id);
1059
+ this.ranges.set(counter.id, range);
1060
+ const nested = this.body(item.body, new Set(initialized));
1061
+ this.counters.delete(counter.id);
1062
+ this.ranges.delete(counter.id);
1063
+ if (item.counterScope !== "existing") {
1064
+ initialized.delete(counter.id);
1065
+ }
1066
+ output.push({
1067
+ kind: "for",
1068
+ counter: counter.id,
1069
+ ...(item.counterScope && { counterScope: item.counterScope }),
1070
+ start: { kind: "integer", value: String(first) },
1071
+ limit: { kind: "integer", value: String(last) },
1072
+ ...(dynamic && {
1073
+ dynamic: {
1074
+ start: evaluatedStart,
1075
+ limit: evaluatedLimit,
1076
+ ...(item.exclusive && { exclusive: item.exclusive }),
1077
+ },
1078
+ }),
1079
+ step: item.step,
1080
+ maxIterations: item.maxIterations,
1081
+ body: nested.body,
1082
+ span: item.span,
1083
+ });
1084
+ }
1085
+
1086
+ private telemetry(
1087
+ item: Extract<Statement, { kind: "telemetry" }>,
1088
+ initialized: Set<string>,
1089
+ output: CoreStatement[],
1090
+ ): void {
1091
+ const evaluate = (value: Expression) =>
1092
+ this.expression(value, initialized, output);
1093
+ const { record } = item;
1094
+ output.push({
1095
+ kind: "telemetry",
1096
+ record:
1097
+ record.kind === "exception"
1098
+ ? { kind: "exception", code: evaluate(record.code) }
1099
+ : record,
1100
+ properties: item.properties.map(({ name, value, length }) => {
1101
+ if (!length) {
1102
+ return { name, value: evaluate(value) };
1103
+ }
1104
+ if (value.kind !== "borrow") {
1105
+ reject("Telemetry text reads a byte array in place.", value.span);
1106
+ }
1107
+ return {
1108
+ name,
1109
+ value: this.borrow(value, initialized, output),
1110
+ length: evaluate(length),
1111
+ };
1112
+ }),
1113
+ span: item.span,
1114
+ });
1115
+ }
1116
+ }