@tsplc/compiler 0.2.17 → 0.2.18

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
package/ir/routine.ts DELETED
@@ -1,859 +0,0 @@
1
- import type { SourceSpan } from "./diagnostics.ts";
2
- import type {
3
- Variable,
4
- Expression,
5
- Statement,
6
- Place,
7
- PlcFunction,
8
- FunctionBlock,
9
- } from "./model.ts";
10
- import type {
11
- CoreExpression,
12
- CoreStatement,
13
- CorePath,
14
- CoreFunction,
15
- CoreFunctionBlock,
16
- } from "./core-model.ts";
17
- import {
18
- fold,
19
- interval,
20
- loopBounds,
21
- narrowRanges,
22
- valueRange,
23
- type IntegerInterval,
24
- } from "./scalars.ts";
25
- import { instancedBlock, integerRange } from "./types.ts";
26
- import { aggregate, expressionIssue, placeType, valueFits } from "./aggregates.ts";
27
- import { reject } from "./normalization-error.ts";
28
- import type { ModuleDeclarations } from "./declarations.ts";
29
-
30
- type Flow = "fallthrough" | "return" | "loop" | "mixed";
31
- interface BodyResult {
32
- body: CoreStatement[];
33
- initialized: Set<string>;
34
- flow: Flow;
35
- }
36
-
37
- // Only paths that reach the next statement participate in a join. A local is
38
- // definitely initialized when every such path initialized it; branches that
39
- // return or leave the loop do not constrain it.
40
- function join(
41
- branches: readonly BodyResult[],
42
- initialized: Set<string>,
43
- ): { flow: Flow; initialized: Set<string> } {
44
- const falling = branches.filter((branch) => branch.flow === "fallthrough");
45
- if (falling.length)
46
- return {
47
- flow: "fallthrough",
48
- initialized: new Set(
49
- [...falling[0]!.initialized].filter((id) =>
50
- falling.every((branch) => branch.initialized.has(id)),
51
- ),
52
- ),
53
- };
54
- const flow = branches[0]!.flow;
55
- return { flow: branches.every((branch) => branch.flow === flow) ? flow : "mixed", initialized };
56
- }
57
-
58
- // All mutable lowering state belongs to one invocation of one authored routine.
59
- // sourceScope admits authored places; scope additionally contains captured temps.
60
- export class RoutineNormalizer {
61
- private readonly fn: PlcFunction;
62
-
63
- private readonly block: FunctionBlock | undefined;
64
- private readonly owner: FunctionBlock | undefined;
65
-
66
- private readonly scope: Map<string, Variable>;
67
-
68
- private readonly sourceScope: Map<string, Variable>;
69
-
70
- private readonly locals: Variable[];
71
-
72
- private readonly ranges = new Map<string, IntegerInterval>();
73
-
74
- private readonly counters = new Set<string>();
75
-
76
- private readonly callees = new Set<string>();
77
-
78
- private temporaryCount = 0;
79
-
80
- constructor(
81
- routine: PlcFunction | FunctionBlock,
82
- private readonly declarations: ModuleDeclarations,
83
- ) {
84
- this.block = "inputs" in routine ? routine : undefined;
85
- this.owner =
86
- this.block ??
87
- ("owner" in routine && routine.owner
88
- ? declarations.blocks.get(routine.owner.block)
89
- : undefined);
90
- const parameters = "parameters" in routine ? routine.parameters : routine.inputs;
91
- this.fn = {
92
- id: routine.id,
93
- name: routine.name,
94
- ...("owner" in routine && routine.owner && { owner: routine.owner }),
95
- ...("origin" in routine && routine.origin && { origin: routine.origin }),
96
- parameters,
97
- locals: routine.locals,
98
- body: routine.body,
99
- span: routine.span,
100
- ...(routine.result && { result: routine.result }),
101
- };
102
- this.scope = new Map(declarations.globals);
103
- for (const item of [
104
- ...parameters,
105
- ...(this.owner ? [...this.owner.state, ...this.owner.outputs] : []),
106
- ...routine.locals,
107
- ])
108
- this.scope.set(item.id, item);
109
- this.sourceScope = new Map(this.scope);
110
- this.locals = [...routine.locals];
111
- }
112
-
113
- normalize(): { routine: CoreFunction | CoreFunctionBlock; callees: ReadonlySet<string> } {
114
- if (this.block?.standard)
115
- return { routine: { ...this.block, body: [] }, callees: this.callees };
116
- const normalized = this.body(this.fn.body, new Set(this.fn.parameters.map((item) => item.id)));
117
- if (this.fn.result && normalized.flow !== "return")
118
- reject("A typed helper must return on every path.", this.fn.span);
119
- const routine = this.block
120
- ? { ...this.block, locals: this.locals, body: normalized.body }
121
- : { ...this.fn, locals: this.locals, body: normalized.body };
122
- return { routine, callees: this.callees };
123
- }
124
-
125
- private temporary(type: string, span: SourceSpan): Variable {
126
- let id: string;
127
- do {
128
- id = `${this.fn.id}:temporary:${this.temporaryCount++}`;
129
- } while (this.declarations.hasId(id));
130
- this.declarations.claimId(id);
131
- const item: Variable = {
132
- id,
133
- name: `temporary_${this.temporaryCount}`,
134
- type,
135
- storage: "local",
136
- mutable: true,
137
- retain: false,
138
- span,
139
- };
140
- this.scope.set(id, item);
141
- this.locals.push(item);
142
- return item;
143
- }
144
-
145
- private load(variable: Variable, span: SourceSpan): CoreExpression {
146
- return { kind: "load", root: variable.id, type: variable.type, span };
147
- }
148
-
149
- private verifyCall(
150
- id: string,
151
- arguments_: readonly Expression[],
152
- span: SourceSpan,
153
- instance?: string,
154
- ): PlcFunction {
155
- const called = this.declarations.signatures.get(id);
156
- if (!called || called.parameters.length !== arguments_.length)
157
- reject("Unknown helper or wrong argument count.", span);
158
- if (called.owner) {
159
- if (instance) {
160
- const variable = this.sourceScope.get(instance);
161
- const type = variable && instancedBlock(variable.type, this.declarations.types);
162
- if (
163
- (variable?.storage !== "instance" && variable?.mode !== "inOut") ||
164
- type?.block !== called.owner.block
165
- )
166
- reject("Method calls require a matching static block instance.", span);
167
- } else if (this.owner?.id !== called.owner.block)
168
- reject("An implicit method call requires its owning block scope.", span);
169
- if (called.owner.access !== "public" && this.owner?.id !== called.owner.block)
170
- reject("Private and protected methods require their owning block scope.", span);
171
- } else if (instance) reject("Ordinary functions cannot have an instance receiver.", span);
172
- this.callees.add(id);
173
- arguments_.forEach((argument, index) => {
174
- if (argument.type !== called.parameters[index]?.type)
175
- reject("Helper argument has the wrong PLC type.", argument.span);
176
- });
177
- return called;
178
- }
179
-
180
- private expression(
181
- value: Expression,
182
- initialized: Set<string>,
183
- output: CoreStatement[],
184
- allowAggregateLoad = false,
185
- ): CoreExpression {
186
- const type = this.declarations.types.get(value.type);
187
- if (!type || !this.declarations.isValueType(value.type))
188
- reject("Unknown or non-value expression type.", value.span);
189
- if (value.kind === "borrow")
190
- reject("Borrowed places are only valid in block update arguments.", value.span);
191
- const common = { type: value.type, span: value.span };
192
- if (value.kind === "length") {
193
- const array = this.declarations.types.get(value.operand.type);
194
- if (array?.kind !== "array" || value.type !== "DINT")
195
- reject("Length requires a fixed array and DINT result.", value.span);
196
- if (value.operand.kind === "load") {
197
- const source = this.sourceScope.get(value.operand.place.root),
198
- checked = placeType(
199
- value.operand.place,
200
- this.declarations.types,
201
- this.sourceScope,
202
- this.ranges,
203
- );
204
- if (
205
- !source ||
206
- checked.issue ||
207
- checked.type !== value.operand.type ||
208
- (source.storage === "local" && !initialized.has(source.id))
209
- )
210
- reject(checked.issue ?? "Invalid array receiver.", value.span);
211
- this.normalizePath(value.operand.place, initialized, output);
212
- } else this.expression(value.operand, initialized, output, true);
213
- return {
214
- ...common,
215
- kind: "constant",
216
- value: { kind: "integer", value: String(array.length) },
217
- };
218
- }
219
- if (value.kind === "conditional") {
220
- if (
221
- value.condition.type !== "BOOL" ||
222
- value.then.type !== value.type ||
223
- value.else.type !== value.type
224
- )
225
- reject("Invalid conditional types.", value.span);
226
- const condition = this.expression(value.condition, initialized, output),
227
- result = this.temporary(value.type, value.span);
228
- const branch = (operand: Expression): CoreStatement[] => {
229
- const statements: CoreStatement[] = [];
230
- const evaluated = this.expression(operand, new Set(initialized), statements);
231
- statements.push({ kind: "assign", root: result.id, value: evaluated, span: value.span });
232
- return statements;
233
- };
234
- output.push({
235
- kind: "if",
236
- condition,
237
- // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
238
- then: branch(value.then),
239
- else: branch(value.else),
240
- span: value.span,
241
- });
242
- initialized.add(result.id);
243
- return this.load(result, value.span);
244
- }
245
- if (value.kind === "call") {
246
- const called = this.verifyCall(value.function, value.arguments, value.span, value.instance);
247
- if (called.result !== value.type)
248
- reject("Expression call requires a matching result type.", value.span);
249
- const index =
250
- value.instance &&
251
- this.instanceIndex(value.instance, value.index, initialized, output, value.span);
252
- const arguments_ = this.arguments(called.parameters, value.arguments, initialized, output);
253
- const result = this.temporary(value.type, value.span);
254
- output.push({
255
- kind: "invoke",
256
- function: value.function,
257
- ...(value.instance && { instance: value.instance }),
258
- ...(index && { index }),
259
- arguments: arguments_,
260
- destination: result.id,
261
- span: value.span,
262
- });
263
- initialized.add(result.id);
264
- return this.load(result, value.span);
265
- }
266
- const issue = expressionIssue(value, this.declarations.types, this.scope, this.ranges);
267
- if (issue) reject(issue, value.span);
268
- switch (value.kind) {
269
- case "copy":
270
- return this.expression(value.operand, initialized, output, true);
271
- case "record":
272
- case "array": {
273
- const result = this.temporary(value.type, value.span);
274
- if (value.kind === "record") {
275
- for (const [name, operand] of Object.entries(value.fields))
276
- output.push({
277
- kind: "assign",
278
- root: result.id,
279
- path: [{ kind: "field", name }],
280
- value: this.expression(operand, initialized, output),
281
- span: operand.span,
282
- });
283
- } else {
284
- const array = this.declarations.types.get(value.type)!;
285
- if (array.kind !== "array") reject("Invalid array construction.", value.span);
286
- value.items.forEach((operand, index) => {
287
- output.push({
288
- kind: "assign",
289
- root: result.id,
290
- path: [
291
- {
292
- kind: "index",
293
- value: {
294
- kind: "constant",
295
- type: "DINT",
296
- value: { kind: "integer", value: String(array.lowerBound + index) },
297
- span: operand.span,
298
- },
299
- },
300
- ],
301
- value: this.expression(operand, initialized, output),
302
- span: operand.span,
303
- });
304
- });
305
- }
306
- initialized.add(result.id);
307
- return this.load(result, value.span);
308
- }
309
- case "constant": {
310
- if (!aggregate(type)) return { ...common, kind: "constant", value: value.value };
311
- const result = this.temporary(value.type, value.span);
312
- output.push({
313
- kind: "assign",
314
- root: result.id,
315
- value: { ...common, kind: "constant", value: value.value },
316
- span: value.span,
317
- });
318
- initialized.add(result.id);
319
- return this.load(result, value.span);
320
- }
321
- case "load": {
322
- const source = this.sourceScope.get(value.place.root),
323
- checked = placeType(value.place, this.declarations.types, this.sourceScope, this.ranges);
324
- if (!source || checked.issue || checked.type !== value.type)
325
- reject(checked.issue ?? "Invalid PLC load.", value.span);
326
- if (aggregate(type) && !allowAggregateLoad)
327
- reject("Aggregate loads require explicit copy or a readonly value argument.", value.span);
328
- if (source.storage === "local" && !initialized.has(source.id))
329
- reject("Local read before initialization.", value.span);
330
- // The virtual .out view is not a vendor record value. Snapshot its
331
- // declared fields, rather than copying the whole FB instance.
332
- const first = value.place.path[0];
333
- if (
334
- source.storage === "instance" &&
335
- value.place.path.length === 1 &&
336
- first?.kind === "field" &&
337
- first.name === "out" &&
338
- type.kind === "record"
339
- ) {
340
- const result = this.temporary(value.type, value.span);
341
- for (const field of type.fields) {
342
- const selected: Expression = {
343
- kind: "load",
344
- type: field.type,
345
- place: {
346
- root: source.id,
347
- path: [...value.place.path, { kind: "field", name: field.name }],
348
- },
349
- span: value.span,
350
- };
351
- const captured = this.expression(selected, initialized, output, true);
352
- output.push({
353
- kind: "assign",
354
- root: result.id,
355
- path: [{ kind: "field", name: field.name }],
356
- value: captured,
357
- span: value.span,
358
- });
359
- }
360
- initialized.add(result.id);
361
- return this.load(result, value.span);
362
- }
363
- const path = this.normalizePath(value.place, initialized, output);
364
- if (source.storage === "constant" && source.initial && !path.length)
365
- return { ...common, kind: "constant", value: source.initial };
366
- // Capture now, before a later operand can invoke an effectful helper.
367
- const result = this.temporary(value.type, value.span);
368
- output.push({
369
- kind: "assign",
370
- root: result.id,
371
- value: { ...common, kind: "load", root: source.id, ...(path.length && { path }) },
372
- span: value.span,
373
- });
374
- const bound = interval(value, this.declarations.types, this.scope, this.ranges);
375
- if (bound) this.ranges.set(result.id, bound);
376
- initialized.add(result.id);
377
- return this.load(result, value.span);
378
- }
379
- case "unary": {
380
- const operand = this.expression(value.operand, initialized, output),
381
- constant = fold(value, this.scope, this.declarations.types);
382
- return constant
383
- ? { ...common, kind: "constant", value: constant }
384
- : { ...common, kind: "unary", operator: value.operator, operand };
385
- }
386
- case "convert": {
387
- const operand = this.expression(value.operand, initialized, output),
388
- constant = fold(value, this.scope, this.declarations.types);
389
- if (value.type === value.operand.type) return operand;
390
- return constant
391
- ? { ...common, kind: "constant", value: constant }
392
- : { ...common, kind: "convert", operand, policy: value.policy };
393
- }
394
- case "binary": {
395
- const left = this.expression(value.left, initialized, output);
396
- if (value.operator === "and" || value.operator === "or") {
397
- const result = this.temporary("BOOL", value.span),
398
- branch: CoreStatement[] = [];
399
- output.push({ kind: "assign", root: result.id, value: left, span: value.span });
400
- const right = this.expression(value.right, new Set(initialized), branch);
401
- branch.push({ kind: "assign", root: result.id, value: right, span: value.span });
402
- const condition: CoreExpression =
403
- value.operator === "and"
404
- ? this.load(result, value.span)
405
- : {
406
- kind: "unary",
407
- operator: "not",
408
- operand: this.load(result, value.span),
409
- type: "BOOL",
410
- span: value.span,
411
- };
412
- output.push({
413
- kind: "if",
414
- condition,
415
- // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
416
- then: branch,
417
- else: [],
418
- span: value.span,
419
- });
420
- initialized.add(result.id);
421
- return this.load(result, value.span);
422
- }
423
- const right = this.expression(value.right, initialized, output),
424
- constant = fold(value, this.scope, this.declarations.types);
425
- if (constant) return { ...common, kind: "constant", value: constant };
426
- return {
427
- ...common,
428
- kind: "binary",
429
- operator: value.operator,
430
- left,
431
- right,
432
- ...(value.policy && { policy: value.policy }),
433
- };
434
- }
435
- }
436
- }
437
-
438
- private normalizePath(place: Place, initialized: Set<string>, output: CoreStatement[]): CorePath {
439
- // An index is evaluated and captured once, before later arguments can change
440
- // its source storage. The resulting path denotes that selected cell.
441
- return place.path.map((segment) =>
442
- segment.kind === "field"
443
- ? segment
444
- : { kind: "index", value: this.expression(segment.value, initialized, output) },
445
- );
446
- }
447
-
448
- private destination(
449
- place: Place,
450
- type: string,
451
- initialized: Set<string>,
452
- span: SourceSpan,
453
- ): Variable {
454
- const target = this.sourceScope.get(place.root),
455
- initializing =
456
- target?.storage === "local" && !initialized.has(place.root) && !place.path.length;
457
- const checked = placeType(
458
- place,
459
- this.declarations.types,
460
- this.sourceScope,
461
- this.ranges,
462
- !initializing,
463
- );
464
- if (!target || checked.issue || checked.type !== type || this.counters.has(place.root))
465
- reject(checked.issue ?? "Invalid assignment destination.", span);
466
- if (place.path.length && target.storage === "local" && !initialized.has(target.id))
467
- reject("Initialize the whole aggregate before assigning fields.", span);
468
- return target;
469
- }
470
-
471
- private instanceIndex(
472
- instance: string,
473
- index: Expression | undefined,
474
- initialized: Set<string>,
475
- output: CoreStatement[],
476
- span: SourceSpan,
477
- ): CoreExpression | undefined {
478
- if (!index) return undefined;
479
- const checked = placeType(
480
- { root: instance, path: [{ kind: "index", value: index }] },
481
- this.declarations.types,
482
- this.sourceScope,
483
- this.ranges,
484
- );
485
- if (checked.issue) reject(checked.issue, span);
486
- return this.expression(index, initialized, output);
487
- }
488
-
489
- private blockUpdate(
490
- item: Extract<Statement, { kind: "blockUpdate" }>,
491
- initialized: Set<string>,
492
- output: CoreStatement[],
493
- ): void {
494
- const instance = this.sourceScope.get(item.instance),
495
- type = instance && instancedBlock(instance.type, this.declarations.types);
496
- const called = type && this.declarations.blocks.get(type.block);
497
- if ((instance?.storage !== "instance" && instance?.mode !== "inOut") || !called)
498
- reject("Updates require a statically allocated block instance.", item.span);
499
- const index = this.instanceIndex(item.instance, item.index, initialized, output, item.span);
500
- const keys = Object.keys(item.inputs);
501
- if (
502
- keys.length !== called.inputs.length ||
503
- called.inputs.some((input) => !Object.hasOwn(item.inputs, input.name))
504
- )
505
- reject("Block update must supply every named input exactly once.", item.span);
506
- this.callees.add(called.id);
507
- const arguments_ = this.arguments(
508
- keys.map((name) => called.inputs.find((input) => input.name === name)!),
509
- keys.map((name) => item.inputs[name]!),
510
- initialized,
511
- output,
512
- );
513
- const inputs = Object.fromEntries(keys.map((name, index) => [name, arguments_[index]!]));
514
- output.push({
515
- kind: "blockUpdate",
516
- instance: instance.id,
517
- ...(index && { index }),
518
- inputs,
519
- span: item.span,
520
- });
521
- }
522
-
523
- private arguments(
524
- parameters: readonly Variable[],
525
- values: readonly Expression[],
526
- initialized: Set<string>,
527
- output: CoreStatement[],
528
- ): CoreExpression[] {
529
- const arguments_: CoreExpression[] = [];
530
- for (const [index, value] of values.entries()) {
531
- const input = parameters[index]!;
532
- if (value.type !== input.type)
533
- reject("Block input differs from its concrete PLC type.", value.span);
534
- const block = this.declarations.types.get(value.type)?.kind === "block";
535
- if (input.mode === "inOut" && value.kind !== "borrow") {
536
- // A value with no writable address reaches the callee through a temporary.
537
- if (block) reject("Pass a block instance by name.", value.span);
538
- const temporary = this.temporary(value.type, value.span);
539
- output.push({
540
- kind: "assign",
541
- root: temporary.id,
542
- value: this.expression(value, initialized, output),
543
- span: value.span,
544
- });
545
- initialized.add(temporary.id);
546
- arguments_.push({
547
- kind: "borrow",
548
- type: value.type,
549
- place: { root: temporary.id, path: [] },
550
- span: value.span,
551
- });
552
- } else if (input.mode === "inOut" && value.kind === "borrow") {
553
- arguments_.push(this.borrow(value, initialized, output));
554
- } else {
555
- if (value.kind === "borrow")
556
- reject("Readonly value inputs cannot receive borrowed references.", value.span);
557
- arguments_.push(this.expression(value, initialized, output, true));
558
- }
559
- }
560
- return arguments_;
561
- }
562
-
563
- private borrow(
564
- value: Extract<Expression, { kind: "borrow" }>,
565
- initialized: Set<string>,
566
- output: CoreStatement[],
567
- ): CoreExpression {
568
- const block = this.declarations.types.get(value.type)?.kind === "block";
569
- const root = this.sourceScope.get(value.place.root),
570
- checked = placeType(
571
- value.place,
572
- this.declarations.types,
573
- this.sourceScope,
574
- this.ranges,
575
- !block,
576
- );
577
- if (
578
- !root ||
579
- checked.issue ||
580
- checked.type !== value.type ||
581
- (!block && !this.declarations.isValueType(value.type)) ||
582
- this.counters.has(root.id) ||
583
- (root.storage === "local" && !initialized.has(root.id))
584
- )
585
- reject(
586
- checked.issue ?? "Borrow requires initialized mutable value storage of the exact type.",
587
- value.span,
588
- );
589
- return {
590
- kind: "borrow",
591
- type: value.type,
592
- place: {
593
- root: value.place.root,
594
- path: this.normalizePath(value.place, initialized, output),
595
- },
596
- span: value.span,
597
- };
598
- }
599
-
600
- private body(
601
- statements: readonly Statement[],
602
- initialized: Set<string>,
603
- inLoop = false,
604
- ): BodyResult {
605
- const output: CoreStatement[] = [];
606
- let flow: Flow = "fallthrough";
607
- for (const item of statements) {
608
- if (flow !== "fallthrough") break;
609
- switch (item.kind) {
610
- case "assign": {
611
- this.destination(item.destination, item.value.type, initialized, item.span);
612
- const path = this.normalizePath(item.destination, initialized, output);
613
- // A const is assigned once, so its initializer's range holds wherever it is read.
614
- const bound =
615
- !path.length &&
616
- this.scope.get(item.destination.root)?.mutable === false &&
617
- valueRange(
618
- item.value,
619
- this.declarations.types,
620
- this.scope,
621
- this.ranges,
622
- this.declarations.signatures,
623
- );
624
- const value = this.expression(item.value, initialized, output);
625
- if (bound) this.ranges.set(item.destination.root, bound);
626
- if (!path.length) initialized.add(item.destination.root);
627
- output.push({
628
- kind: "assign",
629
- root: item.destination.root,
630
- ...(path.length && { path }),
631
- value,
632
- span: item.span,
633
- });
634
- break;
635
- }
636
- case "blockUpdate": {
637
- this.blockUpdate(item, initialized, output);
638
- break;
639
- }
640
- case "invoke": {
641
- const called = this.verifyCall(item.function, item.arguments, item.span, item.instance);
642
- if (item.destination) {
643
- if (item.destination.path.length || !called.result)
644
- reject("Invalid helper destination.", item.span);
645
- this.destination(item.destination, called.result, initialized, item.span);
646
- }
647
- const index =
648
- item.instance &&
649
- this.instanceIndex(item.instance, item.index, initialized, output, item.span);
650
- // Each argument snapshots its reads before the next argument can invoke
651
- // a helper that mutates shared state.
652
- const arguments_ = this.arguments(called.parameters, item.arguments, initialized, output);
653
- output.push({
654
- kind: "invoke",
655
- function: item.function,
656
- ...(item.instance && { instance: item.instance }),
657
- ...(index && { index }),
658
- arguments: arguments_,
659
- span: item.span,
660
- ...(item.destination && { destination: item.destination.root }),
661
- });
662
- if (item.destination) initialized.add(item.destination.root);
663
- break;
664
- }
665
- case "if": {
666
- if (item.condition.type !== "BOOL") reject("Conditions require BOOL.", item.span);
667
- const condition = this.expression(item.condition, initialized, output);
668
- const originalRanges = new Map(this.ranges);
669
- const branch = (statements: readonly Statement[], truth: boolean) => {
670
- this.ranges.clear();
671
- for (const [root, range] of narrowRanges(
672
- item.condition,
673
- truth,
674
- this.declarations.types,
675
- this.sourceScope,
676
- originalRanges,
677
- ))
678
- this.ranges.set(root, range);
679
- try {
680
- return this.body(statements, new Set(initialized), inLoop);
681
- } finally {
682
- this.ranges.clear();
683
- for (const [root, range] of originalRanges) this.ranges.set(root, range);
684
- }
685
- };
686
- const yes = branch(item.then, true),
687
- no = branch(item.else, false);
688
- ({ flow, initialized } = join([yes, no], initialized));
689
- output.push({
690
- kind: "if",
691
- condition,
692
- // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
693
- then: yes.body,
694
- else: no.body,
695
- span: item.span,
696
- });
697
- break;
698
- }
699
- case "switch": {
700
- const value = this.expression(item.value, initialized, output),
701
- seen = new Set<string>();
702
- const branches = item.cases.map((branch) => {
703
- for (const constant of branch.values) {
704
- if (
705
- !valueFits(
706
- constant,
707
- this.declarations.types.get(item.value.type)!,
708
- this.declarations.types,
709
- )
710
- )
711
- reject("Invalid case constant.", item.span);
712
- const key = JSON.stringify(constant);
713
- if (seen.has(key)) reject("Duplicate case constant.", item.span);
714
- seen.add(key);
715
- }
716
- return {
717
- values: branch.values,
718
- result: this.body(branch.body, new Set(initialized), inLoop),
719
- };
720
- });
721
- const fallback = this.body(item.fallback, new Set(initialized), inLoop);
722
- ({ flow, initialized } = join(
723
- [...branches.map((branch) => branch.result), fallback],
724
- initialized,
725
- ));
726
- output.push({
727
- kind: "switch",
728
- value,
729
- cases: branches.map((branch) => ({ values: branch.values, body: branch.result.body })),
730
- fallback: fallback.body,
731
- span: item.span,
732
- });
733
- break;
734
- }
735
- case "for": {
736
- const counter = this.sourceScope.get(item.counter);
737
- const counterType = counter && this.declarations.types.get(counter.type);
738
- if (
739
- !counter ||
740
- !(item.counterScope === "existing"
741
- ? ["local", "module", "field"].includes(counter.storage)
742
- : counter.storage === "local") ||
743
- !counter.mutable ||
744
- counterType?.kind !== "integer" ||
745
- this.counters.has(counter.id) ||
746
- item.start.type !== counter.type ||
747
- item.limit.type !== counter.type ||
748
- !/^(-?[1-9][0-9]*)$/.test(item.step)
749
- )
750
- reject("Invalid bounded loop.", item.span);
751
- const start = fold(item.start, this.scope, this.declarations.types);
752
- const limit = fold(item.limit, this.scope, this.declarations.types);
753
- const startRange = interval(
754
- item.start,
755
- this.declarations.types,
756
- this.sourceScope,
757
- this.ranges,
758
- );
759
- const limitRange = interval(
760
- item.limit,
761
- this.declarations.types,
762
- this.sourceScope,
763
- this.ranges,
764
- );
765
- if (!startRange || !limitRange)
766
- reject("Loop bounds require finite integer ranges.", item.span);
767
- const step = BigInt(item.step);
768
- const proof = loopBounds(startRange, limitRange, step, item.exclusive);
769
- const dynamic = start?.kind !== "integer" || limit?.kind !== "integer";
770
- const first = proof.first,
771
- last = proof.last,
772
- count = proof.count;
773
- if (
774
- count > 1_000_000n ||
775
- Number(count) !== item.maxIterations ||
776
- !Number.isSafeInteger(item.maxIterations)
777
- )
778
- reject("Loop iteration proof differs from its bounds.", item.span);
779
- if (item.counterScope === "existing") {
780
- const terminal = dynamic
781
- ? (step > 0n ? proof.range[1] : proof.range[0]) + step
782
- : first + count * step;
783
- const [minimum, maximum] = integerRange(counterType);
784
- if (count > 0n && (terminal < minimum || terminal > maximum))
785
- reject("The existing loop counter overflows on termination.", item.span);
786
- }
787
- const evaluatedStart = this.expression(item.start, initialized, output);
788
- const evaluatedLimit = this.expression(item.limit, initialized, output);
789
- initialized.add(counter.id);
790
- this.counters.add(counter.id);
791
- this.ranges.set(counter.id, proof.range);
792
- const nested = this.body(item.body, new Set(initialized), true);
793
- this.counters.delete(counter.id);
794
- this.ranges.delete(counter.id);
795
- if (item.counterScope !== "existing") initialized.delete(counter.id);
796
- output.push({
797
- kind: "for",
798
- counter: counter.id,
799
- ...(item.counterScope && { counterScope: item.counterScope }),
800
- start: { kind: "integer", value: String(first) },
801
- limit: { kind: "integer", value: String(last) },
802
- ...(dynamic && {
803
- dynamic: {
804
- start: evaluatedStart,
805
- limit: evaluatedLimit,
806
- ...(item.exclusive && { exclusive: item.exclusive }),
807
- },
808
- }),
809
- step: item.step,
810
- maxIterations: item.maxIterations,
811
- body: nested.body,
812
- span: item.span,
813
- });
814
- break;
815
- }
816
- case "return": {
817
- if (item.value?.type !== this.fn.result)
818
- reject("Return differs from the function signature.", item.span);
819
- const value = item.value && this.expression(item.value, initialized, output);
820
- output.push({ kind: "return", span: item.span, ...(value && { value }) });
821
- flow = "return";
822
- break;
823
- }
824
- case "telemetry": {
825
- const evaluate = (value: Expression) => this.expression(value, initialized, output);
826
- const { record } = item;
827
- output.push({
828
- kind: "telemetry",
829
- record:
830
- record.kind === "exception"
831
- ? { kind: "exception", code: evaluate(record.code) }
832
- : record,
833
- properties: item.properties.map(({ name, value, length }) => {
834
- if (!length) return { name, value: evaluate(value) };
835
- if (value.kind !== "borrow")
836
- reject("Telemetry text reads a byte array in place.", value.span);
837
- return {
838
- name,
839
- value: this.borrow(value, initialized, output),
840
- length: evaluate(length),
841
- };
842
- }),
843
- span: item.span,
844
- });
845
- break;
846
- }
847
- case "break":
848
- case "continue":
849
- if (!inLoop) reject("Loop control appears outside a bounded loop.", item.span);
850
- output.push({ kind: item.kind, span: item.span });
851
- flow = "loop";
852
- break;
853
- default:
854
- reject("Unknown PLC statement.");
855
- }
856
- }
857
- return { body: output, initialized, flow };
858
- }
859
- }