@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/dist/ir.js CHANGED
@@ -1,63 +1,19 @@
1
- // packages/compiler/ir/diagnostics.ts
2
- function error(code, message, span) {
3
- return { origin: "plc", code, severity: "error", message, ...span && { span } };
4
- }
5
- function hasErrors(diagnostics) {
6
- return diagnostics.some((diagnostic) => diagnostic.severity === "error");
7
- }
8
- function formatDiagnostic(diagnostic, source) {
9
- const { span } = diagnostic;
10
- const location = span ? `${span.file}:${span.line}:${span.column}: ` : "";
11
- let result = `${location}${diagnostic.code}: ${diagnostic.message}`;
12
- if (source !== undefined && span) {
13
- const line = source.split(/\r?\n/)[span.line - 1];
14
- if (line !== undefined) {
15
- const width = Math.max(1, Math.min(span.end - span.start, line.length - span.column + 2));
16
- result += `
17
- ${span.line} | ${line}
18
- ${" ".repeat(String(span.line).length + 3 + span.column - 1)}${"^".repeat(width)}`;
19
- }
1
+ // packages/compiler/src/ir/core-model.ts
2
+ var nestedBodies = (item) => {
3
+ if (item.kind === "if") {
4
+ return [item.then, item.else];
20
5
  }
21
- for (const related of diagnostic.related ?? []) {
22
- result += `
23
- ${related.span.file}:${related.span.line}:${related.span.column}: ${related.message}`;
6
+ if (item.kind === "switch") {
7
+ return [...item.cases.map((branch) => branch.body), item.fallback];
24
8
  }
25
- for (const note of diagnostic.notes ?? [])
26
- result += `
27
- ${note}`;
28
- return result;
29
- }
30
- // packages/compiler/ir/types.ts
31
- var instancedBlock = (id, types) => {
32
- const type = types.get(id);
33
- const element = type?.kind === "array" ? types.get(type.element) : type;
34
- return element?.kind === "block" ? element : undefined;
9
+ if (item.kind === "for") {
10
+ return [item.body];
11
+ }
12
+ return [];
35
13
  };
36
- var primitiveTypes = [
37
- { id: "BOOL", kind: "bool" },
38
- ...[
39
- ["SINT", "USINT", "BYTE", 8],
40
- ["INT", "UINT", "WORD", 16],
41
- ["DINT", "UDINT", "DWORD", 32],
42
- ["LINT", "ULINT", "LWORD", 64]
43
- ].flatMap(([signed, unsigned, bitstring, bits]) => [
44
- { id: signed, kind: "integer", bits, signed: true },
45
- { id: unsigned, kind: "integer", bits, signed: false },
46
- { id: bitstring, kind: "bits", bits }
47
- ]),
48
- { id: "REAL", kind: "float", bits: 32 },
49
- { id: "LREAL", kind: "float", bits: 64 },
50
- { id: "TIME", kind: "duration" },
51
- { id: "DATE", kind: "calendar", domain: "date" },
52
- { id: "TIME_OF_DAY", kind: "calendar", domain: "timeOfDay" },
53
- { id: "DATE_AND_TIME", kind: "calendar", domain: "dateTime" }
54
- ];
55
- function integerRange(type) {
56
- const signed = type.kind === "integer" && type.signed;
57
- const limit = 1n << BigInt(type.bits - (signed ? 1 : 0));
58
- return signed ? [-limit, limit - 1n] : [0n, limit - 1n];
59
- }
60
- // packages/compiler/ir/model.ts
14
+ var verified = Symbol("verified core");
15
+
16
+ // packages/compiler/src/ir/model.ts
61
17
  var comparisonOperators = new Set([
62
18
  "equal",
63
19
  "notEqual",
@@ -66,7 +22,10 @@ var comparisonOperators = new Set([
66
22
  "greater",
67
23
  "greaterEqual"
68
24
  ]);
69
- var telemetryOperands = ({ record, properties }) => [
25
+ var telemetryOperands = ({
26
+ record,
27
+ properties
28
+ }) => [
70
29
  ...record.kind === "exception" ? [record.code] : [],
71
30
  ...properties.flatMap(({ value, length }) => length ? [value, length] : [value])
72
31
  ];
@@ -143,672 +102,891 @@ var standardBlocks = {
143
102
  outputs: [["on", "OUT", "BOOL"]]
144
103
  }
145
104
  };
146
- // packages/compiler/ir/core-model.ts
147
- var nestedBodies = (item) => {
148
- if (item.kind === "if")
149
- return [item.then, item.else];
150
- if (item.kind === "switch")
151
- return [...item.cases.map((branch) => branch.body), item.fallback];
152
- if (item.kind === "for")
153
- return [item.body];
154
- return [];
155
- };
156
- var verified = Symbol("verified core");
157
105
 
158
- // packages/compiler/ir/scalars.ts
159
- function integerType(type) {
160
- return type.kind === "integer" || type.kind === "bits";
161
- }
162
- function floatMaximum(type) {
163
- return type.bits === 32 ? Math.fround((2 - 2 ** -23) * 2 ** 127) : Number.MAX_VALUE;
106
+ // packages/compiler/src/ir/types.ts
107
+ import {
108
+ elementaryTypes,
109
+ integerRange as elementaryIntegerRange
110
+ } from "@tsplc/iec";
111
+ var instancedBlock = (id, types) => {
112
+ const type = types.get(id);
113
+ const element = type?.kind === "array" ? types.get(type.element) : type;
114
+ return element?.kind === "block" ? element : undefined;
115
+ };
116
+ var primitiveType = (type) => {
117
+ switch (type.family) {
118
+ case "bool":
119
+ return [{ id: type.name, kind: "bool" }];
120
+ case "integer":
121
+ return [
122
+ {
123
+ id: type.name,
124
+ kind: "integer",
125
+ bits: type.bits,
126
+ signed: type.signed
127
+ }
128
+ ];
129
+ case "bits":
130
+ return [{ id: type.name, kind: "bits", bits: type.bits }];
131
+ case "real":
132
+ return [{ id: type.name, kind: "float", bits: type.bits }];
133
+ case "duration":
134
+ return type.bits === 32 ? [{ id: type.name, kind: "duration" }] : [];
135
+ case "date":
136
+ case "timeOfDay":
137
+ case "dateTime":
138
+ return type.bits === 32 ? [{ id: type.name, kind: "calendar", domain: type.family }] : [];
139
+ case "char":
140
+ case "string":
141
+ return [];
142
+ }
143
+ };
144
+ var isIntegerValued = (type) => type.kind === "integer" || type.kind === "bits";
145
+ var integerKindRank = (type) => {
146
+ if (type.kind === "bits") {
147
+ return 2;
148
+ }
149
+ return type.signed ? 0 : 1;
150
+ };
151
+ var elementaryPrimitives = elementaryTypes.flatMap(primitiveType);
152
+ var primitiveTypes = [
153
+ ...elementaryPrimitives.filter((type) => type.kind === "bool"),
154
+ ...elementaryPrimitives.filter(isIntegerValued).sort((left, right) => left.bits - right.bits || integerKindRank(left) - integerKindRank(right)),
155
+ ...elementaryPrimitives.filter((type) => type.kind !== "bool" && !isIntegerValued(type))
156
+ ];
157
+ function integerRange(type) {
158
+ return elementaryIntegerRange({
159
+ bits: type.bits,
160
+ signed: type.kind === "integer" && type.signed
161
+ });
164
162
  }
165
- function saturateFloat(value, type) {
163
+
164
+ // packages/compiler/src/ir/numeric.ts
165
+ var lowest = (a, b) => a < b ? a : b;
166
+ var highest = (a, b) => a > b ? a : b;
167
+ var within = (inner, outer) => inner[0] >= outer[0] && inner[1] <= outer[1];
168
+ var admits = (interval, value) => interval[0] <= value && value <= interval[1];
169
+ var canonicalInteger = /^(?:0|-?[1-9][0-9]*)$/;
170
+ var integerType = (type) => type.kind === "integer" || type.kind === "bits";
171
+ var floatFormats = {
172
+ 32: { maximum: Math.fround((2 - 2 ** -23) * 2 ** 127), precision: 24 },
173
+ 64: { maximum: Number.MAX_VALUE, precision: 53 }
174
+ };
175
+ var floatMaximum = (type) => floatFormats[type.bits].maximum;
176
+ var exactIntegerLimit = (type) => 1n << BigInt(floatFormats[type.bits].precision);
177
+ var roundFloat = (value, type) => type.bits === 32 ? Math.fround(value) : value;
178
+ var saturateFloat = (value, type) => {
166
179
  const maximum = floatMaximum(type);
167
- const clipped = value < -maximum ? -maximum : value > maximum ? maximum : value;
168
- return type.bits === 32 ? Math.fround(clipped) : clipped;
169
- }
170
- function parseInteger(text) {
180
+ if (value < -maximum) {
181
+ return -maximum;
182
+ }
183
+ if (value > maximum) {
184
+ return maximum;
185
+ }
186
+ return roundFloat(value, type);
187
+ };
188
+ var exactDecimal = (text, scale) => {
189
+ const match = /^(-?\d+)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(text);
190
+ if (!match) {
191
+ return "malformed";
192
+ }
193
+ const [, whole, fraction = "", exponentText = "0"] = match;
194
+ const exponent = Number(exponentText) - fraction.length;
195
+ if (!Number.isSafeInteger(exponent) || Math.abs(exponent) > 400) {
196
+ return "exponent";
197
+ }
198
+ const digits = BigInt(whole + fraction) * scale;
199
+ if (exponent >= 0) {
200
+ return digits * 10n ** BigInt(exponent);
201
+ }
202
+ const divisor = 10n ** BigInt(-exponent);
203
+ return digits % divisor ? "fraction" : digits / divisor;
204
+ };
205
+ var integerLiteralIssues = {
206
+ malformed: "Expected an exact integer literal.",
207
+ exponent: "Integer literal exponent is out of range.",
208
+ fraction: "Integer literals cannot have a fractional part."
209
+ };
210
+ var parseInteger = (text) => {
171
211
  const clean = text.replaceAll("_", "").replace(/n$/, "");
172
- const negative = clean.startsWith("-");
173
- const unsigned = negative ? clean.slice(1) : clean;
174
- if (/^0[xob]/i.test(unsigned))
175
- return (negative ? -1n : 1n) * BigInt(unsigned);
176
- const match = /^(\d+)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(unsigned);
177
- if (!match)
178
- throw new Error("Expected an exact integer literal.");
179
- const fraction = match[2] ?? "";
180
- const exponent = Number(match[3] ?? 0) - fraction.length;
181
- if (!Number.isSafeInteger(exponent) || Math.abs(exponent) > 400)
182
- throw new Error("Integer literal exponent is out of range.");
183
- let value = BigInt(match[1] + fraction);
184
- if (exponent >= 0)
185
- value *= 10n ** BigInt(exponent);
186
- else {
187
- const divisor = 10n ** BigInt(-exponent);
188
- if (value % divisor)
189
- throw new Error("Integer literals cannot have a fractional part.");
190
- value /= divisor;
191
- }
192
- return negative ? -value : value;
193
- }
194
- function constantFits(value, type) {
195
- if (type.kind === "bool")
212
+ if (/^-?0[xob]/i.test(clean)) {
213
+ return clean.startsWith("-") ? -BigInt(clean.slice(1)) : BigInt(clean);
214
+ }
215
+ const value = exactDecimal(clean, 1n);
216
+ if (typeof value !== "bigint") {
217
+ throw new Error(integerLiteralIssues[value]);
218
+ }
219
+ return value;
220
+ };
221
+ var constantFits = (value, type) => {
222
+ if (type.kind === "bool") {
196
223
  return value.kind === "bool" && typeof value.value === "boolean";
224
+ }
197
225
  if (integerType(type)) {
198
- if (value.kind !== "integer" || !/^(?:0|-?[1-9][0-9]*)$/.test(value.value))
199
- return false;
200
- const [minimum, maximum] = integerRange(type), number = BigInt(value.value);
201
- return number >= minimum && number <= maximum;
226
+ return value.kind === "integer" && canonicalInteger.test(value.value) && admits(integerRange(type), BigInt(value.value));
227
+ }
228
+ if (type.kind === "float") {
229
+ return value.kind === "float" && Number.isFinite(value.value) && Object.is(roundFloat(value.value, type), value.value);
202
230
  }
203
- if (type.kind === "float")
204
- return value.kind === "float" && Number.isFinite(value.value) && (type.bits === 64 || Object.is(Math.fround(value.value), value.value));
205
231
  return false;
206
- }
207
- function canAssign(source, destination, value) {
232
+ };
233
+ var canAssign = (source, destination, value) => {
208
234
  if (value) {
209
- if (source.kind !== destination.kind || !constantFits(value, destination))
210
- return false;
211
- if (source.kind === "float" && destination.kind === "float" && source.bits > destination.bits && value.kind === "float")
212
- return Object.is(Math.fround(value.value), value.value);
213
- return true;
235
+ return source.kind === destination.kind && constantFits(value, destination);
214
236
  }
215
- if (source.id === destination.id)
237
+ if (source.id === destination.id) {
216
238
  return true;
239
+ }
217
240
  if (source.kind === "integer" && destination.kind === "integer") {
218
- const [fromMin, fromMax] = integerRange(source), [toMin, toMax] = integerRange(destination);
219
- return fromMin >= toMin && fromMax <= toMax;
241
+ return within(integerRange(source), integerRange(destination));
220
242
  }
221
243
  return source.kind === "float" && destination.kind === "float" && source.bits <= destination.bits;
244
+ };
245
+ var wrapsNatively = (expression) => expression.kind === "binary" && !expression.policy && (expression.operator === "add" || expression.operator === "subtract" || expression.operator === "multiply");
246
+ var applyIntegerPolicy = (value, type, policy) => {
247
+ if (policy === "saturate") {
248
+ const [minimum, maximum] = integerRange(type);
249
+ return highest(minimum, lowest(value, maximum));
250
+ }
251
+ return type.kind === "integer" && type.signed ? BigInt.asIntN(type.bits, value) : BigInt.asUintN(type.bits, value);
252
+ };
253
+
254
+ // packages/compiler/src/ir/domains.ts
255
+ import { elementaryType, integerRange as integerRange2 } from "@tsplc/iec";
256
+ var nanosecondsPerMillisecond = 1000000n;
257
+ var [, latestMillisecond] = integerRange2({
258
+ bits: elementaryType("TIME").bits,
259
+ signed: false
260
+ });
261
+ var [, latestSecond] = integerRange2({
262
+ bits: elementaryType("DATE_AND_TIME").bits,
263
+ signed: false
264
+ });
265
+ var latestDateTime = new Date(Number(latestSecond) * 1000).toISOString().slice(0, "YYYY-MM-DDTHH:mm:ss".length);
266
+ var latestDate = latestDateTime.slice(0, "YYYY-MM-DD".length);
267
+ var calendarZero = {
268
+ date: "1970-01-01",
269
+ timeOfDay: "00:00:00.000",
270
+ dateTime: "1970-01-01T00:00:00"
271
+ };
272
+ function durationLiteral(text, scaleNanoseconds) {
273
+ const clean = text.replaceAll("_", "").replace(/^(-?)\./, (_, sign) => `${sign}0.`);
274
+ const value = exactDecimal(clean, scaleNanoseconds);
275
+ return typeof value === "bigint" && validDuration(value) ? { kind: "duration", nanoseconds: String(value) } : undefined;
222
276
  }
223
- function fold(expression, variables, types) {
224
- if (expression.kind === "constant")
225
- return expression.value;
226
- if (expression.kind === "copy")
227
- return fold(expression.operand, variables, types);
228
- if (expression.kind === "length") {
229
- const type = types?.get(expression.operand.type);
230
- const receiver = expression.operand.kind === "load" ? variables.get(expression.operand.place.root) : undefined;
231
- const pure = expression.operand.kind === "load" && expression.operand.place.path.every((segment) => segment.kind === "field") && Boolean(receiver?.initial || receiver?.storage === "input" || receiver?.storage === "output");
232
- if (type?.kind === "array" && (pure || fold(expression.operand, variables, types)))
233
- return { kind: "integer", value: String(type.length) };
277
+ function validDuration(nanoseconds) {
278
+ return nanoseconds >= 0n && nanoseconds <= latestMillisecond * nanosecondsPerMillisecond && nanoseconds % nanosecondsPerMillisecond === 0n;
279
+ }
280
+ function validDate(text) {
281
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
282
+ if (!match) {
283
+ return false;
284
+ }
285
+ const year = Number(match[1]);
286
+ const month = Number(match[2]);
287
+ const day = Number(match[3]);
288
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
289
+ const length = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
290
+ return Boolean(length && day >= 1 && day <= length && text >= calendarZero.date && text <= latestDate);
291
+ }
292
+ function validClock(text, milliseconds) {
293
+ const match = (milliseconds ? /^(\d{2}):(\d{2}):(\d{2})\.(\d{3})$/ : /^(\d{2}):(\d{2}):(\d{2})$/).exec(text);
294
+ return Boolean(match && Number(match[1]) < 24 && Number(match[2]) < 60 && Number(match[3]) < 60);
295
+ }
296
+ function calendarLiteral(domain, text) {
297
+ if (domain === "date") {
298
+ return validDate(text) ? { kind: "calendar", value: text } : undefined;
299
+ }
300
+ if (domain === "timeOfDay") {
301
+ const canonical = /^\d{2}:\d{2}:\d{2}$/.test(text) ? `${text}.000` : text;
302
+ return validClock(canonical, true) ? { kind: "calendar", value: canonical } : undefined;
303
+ }
304
+ return text.length === 19 && text[10] === "T" && validDate(text.slice(0, 10)) && validClock(text.slice(11), false) && text <= latestDateTime ? { kind: "calendar", value: text } : undefined;
305
+ }
306
+ function domainConstantFits(value, type) {
307
+ if (type.kind === "duration") {
308
+ return value.kind === "duration" && canonicalInteger.test(value.nanoseconds) && validDuration(BigInt(value.nanoseconds));
309
+ }
310
+ if (type.kind === "calendar" && value.kind === "calendar") {
311
+ const parsed = calendarLiteral(type.domain, value.value);
312
+ return parsed?.kind === "calendar" && parsed.value === value.value;
313
+ }
314
+ return false;
315
+ }
316
+ function domainIssue(value, types) {
317
+ const type = types.get(value.type);
318
+ if (value.kind === "constant") {
319
+ return type && domainConstantFits(value.value, type) ? undefined : "Invalid TIME/calendar constant.";
320
+ }
321
+ if (value.kind === "load" || value.kind === "call" || value.kind === "conditional") {
234
322
  return;
235
323
  }
236
- if (expression.kind === "record") {
237
- const fields = Object.create(null);
238
- for (const [name, operand] of Object.entries(expression.fields)) {
239
- const value = fold(operand, variables, types);
240
- if (!value)
324
+ if (value.kind === "binary" && comparisonOperators.has(value.operator)) {
325
+ const left = types.get(value.left.type);
326
+ return value.type === "BOOL" && left && ["duration", "calendar"].includes(left.kind) && value.left.type === value.right.type ? undefined : "Time comparisons require matching domains.";
327
+ }
328
+ return "TIME and calendar domains permit storage, typed copies and comparisons; implicit numeric arithmetic is unsupported.";
329
+ }
330
+
331
+ // packages/compiler/src/ir/fold.ts
332
+ var fold = (expression, variables, types) => {
333
+ switch (expression.kind) {
334
+ case "constant":
335
+ return expression.value;
336
+ case "copy":
337
+ return fold(expression.operand, variables, types);
338
+ case "length":
339
+ return foldLength(expression, variables, types);
340
+ case "record":
341
+ return foldRecord(expression, variables, types);
342
+ case "array": {
343
+ const items = expression.items.map((item) => fold(item, variables, types));
344
+ return items.every((item) => item !== undefined) ? { kind: "array", items } : undefined;
345
+ }
346
+ case "load": {
347
+ if (expression.place.path.length) {
241
348
  return;
242
- fields[name] = value;
349
+ }
350
+ const variable = variables.get(expression.place.root);
351
+ return variable?.storage === "constant" ? variable.initial : undefined;
243
352
  }
244
- return { kind: "record", fields };
245
- }
246
- if (expression.kind === "array") {
247
- const items = expression.items.map((item) => fold(item, variables, types));
248
- return items.every((item) => item !== undefined) ? { kind: "array", items } : undefined;
353
+ case "convert":
354
+ return foldConvert(expression, fold(expression.operand, variables, types), types?.get(expression.type));
355
+ case "unary":
356
+ return foldUnary(expression, fold(expression.operand, variables, types), types?.get(expression.type));
357
+ case "binary": {
358
+ const left = fold(expression.left, variables, types);
359
+ const right = fold(expression.right, variables, types);
360
+ return left && right ? foldBinary(expression, left, right, types?.get(expression.type)) : undefined;
361
+ }
362
+ default:
363
+ return;
249
364
  }
250
- if (expression.kind === "load" && !expression.place.path.length) {
251
- const variable = variables.get(expression.place.root);
252
- return variable?.storage === "constant" ? variable.initial : undefined;
365
+ };
366
+ var foldLength = (expression, variables, types) => {
367
+ const type = types?.get(expression.operand.type);
368
+ const receiver = expression.operand.kind === "load" ? variables.get(expression.operand.place.root) : undefined;
369
+ const pure = expression.operand.kind === "load" && expression.operand.place.path.every((segment) => segment.kind === "field") && Boolean(receiver?.initial || receiver?.storage === "input" || receiver?.storage === "output");
370
+ if (type?.kind === "array" && (pure || fold(expression.operand, variables, types))) {
371
+ return { kind: "integer", value: String(type.length) };
253
372
  }
254
- if (expression.kind === "convert") {
255
- const value = fold(expression.operand, variables, types);
256
- const target = types?.get(expression.type);
257
- if (value?.kind === "integer" && target) {
258
- if (integerType(target))
259
- return {
260
- kind: "integer",
261
- value: String(expression.policy === "exact" ? BigInt(value.value) : applyIntegerPolicy(BigInt(value.value), target, expression.policy))
262
- };
263
- if (target.kind === "float")
264
- return {
265
- kind: "float",
266
- value: target.bits === 32 ? Math.fround(Number(value.value)) : Number(value.value)
267
- };
373
+ return;
374
+ };
375
+ var foldRecord = (expression, variables, types) => {
376
+ const fields = Object.create(null);
377
+ for (const [name, operand] of Object.entries(expression.fields)) {
378
+ const value = fold(operand, variables, types);
379
+ if (!value) {
380
+ return;
268
381
  }
269
- if (value?.kind === "float" && target?.kind === "float")
270
- return {
271
- kind: "float",
272
- value: expression.policy === "saturate" ? saturateFloat(value.value, target) : target.bits === 32 ? Math.fround(value.value) : value.value
273
- };
382
+ fields[name] = value;
383
+ }
384
+ return { kind: "record", fields };
385
+ };
386
+ var foldConvert = (expression, value, target) => {
387
+ if (value?.kind === "integer" && target && integerType(target)) {
388
+ const integer = BigInt(value.value);
389
+ return {
390
+ kind: "integer",
391
+ value: String(expression.policy === "exact" ? integer : applyIntegerPolicy(integer, target, expression.policy))
392
+ };
393
+ }
394
+ if (value?.kind === "integer" && target?.kind === "float") {
395
+ return { kind: "float", value: roundFloat(Number(value.value), target) };
396
+ }
397
+ if (value?.kind === "float" && target?.kind === "float") {
398
+ return {
399
+ kind: "float",
400
+ value: expression.policy === "saturate" ? saturateFloat(value.value, target) : roundFloat(value.value, target)
401
+ };
402
+ }
403
+ return;
404
+ };
405
+ var foldUnary = (expression, value, target) => {
406
+ if (value?.kind === "duration" && expression.operator === "timeToMilliseconds") {
407
+ return {
408
+ kind: "integer",
409
+ value: String(BigInt(value.nanoseconds) / nanosecondsPerMillisecond)
410
+ };
411
+ }
412
+ if (value?.kind === "bool" && expression.operator === "not") {
413
+ return { kind: "bool", value: !value.value };
414
+ }
415
+ if (value?.kind === "integer" && expression.operator === "bitNot" && target?.kind === "bits") {
416
+ return {
417
+ kind: "integer",
418
+ value: String(applyIntegerPolicy(~BigInt(value.value), target, "wrap"))
419
+ };
420
+ }
421
+ if (value?.kind === "integer" && expression.operator === "negate") {
422
+ return { kind: "integer", value: String(-BigInt(value.value)) };
423
+ }
424
+ if (value?.kind === "float" && expression.operator === "negate") {
425
+ return { kind: "float", value: -value.value };
426
+ }
427
+ return;
428
+ };
429
+ var ordered = (value) => value.kind !== "bool" && value.kind !== "array" && value.kind !== "record";
430
+ var comparable = (value) => {
431
+ switch (value.kind) {
432
+ case "integer":
433
+ return BigInt(value.value);
434
+ case "duration":
435
+ return BigInt(value.nanoseconds);
436
+ default:
437
+ return value.value;
438
+ }
439
+ };
440
+ var foldBinary = (expression, left, right, target) => {
441
+ if (left.kind === "bool" && right.kind === "bool") {
442
+ return foldLogical(expression.operator, left.value, right.value);
443
+ }
444
+ if (left.kind !== right.kind || !ordered(left) || !ordered(right)) {
274
445
  return;
275
446
  }
276
- if (expression.kind === "unary") {
277
- const value = fold(expression.operand, variables, types);
278
- if (value?.kind === "duration" && expression.operator === "timeToMilliseconds")
279
- return { kind: "integer", value: String(BigInt(value.nanoseconds) / 1000000n) };
280
- if (value?.kind === "bool" && expression.operator === "not")
281
- return { kind: "bool", value: !value.value };
282
- if (value?.kind === "integer" && expression.operator === "bitNot") {
283
- const target = types?.get(expression.type);
284
- if (target?.kind === "bits")
285
- return {
286
- kind: "integer",
287
- value: String(applyIntegerPolicy(~BigInt(value.value), target, "wrap"))
288
- };
447
+ const compared = compare(expression.operator, comparable(left), comparable(right));
448
+ if (compared !== undefined) {
449
+ return { kind: "bool", value: compared };
450
+ }
451
+ if (left.kind === "integer" && right.kind === "integer") {
452
+ const value = integerArithmetic(expression.operator, BigInt(left.value), BigInt(right.value));
453
+ if (value === undefined) {
454
+ return;
289
455
  }
290
- if (value?.kind === "integer" && expression.operator === "negate")
291
- return { kind: "integer", value: String(-BigInt(value.value)) };
292
- if (value?.kind === "float" && expression.operator === "negate")
293
- return { kind: "float", value: -value.value };
456
+ const wrapped = target && integerType(target) && (expression.policy || target.kind === "bits") ? applyIntegerPolicy(value, target, expression.policy ?? "wrap") : value;
457
+ return { kind: "integer", value: String(wrapped) };
294
458
  }
295
- if (expression.kind === "binary") {
296
- const left = fold(expression.left, variables, types), right = fold(expression.right, variables, types);
297
- if (!left || !right || left.kind !== right.kind)
459
+ if (left.kind === "float" && right.kind === "float") {
460
+ const value = floatArithmetic(expression.operator, left.value, right.value);
461
+ if (value === undefined) {
298
462
  return;
299
- if (left.kind === "bool" && right.kind === "bool") {
300
- if (expression.operator === "and")
301
- return { kind: "bool", value: left.value && right.value };
302
- if (expression.operator === "or")
303
- return { kind: "bool", value: left.value || right.value };
304
- if (expression.operator === "equal")
305
- return { kind: "bool", value: left.value === right.value };
306
- if (expression.operator === "notEqual")
307
- return { kind: "bool", value: left.value !== right.value };
308
- }
309
- if (left.kind === "integer" && right.kind === "integer" || left.kind === "float" && right.kind === "float" || left.kind === "duration" && right.kind === "duration" || left.kind === "calendar" && right.kind === "calendar" || left.kind === "string" && right.kind === "string") {
310
- const a = left.kind === "integer" ? BigInt(left.value) : left.kind === "duration" ? BigInt(left.nanoseconds) : left.value;
311
- const b = right.kind === "integer" ? BigInt(right.value) : right.kind === "duration" ? BigInt(right.nanoseconds) : right.value;
312
- switch (expression.operator) {
313
- case "equal":
314
- return { kind: "bool", value: a === b };
315
- case "notEqual":
316
- return { kind: "bool", value: a !== b };
317
- case "less":
318
- return { kind: "bool", value: a < b };
319
- case "lessEqual":
320
- return { kind: "bool", value: a <= b };
321
- case "greater":
322
- return { kind: "bool", value: a > b };
323
- case "greaterEqual":
324
- return { kind: "bool", value: a >= b };
325
- }
326
- if (left.kind !== "integer" && left.kind !== "float")
327
- return;
328
- if (typeof a === "bigint" && typeof b === "bigint") {
329
- let value;
330
- switch (expression.operator) {
331
- case "add":
332
- value = a + b;
333
- break;
334
- case "subtract":
335
- value = a - b;
336
- break;
337
- case "multiply":
338
- value = a * b;
339
- break;
340
- case "divide":
341
- if (b === 0n)
342
- return;
343
- value = a / b;
344
- break;
345
- case "remainder":
346
- if (b === 0n)
347
- return;
348
- value = a % b;
349
- break;
350
- case "bitAnd":
351
- value = a & b;
352
- break;
353
- case "bitOr":
354
- value = a | b;
355
- break;
356
- case "bitXor":
357
- value = a ^ b;
358
- break;
359
- case "shiftLeft":
360
- if (b < 0n || b > 63n)
361
- return;
362
- value = a << b;
363
- break;
364
- case "shiftRight":
365
- if (b < 0n || b > 63n)
366
- return;
367
- value = a >> b;
368
- break;
369
- default:
370
- return;
371
- }
372
- const target = types?.get(expression.type);
373
- if (target && integerType(target) && (expression.policy || target.kind === "bits"))
374
- value = applyIntegerPolicy(value, target, expression.policy ?? "wrap");
375
- return { kind: "integer", value: String(value) };
376
- }
377
- if (typeof a === "number" && typeof b === "number") {
378
- let value;
379
- switch (expression.operator) {
380
- case "add":
381
- value = a + b;
382
- break;
383
- case "subtract":
384
- value = a - b;
385
- break;
386
- case "multiply":
387
- value = a * b;
388
- break;
389
- case "divide":
390
- value = a / b;
391
- break;
392
- case "remainder":
393
- value = a % b;
394
- break;
395
- default:
396
- return;
397
- }
398
- return {
399
- kind: "float",
400
- value: types?.get(expression.type)?.kind === "float" && expression.type === "REAL" ? Math.fround(value) : value
401
- };
402
- }
403
463
  }
464
+ return {
465
+ kind: "float",
466
+ value: target?.kind === "float" ? roundFloat(value, target) : value
467
+ };
404
468
  }
405
469
  return;
406
- }
407
- function interval(expression, types, variables, ranges = new Map) {
470
+ };
471
+ var foldLogical = (operator, left, right) => {
472
+ switch (operator) {
473
+ case "and":
474
+ return { kind: "bool", value: left && right };
475
+ case "or":
476
+ return { kind: "bool", value: left || right };
477
+ case "equal":
478
+ return { kind: "bool", value: left === right };
479
+ case "notEqual":
480
+ return { kind: "bool", value: left !== right };
481
+ default:
482
+ return;
483
+ }
484
+ };
485
+ var compare = (operator, left, right) => {
486
+ switch (operator) {
487
+ case "equal":
488
+ return left === right;
489
+ case "notEqual":
490
+ return left !== right;
491
+ case "less":
492
+ return left < right;
493
+ case "lessEqual":
494
+ return left <= right;
495
+ case "greater":
496
+ return left > right;
497
+ case "greaterEqual":
498
+ return left >= right;
499
+ default:
500
+ return;
501
+ }
502
+ };
503
+ var integerArithmetic = (operator, left, right) => {
504
+ switch (operator) {
505
+ case "add":
506
+ return left + right;
507
+ case "subtract":
508
+ return left - right;
509
+ case "multiply":
510
+ return left * right;
511
+ case "divide":
512
+ return right === 0n ? undefined : left / right;
513
+ case "remainder":
514
+ return right === 0n ? undefined : left % right;
515
+ case "bitAnd":
516
+ return left & right;
517
+ case "bitOr":
518
+ return left | right;
519
+ case "bitXor":
520
+ return left ^ right;
521
+ case "shiftLeft":
522
+ return right < 0n || right > 63n ? undefined : left << right;
523
+ case "shiftRight":
524
+ return right < 0n || right > 63n ? undefined : left >> right;
525
+ default:
526
+ return;
527
+ }
528
+ };
529
+ var floatArithmetic = (operator, left, right) => {
530
+ switch (operator) {
531
+ case "add":
532
+ return left + right;
533
+ case "subtract":
534
+ return left - right;
535
+ case "multiply":
536
+ return left * right;
537
+ case "divide":
538
+ return left / right;
539
+ case "remainder":
540
+ return left % right;
541
+ default:
542
+ return;
543
+ }
544
+ };
545
+
546
+ // packages/compiler/src/ir/ranges.ts
547
+ var interval = (expression, types, variables, ranges = new Map) => {
408
548
  if (expression.kind === "length") {
409
549
  const array = types.get(expression.operand.type);
410
- if (array?.kind === "array")
550
+ if (array?.kind === "array") {
411
551
  return [BigInt(array.length), BigInt(array.length)];
552
+ }
412
553
  }
413
554
  const value = fold(expression, variables, types);
414
- if (value?.kind === "integer")
555
+ if (value?.kind === "integer") {
415
556
  return [BigInt(value.value), BigInt(value.value)];
557
+ }
416
558
  const type = types.get(expression.type);
417
- if (!type || !integerType(type))
559
+ if (!type || !integerType(type)) {
418
560
  return;
419
- if (expression.kind === "load")
561
+ }
562
+ if (expression.kind === "load") {
420
563
  return ranges.get(expression.place.root) ?? integerRange(type);
421
- if (expression.kind === "convert")
564
+ }
565
+ if (expression.kind === "convert") {
422
566
  return expression.policy === "exact" ? interval(expression.operand, types, variables, ranges) : integerRange(type);
567
+ }
423
568
  if (expression.kind === "unary" && expression.operator === "negate") {
424
569
  const operand = interval(expression.operand, types, variables, ranges);
425
570
  return operand && [-operand[1], -operand[0]];
426
571
  }
427
572
  if (expression.kind === "binary" && !expression.policy) {
428
- const a = interval(expression.left, types, variables, ranges), b = interval(expression.right, types, variables, ranges);
429
- if (!a || !b)
430
- return;
431
- const [minimum, maximum] = integerRange(type);
432
- const unwrapped = (low, high) => low < minimum || high > maximum ? [minimum, maximum] : [low, high];
433
- switch (expression.operator) {
434
- case "add":
435
- return unwrapped(a[0] + b[0], a[1] + b[1]);
436
- case "subtract":
437
- return unwrapped(a[0] - b[1], a[1] - b[0]);
438
- case "multiply": {
439
- const values = [a[0] * b[0], a[0] * b[1], a[1] * b[0], a[1] * b[1]];
440
- return unwrapped(values.reduce((x, y) => x < y ? x : y), values.reduce((x, y) => x > y ? x : y));
441
- }
442
- case "divide": {
443
- if (b[0] <= 0n && b[1] >= 0n)
444
- return;
445
- const values = [a[0] / b[0], a[0] / b[1], a[1] / b[0], a[1] / b[1]];
446
- return [values.reduce((x, y) => x < y ? x : y), values.reduce((x, y) => x > y ? x : y)];
573
+ const left = interval(expression.left, types, variables, ranges);
574
+ const right = interval(expression.right, types, variables, ranges);
575
+ return left && right && arithmeticInterval(expression.operator, left, right, integerRange(type));
576
+ }
577
+ return integerRange(type);
578
+ };
579
+ var arithmeticInterval = (operator, left, right, type) => {
580
+ const unwrapped = (result) => within(result, type) ? result : type;
581
+ const corners = (combine) => [
582
+ combine(left[0], right[0]),
583
+ combine(left[0], right[1]),
584
+ combine(left[1], right[0]),
585
+ combine(left[1], right[1])
586
+ ];
587
+ switch (operator) {
588
+ case "add":
589
+ return unwrapped([left[0] + right[0], left[1] + right[1]]);
590
+ case "subtract":
591
+ return unwrapped([left[0] - right[1], left[1] - right[0]]);
592
+ case "multiply": {
593
+ const products = corners((a, b) => a * b);
594
+ return unwrapped([products.reduce(lowest), products.reduce(highest)]);
595
+ }
596
+ case "divide": {
597
+ if (admits(right, 0n)) {
598
+ return;
447
599
  }
448
- case "remainder": {
449
- if (b[0] <= 0n && b[1] >= 0n)
450
- return;
451
- const maximum = [b[0], b[1]].map((n) => n < 0n ? -n : n).reduce((x, y) => x > y ? x : y) - 1n;
452
- return [a[0] < 0n ? -maximum : 0n, a[1] > 0n ? maximum : 0n];
600
+ const quotients = corners((a, b) => a / b);
601
+ return [quotients.reduce(lowest), quotients.reduce(highest)];
602
+ }
603
+ case "remainder": {
604
+ if (admits(right, 0n)) {
605
+ return;
453
606
  }
607
+ const magnitude = (value) => value < 0n ? -value : value;
608
+ const largest = highest(magnitude(right[0]), magnitude(right[1])) - 1n;
609
+ return [left[0] < 0n ? -largest : 0n, left[1] > 0n ? largest : 0n];
454
610
  }
611
+ default:
612
+ return type;
455
613
  }
456
- return integerRange(type);
457
- }
458
- function loopIterations(first, last, step) {
459
- if (step > 0n)
614
+ };
615
+ var maxLoopIterations = 1000000n;
616
+ var loopIterations = (first, last, step) => {
617
+ if (step > 0n) {
460
618
  return last >= first ? (last - first) / step + 1n : 0n;
619
+ }
461
620
  return last <= first ? (first - last) / -step + 1n : 0n;
462
- }
463
- function loopBounds(start, limit, step, exclusive = false) {
621
+ };
622
+ var loopBounds = (start, limit, step, exclusive = false) => {
623
+ const excluded = exclusive ? 1n : 0n;
464
624
  const first = step > 0n ? start[0] : start[1];
465
- const last = step > 0n ? limit[1] - (exclusive ? 1n : 0n) : limit[0] + (exclusive ? 1n : 0n);
625
+ const last = step > 0n ? limit[1] - excluded : limit[0] + excluded;
466
626
  const count = loopIterations(first, last, step);
467
627
  const range = first <= last ? [first, last] : [last, first];
468
628
  return { first, last, count, range };
469
- }
470
- function narrowRanges(condition, truth, types, variables, ranges) {
629
+ };
630
+ var negatedComparisons = {
631
+ less: "greaterEqual",
632
+ lessEqual: "greater",
633
+ greater: "lessEqual",
634
+ greaterEqual: "less"
635
+ };
636
+ var bounded = (current, operator, value) => {
637
+ const [lower, upper] = current;
638
+ switch (operator) {
639
+ case "less":
640
+ return [lower, lowest(upper, value - 1n)];
641
+ case "lessEqual":
642
+ return [lower, lowest(upper, value)];
643
+ case "greater":
644
+ return [highest(lower, value + 1n), upper];
645
+ case "greaterEqual":
646
+ return [highest(lower, value), upper];
647
+ default:
648
+ return current;
649
+ }
650
+ };
651
+ var narrowRanges = (condition, truth, types, variables, ranges) => {
471
652
  const narrowed = new Map(ranges);
472
- if (condition.kind !== "binary")
653
+ if (condition.kind !== "binary") {
473
654
  return narrowed;
474
- if (condition.operator === "and")
655
+ }
656
+ if (condition.operator === "and") {
475
657
  return truth ? narrowRanges(condition.right, truth, types, variables, narrowRanges(condition.left, truth, types, variables, ranges)) : narrowed;
476
- if (condition.left.kind !== "load" || condition.left.place.path.length)
658
+ }
659
+ if (condition.left.kind !== "load" || condition.left.place.path.length) {
477
660
  return narrowed;
478
- const root = condition.left.place.root, variable = variables.get(root), type = types.get(condition.left.type), fixed = variable && (variable.storage === "parameter" && !variable.mode || variable.storage === "local" && !variable.mutable), current = ranges.get(root) ?? (fixed && type && integerType(type) ? integerRange(type) : undefined), bound = interval(condition.right, types, variables, ranges);
479
- if (!current || !bound || bound[0] !== bound[1])
661
+ }
662
+ const root = condition.left.place.root;
663
+ const variable = variables.get(root);
664
+ const type = types.get(condition.left.type);
665
+ const fixed = variable && (variable.storage === "parameter" && !variable.mode || variable.storage === "local" && !variable.mutable);
666
+ const current = ranges.get(root) ?? (fixed && type && integerType(type) ? integerRange(type) : undefined);
667
+ const bound = interval(condition.right, types, variables, ranges);
668
+ if (!current || !bound || bound[0] !== bound[1]) {
480
669
  return narrowed;
481
- const value = bound[0];
482
- let lower = current[0], upper = current[1];
483
- switch (condition.operator) {
484
- case "less":
485
- if (truth)
486
- upper = value - 1n < upper ? value - 1n : upper;
487
- else
488
- lower = value > lower ? value : lower;
489
- break;
490
- case "lessEqual":
491
- if (truth)
492
- upper = value < upper ? value : upper;
493
- else
494
- lower = value + 1n > lower ? value + 1n : lower;
495
- break;
496
- case "greater":
497
- if (truth)
498
- lower = value + 1n > lower ? value + 1n : lower;
499
- else
500
- upper = value < upper ? value : upper;
501
- break;
502
- case "greaterEqual":
503
- if (truth)
504
- lower = value > lower ? value : lower;
505
- else
506
- upper = value - 1n < upper ? value - 1n : upper;
507
- break;
508
670
  }
509
- if (lower <= upper)
671
+ const [lower, upper] = bounded(current, truth ? condition.operator : negatedComparisons[condition.operator], bound[0]);
672
+ if (lower <= upper) {
510
673
  narrowed.set(root, [lower, upper]);
511
- return narrowed;
512
- }
513
- function wrapsNatively(expression) {
514
- return expression.kind === "binary" && !expression.policy && (expression.operator === "add" || expression.operator === "subtract" || expression.operator === "multiply");
515
- }
516
- var lowest = (a, b) => a < b ? a : b;
517
- var highest = (a, b) => a > b ? a : b;
518
- function valueRange(expression, types, variables, ranges, functions) {
519
- if (expression.kind !== "call")
674
+ }
675
+ return narrowed;
676
+ };
677
+ var valueRange = (expression, types, variables, ranges, functions) => {
678
+ if (expression.kind !== "call") {
520
679
  return interval(expression, types, variables, ranges);
680
+ }
521
681
  const helper = functions.get(expression.function)?.bounds;
522
682
  return helper && mathHelperRange(helper, expression.arguments.map((argument) => valueRange(argument, types, variables, ranges, functions)));
523
- }
524
- function mathHelperRange(helper, [first, second, third]) {
525
- if (!first || !second)
683
+ };
684
+ var mathHelperRange = (helper, [first, second, third]) => {
685
+ if (!first || !second) {
526
686
  return;
527
- if (helper === "min")
687
+ }
688
+ if (helper === "min") {
528
689
  return [lowest(first[0], second[0]), lowest(first[1], second[1])];
529
- if (helper === "max")
690
+ }
691
+ if (helper === "max") {
530
692
  return [highest(first[0], second[0]), highest(first[1], second[1])];
531
- if (!third)
693
+ }
694
+ if (!third) {
532
695
  return;
696
+ }
533
697
  return [lowest(second[0], third[0]), highest(second[1], third[1])];
534
- }
535
- function applyIntegerPolicy(value, type, policy) {
536
- const [minimum, maximum] = integerRange(type);
537
- if (policy === "saturate")
538
- return value < minimum ? minimum : value > maximum ? maximum : value;
539
- return type.kind === "integer" && type.signed ? BigInt.asIntN(type.bits, value) : BigInt.asUintN(type.bits, value);
540
- }
541
- function scalarIssue(expression, types, variables, ranges = new Map) {
698
+ };
699
+
700
+ // packages/compiler/src/ir/scalars.ts
701
+ var scalarKinds = new Set([
702
+ "bool",
703
+ "integer",
704
+ "bits",
705
+ "float"
706
+ ]);
707
+ var scalarIssue = (expression, types, variables, ranges = new Map) => {
708
+ const proof = {
709
+ fold: (value) => fold(value, variables, types),
710
+ interval: (value) => interval(value, types, variables, ranges)
711
+ };
542
712
  const type = types.get(expression.type);
543
- if (!type || !["bool", "integer", "bits", "float"].includes(type.kind))
713
+ if (!type || !scalarKinds.has(type.kind)) {
544
714
  return "Unknown scalar expression type.";
545
- if (expression.kind === "constant")
715
+ }
716
+ if (expression.kind === "constant") {
546
717
  return constantFits(expression.value, type) ? undefined : "Literal is outside its PLC type or has the wrong domain.";
547
- if (expression.kind === "load" || expression.kind === "call")
718
+ }
719
+ if (expression.kind === "load" || expression.kind === "call") {
548
720
  return;
549
- if ("operand" in expression && !types.has(expression.operand.type) || "left" in expression && (!types.has(expression.left.type) || !types.has(expression.right.type)))
721
+ }
722
+ if (expression.kind === "convert" || expression.kind === "unary") {
723
+ const source = types.get(expression.operand.type);
724
+ if (!source) {
725
+ return "Unknown operand type.";
726
+ }
727
+ return expression.kind === "convert" ? conversionIssue(expression, source, type, proof) : unaryIssue(expression, source, type, proof);
728
+ }
729
+ if (expression.kind === "binary") {
730
+ const left = types.get(expression.left.type);
731
+ const right = types.get(expression.right.type);
732
+ if (!left || !right) {
733
+ return "Unknown operand type.";
734
+ }
735
+ return binaryIssue(expression, left, right, type, proof);
736
+ }
737
+ if ("operand" in expression && !types.has(expression.operand.type)) {
550
738
  return "Unknown operand type.";
551
- const operand = (value) => types.get(value.type);
552
- if (expression.kind === "convert") {
553
- if (!["exact", "wrap", "saturate"].includes(expression.policy))
554
- return "Unknown numeric conversion policy.";
555
- const source = operand(expression.operand), value = fold(expression.operand, variables, types);
556
- if (source.kind === "bool" || type.kind === "bool")
557
- return "Numeric conversions cannot use BOOL.";
558
- if (expression.policy === "exact") {
559
- if (canAssign(source, type, value) || value && integerType(source) && integerType(type) && constantFits(value, type))
560
- return;
561
- if (integerType(source) && type.kind === "float") {
562
- if (value?.kind === "integer") {
563
- const converted = type.bits === 32 ? Math.fround(Number(value.value)) : Number(value.value);
564
- if (Number.isFinite(converted) && Number.isInteger(converted) && BigInt(converted) === BigInt(value.value))
565
- return;
566
- }
567
- const [minimum, maximum] = interval(expression.operand, types, variables, ranges) ?? integerRange(source);
568
- const limit = 1n << BigInt(type.bits === 32 ? 24 : 53);
569
- if (minimum >= -limit && maximum <= limit)
570
- return;
571
- }
572
- if (integerType(source) && integerType(type)) {
573
- const [fromMin, fromMax] = interval(expression.operand, types, variables, ranges) ?? integerRange(source), [toMin, toMax] = integerRange(type);
574
- if (fromMin >= toMin && fromMax <= toMax)
575
- return;
576
- }
577
- return "Exact conversion cannot be proved lossless.";
739
+ }
740
+ return "Expression has not been reduced to a scalar operation.";
741
+ };
742
+ var conversionIssue = (expression, source, type, proof) => {
743
+ if (!["exact", "wrap", "saturate"].includes(expression.policy)) {
744
+ return "Unknown numeric conversion policy.";
745
+ }
746
+ if (source.kind === "bool" || type.kind === "bool") {
747
+ return "Numeric conversions cannot use BOOL.";
748
+ }
749
+ if (expression.policy === "exact") {
750
+ return exactConversionIssue(expression, source, type, proof);
751
+ }
752
+ if (expression.policy === "saturate" && source.kind === "float" && type.kind === "float") {
753
+ return;
754
+ }
755
+ if (integerType(source) && integerType(type)) {
756
+ return;
757
+ }
758
+ return expression.policy === "saturate" ? "Saturate conversions require two integer/bit-string operands or two floating operands." : "Wrap conversions require integer or bit-string operands.";
759
+ };
760
+ var exactConversionIssue = (expression, source, type, proof) => {
761
+ const value = proof.fold(expression.operand);
762
+ if (canAssign(source, type, value) || value && integerType(source) && integerType(type) && constantFits(value, type)) {
763
+ return;
764
+ }
765
+ if (!integerType(source)) {
766
+ return "Exact conversion cannot be proved lossless.";
767
+ }
768
+ if (type.kind === "float" && value?.kind === "integer") {
769
+ const converted = roundFloat(Number(value.value), type);
770
+ if (Number.isFinite(converted) && Number.isInteger(converted) && BigInt(converted) === BigInt(value.value)) {
771
+ return;
578
772
  }
579
- if (expression.policy === "saturate" && source.kind === "float" && type.kind === "float")
773
+ }
774
+ const proved = proof.interval(expression.operand) ?? integerRange(source);
775
+ if (type.kind === "float") {
776
+ const limit = exactIntegerLimit(type);
777
+ if (within(proved, [-limit, limit])) {
580
778
  return;
581
- return integerType(source) && integerType(type) ? undefined : expression.policy === "saturate" ? "Saturate conversions require two integer/bit-string operands or two floating operands." : "Wrap conversions require integer or bit-string operands.";
779
+ }
582
780
  }
583
- if (expression.kind === "unary") {
584
- const source = operand(expression.operand);
585
- if (expression.operator === "clock")
781
+ if (integerType(type) && within(proved, integerRange(type))) {
782
+ return;
783
+ }
784
+ return "Exact conversion cannot be proved lossless.";
785
+ };
786
+ var unaryIssue = (expression, source, type, proof) => {
787
+ switch (expression.operator) {
788
+ case "clock":
586
789
  return type.id === "DINT" ? undefined : "now() returns DINT milliseconds.";
587
- if (expression.operator === "timeToMilliseconds")
790
+ case "timeToMilliseconds":
588
791
  return source.id === "TIME" && source.kind === "duration" && type.id === "UDINT" ? undefined : "timeToMilliseconds requires TIME and returns UDINT.";
589
- if (expression.operator === "not")
792
+ case "not":
590
793
  return type.kind === "bool" && source.kind === "bool" ? undefined : "Logical negation requires BOOL.";
591
- if (expression.operator === "bitNot")
794
+ case "bitNot":
592
795
  return type.kind === "bits" && source.id === type.id ? undefined : "Bitwise complement requires a bit string.";
593
- if (source.id !== type.id || !(type.kind === "integer" || type.kind === "float"))
594
- return "Numeric negation requires one arithmetic type.";
595
- } else if (expression.kind === "binary") {
596
- const left = operand(expression.left), right = operand(expression.right);
597
- if (expression.operator === "and" || expression.operator === "or")
598
- return type.kind === "bool" && left.kind === "bool" && right.kind === "bool" ? undefined : "Logical operators require BOOL.";
599
- if (comparisonOperators.has(expression.operator))
600
- return type.kind === "bool" && left.id === right.id && ["bool", "integer", "bits", "float"].includes(left.kind) && (left.kind !== "bool" || ["equal", "notEqual"].includes(expression.operator)) ? undefined : "Comparison operands need the same PLC domain.";
601
- if (["bitAnd", "bitOr", "bitXor", "shiftLeft", "shiftRight"].includes(expression.operator)) {
602
- if (type.kind !== "bits" || left.id !== type.id)
603
- return "Bitwise operators require bit strings.";
604
- if (expression.operator === "shiftLeft" || expression.operator === "shiftRight") {
605
- const count = fold(expression.right, variables, types);
606
- return count?.kind === "integer" && BigInt(count.value) >= 0n && BigInt(count.value) < BigInt(type.bits) ? undefined : "Shift count must be a compile-time integer within the bit width.";
796
+ case "negate":
797
+ if (source.id !== type.id || !(type.kind === "integer" || type.kind === "float")) {
798
+ return "Numeric negation requires one arithmetic type.";
607
799
  }
608
- return right.id === type.id ? undefined : "Bit-string widths differ.";
609
- }
610
- if (left.id !== type.id || right.id !== type.id || type.kind !== "integer" && type.kind !== "float")
611
- return "Arithmetic operands need one integer or floating type.";
612
- if (expression.policy)
613
- return type.kind === "integer" && ["add", "subtract", "multiply"].includes(expression.operator) ? undefined : "Explicit arithmetic policies require integer addition, subtraction or multiplication.";
614
- if ((expression.operator === "divide" || expression.operator === "remainder") && type.kind === "integer") {
615
- const divisor = interval(expression.right, types, variables, ranges);
616
- if (!divisor || divisor[0] <= 0n && divisor[1] >= 0n)
617
- return "Division requires a proved nonzero divisor.";
618
- const dividend = interval(expression.left, types, variables, ranges);
619
- const [minimum] = integerRange(type);
620
- if (type.signed && dividend && dividend[0] <= minimum && divisor[0] <= -1n && divisor[1] >= -1n)
621
- return "Signed minimum divided by -1 cannot be represented.";
622
- }
623
- } else
624
- return "Expression has not been reduced to a scalar operation.";
800
+ return resultIssue(expression, type, proof);
801
+ }
802
+ };
803
+ var binaryIssue = (expression, left, right, type, proof) => {
804
+ if (expression.operator === "and" || expression.operator === "or") {
805
+ return type.kind === "bool" && left.kind === "bool" && right.kind === "bool" ? undefined : "Logical operators require BOOL.";
806
+ }
807
+ if (comparisonOperators.has(expression.operator)) {
808
+ return type.kind === "bool" && left.id === right.id && scalarKinds.has(left.kind) && (left.kind !== "bool" || ["equal", "notEqual"].includes(expression.operator)) ? undefined : "Comparison operands need the same PLC domain.";
809
+ }
810
+ if (["bitAnd", "bitOr", "bitXor", "shiftLeft", "shiftRight"].includes(expression.operator)) {
811
+ if (type.kind !== "bits" || left.id !== type.id) {
812
+ return "Bitwise operators require bit strings.";
813
+ }
814
+ if (expression.operator === "shiftLeft" || expression.operator === "shiftRight") {
815
+ const count = proof.fold(expression.right);
816
+ return count?.kind === "integer" && BigInt(count.value) >= 0n && BigInt(count.value) < BigInt(type.bits) ? undefined : "Shift count must be a compile-time integer within the bit width.";
817
+ }
818
+ return right.id === type.id ? undefined : "Bit-string widths differ.";
819
+ }
820
+ if (left.id !== type.id || right.id !== type.id || type.kind !== "integer" && type.kind !== "float") {
821
+ return "Arithmetic operands need one integer or floating type.";
822
+ }
823
+ if (expression.policy) {
824
+ return type.kind === "integer" && ["add", "subtract", "multiply"].includes(expression.operator) ? undefined : "Explicit arithmetic policies require integer addition, subtraction or multiplication.";
825
+ }
826
+ if ((expression.operator === "divide" || expression.operator === "remainder") && type.kind === "integer") {
827
+ const divisor = proof.interval(expression.right);
828
+ if (!divisor || admits(divisor, 0n)) {
829
+ return "Division requires a proved nonzero divisor.";
830
+ }
831
+ const dividend = proof.interval(expression.left);
832
+ const [minimum] = integerRange(type);
833
+ if (type.signed && dividend && dividend[0] <= minimum && admits(divisor, -1n)) {
834
+ return "Signed minimum divided by -1 cannot be represented.";
835
+ }
836
+ }
837
+ return resultIssue(expression, type, proof);
838
+ };
839
+ var resultIssue = (expression, type, proof) => {
625
840
  if (integerType(type)) {
626
- const result = interval(expression, types, variables, ranges), [minimum, maximum] = integerRange(type);
627
- if (!(wrapsNatively(expression) && !fold(expression, variables, types)) && (!result || result[0] < minimum || result[1] > maximum))
841
+ const result = proof.interval(expression);
842
+ if (!(wrapsNatively(expression) && !proof.fold(expression)) && (!result || !within(result, integerRange(type)))) {
628
843
  return "Arithmetic may overflow; widen the result or use an explicit wrap/saturate operation.";
629
- } else if (type.kind === "float") {
630
- const result = fold(expression, variables, types);
631
- if (result)
632
- return constantFits(result, type) ? undefined : "Floating result is not finite or representable.";
633
- if (expression.kind === "binary") {
634
- const lhs = fold(expression.left, variables, types);
635
- const rhs = fold(expression.right, variables, types);
636
- if (["add", "subtract"].includes(expression.operator) && (lhs?.kind === "float" || rhs?.kind === "float")) {
637
- const maximum = floatMaximum(type);
638
- const finite = [-maximum, maximum].every((endpoint) => {
639
- const a = lhs?.kind === "float" ? lhs.value : endpoint;
640
- const b = rhs?.kind === "float" ? rhs.value : endpoint;
641
- const value = expression.operator === "add" ? a + b : a - b;
642
- return Number.isFinite(type.bits === 32 ? Math.fround(value) : value);
643
- });
644
- if (finite)
645
- return;
646
- }
647
- if (rhs?.kind === "float" && rhs.value === 1 && ["multiply", "divide"].includes(expression.operator))
648
- return;
649
- } else if (expression.kind === "unary")
650
- return;
651
- return "Floating arithmetic must prove a finite result.";
652
- }
653
- return;
654
- }
655
-
656
- // packages/compiler/ir/domains.ts
657
- function durationLiteral(text, scaleNanoseconds) {
658
- const clean = text.replaceAll("_", "").replace(/^(-?)\./, (_, sign) => `${sign}0.`);
659
- const match = /^(-?)(\d+)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(clean);
660
- if (!match)
844
+ }
661
845
  return;
662
- const fraction = match[3] ?? "", exponent = Number(match[4] ?? 0) - fraction.length;
663
- if (!Number.isSafeInteger(exponent) || Math.abs(exponent) > 400)
846
+ }
847
+ if (type.kind !== "float") {
664
848
  return;
665
- let value = BigInt(match[2] + fraction) * scaleNanoseconds;
666
- if (exponent >= 0)
667
- value *= 10n ** BigInt(exponent);
668
- else {
669
- const divisor = 10n ** BigInt(-exponent);
670
- if (value % divisor)
671
- return;
672
- value /= divisor;
673
849
  }
674
- if (match[1])
675
- value = -value;
676
- return validDuration(value) ? { kind: "duration", nanoseconds: String(value) } : undefined;
677
- }
678
- function validDuration(nanoseconds) {
679
- return nanoseconds >= 0n && nanoseconds <= 4294967295000000n && nanoseconds % 1000000n === 0n;
680
- }
681
- function validDate(text) {
682
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
683
- if (!match)
684
- return false;
685
- const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
686
- const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
687
- const length = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
688
- return Boolean(length && day >= 1 && day <= length && text >= "1970-01-01" && text <= "2106-02-07");
689
- }
690
- function validClock(text, milliseconds) {
691
- const match = (milliseconds ? /^(\d{2}):(\d{2}):(\d{2})\.(\d{3})$/ : /^(\d{2}):(\d{2}):(\d{2})$/).exec(text);
692
- return Boolean(match && Number(match[1]) < 24 && Number(match[2]) < 60 && Number(match[3]) < 60);
693
- }
694
- function calendarLiteral(domain, text) {
695
- if (domain === "date")
696
- return validDate(text) ? { kind: "calendar", value: text } : undefined;
697
- if (domain === "timeOfDay") {
698
- const canonical = /^\d{2}:\d{2}:\d{2}$/.test(text) ? `${text}.000` : text;
699
- return validClock(canonical, true) ? { kind: "calendar", value: canonical } : undefined;
850
+ const result = proof.fold(expression);
851
+ if (result) {
852
+ return constantFits(result, type) ? undefined : "Floating result is not finite or representable.";
700
853
  }
701
- return text.length === 19 && text[10] === "T" && validDate(text.slice(0, 10)) && validClock(text.slice(11), false) && text <= "2106-02-07T06:28:15" ? { kind: "calendar", value: text } : undefined;
702
- }
703
- function domainConstantFits(value, type) {
704
- if (type.kind === "duration")
705
- return value.kind === "duration" && /^(?:0|[1-9][0-9]*)$/.test(value.nanoseconds) && validDuration(BigInt(value.nanoseconds));
706
- if (type.kind === "calendar" && value.kind === "calendar") {
707
- const parsed = calendarLiteral(type.domain, value.value);
708
- return parsed?.kind === "calendar" && parsed.value === value.value;
854
+ if (expression.kind === "unary") {
855
+ return;
709
856
  }
710
- return false;
711
- }
712
- function domainIssue(value, types) {
713
- const type = types.get(value.type);
714
- if (value.kind === "constant")
715
- return type && domainConstantFits(value.value, type) ? undefined : "Invalid TIME/calendar constant.";
716
- if (value.kind === "load" || value.kind === "call" || value.kind === "conditional")
857
+ const lhs = proof.fold(expression.left);
858
+ const rhs = proof.fold(expression.right);
859
+ if (["add", "subtract"].includes(expression.operator) && (lhs?.kind === "float" || rhs?.kind === "float")) {
860
+ const maximum = floatMaximum(type);
861
+ const finite = [-maximum, maximum].every((endpoint) => {
862
+ const a = lhs?.kind === "float" ? lhs.value : endpoint;
863
+ const b = rhs?.kind === "float" ? rhs.value : endpoint;
864
+ const value = expression.operator === "add" ? a + b : a - b;
865
+ return Number.isFinite(roundFloat(value, type));
866
+ });
867
+ if (finite) {
868
+ return;
869
+ }
870
+ }
871
+ if (rhs?.kind === "float" && rhs.value === 1 && ["multiply", "divide"].includes(expression.operator)) {
717
872
  return;
718
- if (value.kind === "binary" && comparisonOperators.has(value.operator)) {
719
- const left = types.get(value.left.type);
720
- return value.type === "BOOL" && left && ["duration", "calendar"].includes(left.kind) && value.left.type === value.right.type ? undefined : "Time comparisons require matching domains.";
721
873
  }
722
- return "TIME and calendar domains permit storage, typed copies and comparisons; implicit numeric arithmetic is unsupported.";
723
- }
874
+ return "Floating arithmetic must prove a finite result.";
875
+ };
724
876
 
725
- // packages/compiler/ir/aggregates.ts
877
+ // packages/compiler/src/ir/aggregates.ts
726
878
  function aggregate(type) {
727
879
  return type?.kind === "record" || type?.kind === "array";
728
880
  }
729
881
  function valueFits(value, type, types) {
730
- if (type.kind === "duration" || type.kind === "calendar")
882
+ if (type.kind === "duration" || type.kind === "calendar") {
731
883
  return domainConstantFits(value, type);
732
- if (type.kind === "enum")
884
+ }
885
+ if (type.kind === "enum") {
733
886
  return value.kind === "integer" && type.members.some((member) => member.value === value.value);
734
- if (type.kind === "string")
887
+ }
888
+ if (type.kind === "string") {
735
889
  return value.kind === "string" && !value.value.includes("\x00") && (type.encoding === "utf8" ? new TextEncoder().encode(value.value).length <= type.capacity : value.value.length <= type.capacity);
736
- if (type.kind === "array")
890
+ }
891
+ if (type.kind === "array") {
737
892
  return value.kind === "array" && value.items.length === type.length && value.items.every((item) => valueFits(item, types.get(type.element), types));
738
- if (type.kind === "record")
893
+ }
894
+ if (type.kind === "record") {
739
895
  return value.kind === "record" && Object.keys(value.fields).length === type.fields.length && type.fields.every((field) => Object.hasOwn(value.fields, field.name) && valueFits(value.fields[field.name], types.get(field.type), types));
896
+ }
740
897
  return constantFits(value, type);
741
898
  }
742
899
  function defaultValue(typeId, types) {
743
900
  const type = types.get(typeId);
744
- if (!type)
901
+ if (!type) {
745
902
  throw new Error("Unknown default-value type");
746
- if (type.kind === "bool")
903
+ }
904
+ if (type.kind === "bool") {
747
905
  return { kind: "bool", value: false };
748
- if (type.kind === "float")
906
+ }
907
+ if (type.kind === "float") {
749
908
  return { kind: "float", value: 0 };
750
- if (type.kind === "string")
909
+ }
910
+ if (type.kind === "string") {
751
911
  return { kind: "string", value: "" };
752
- if (type.kind === "enum")
912
+ }
913
+ if (type.kind === "enum") {
753
914
  return {
754
915
  kind: "integer",
755
916
  value: type.members.find((member) => member.value === "0")?.value ?? type.members[0].value
756
917
  };
757
- if (type.kind === "array")
918
+ }
919
+ if (type.kind === "array") {
758
920
  return {
759
921
  kind: "array",
760
922
  items: Array.from({ length: type.length }, () => defaultValue(type.element, types))
761
923
  };
762
- if (type.kind === "record")
924
+ }
925
+ if (type.kind === "record") {
763
926
  return {
764
927
  kind: "record",
765
- fields: Object.fromEntries(type.fields.map((field) => [field.name, defaultValue(field.type, types)]))
928
+ fields: Object.fromEntries(type.fields.map((field) => [
929
+ field.name,
930
+ defaultValue(field.type, types)
931
+ ]))
766
932
  };
767
- if (type.kind === "duration")
933
+ }
934
+ if (type.kind === "duration") {
768
935
  return { kind: "duration", nanoseconds: "0" };
769
- if (type.kind === "calendar")
770
- return {
771
- kind: "calendar",
772
- value: type.domain === "date" ? "1970-01-01" : type.domain === "timeOfDay" ? "00:00:00.000" : "1970-01-01T00:00:00"
773
- };
774
- if (type.kind === "integer" || type.kind === "bits")
936
+ }
937
+ if (type.kind === "calendar") {
938
+ return { kind: "calendar", value: calendarZero[type.domain] };
939
+ }
940
+ if (type.kind === "integer" || type.kind === "bits") {
775
941
  return { kind: "integer", value: "0" };
942
+ }
776
943
  throw new Error("Unsupported default-value type");
777
944
  }
778
945
  function placeType(place, types, variables, ranges = new Map, writable = false) {
779
946
  const root = variables.get(place.root);
780
- if (!root)
947
+ if (!root) {
781
948
  return { issue: "Unknown storage root." };
782
- if (writable && (root.storage === "input" || root.storage === "constant" || root.storage === "blockOutput" || root.storage === "parameter" && root.mode !== "inOut" || !place.path.length && !root.mutable))
949
+ }
950
+ if (writable && (root.storage === "input" || root.storage === "constant" || root.storage === "blockOutput" || root.storage === "parameter" && root.mode !== "inOut" || !place.path.length && !root.mutable)) {
783
951
  return { issue: "This storage is read-only." };
952
+ }
784
953
  let id = root.type;
785
954
  for (const segment of place.path) {
786
955
  const type = types.get(id);
787
956
  if (segment.kind === "field") {
788
957
  if (type?.kind === "block" && segment.name === "out" && type.output) {
789
- if (writable)
958
+ if (writable) {
790
959
  return { issue: "Function block output views are read-only." };
960
+ }
791
961
  id = type.output;
792
962
  continue;
793
963
  }
794
- if (type?.kind !== "record")
964
+ if (type?.kind !== "record") {
795
965
  return { issue: "Field access requires a record." };
966
+ }
796
967
  const field = type.fields.find((field) => field.name === segment.name);
797
- if (!field)
968
+ if (!field) {
798
969
  return { issue: "Unknown record field." };
799
- if (writable && field.readonly)
970
+ }
971
+ if (writable && field.readonly) {
800
972
  return { issue: "This field is read-only." };
973
+ }
801
974
  id = field.type;
802
975
  } else {
803
- if (type?.kind !== "array")
976
+ if (type?.kind !== "array") {
804
977
  return { issue: "Index access requires a fixed array." };
978
+ }
805
979
  if (type.index && segment.value.type === type.index) {
806
980
  id = type.element;
807
981
  continue;
808
982
  }
809
- const indexType = types.get(segment.value.type), bounds = interval(segment.value, types, variables, ranges);
810
- if (indexType?.kind !== "integer" || !bounds || bounds[0] < BigInt(type.lowerBound) || bounds[1] >= BigInt(type.lowerBound + type.length))
811
- return { issue: "Array index must be proved within the declared bounds." };
983
+ const indexType = types.get(segment.value.type);
984
+ const bounds = interval(segment.value, types, variables, ranges);
985
+ if (indexType?.kind !== "integer" || !bounds || bounds[0] < BigInt(type.lowerBound) || bounds[1] >= BigInt(type.lowerBound + type.length)) {
986
+ return {
987
+ issue: "Array index must be proved within the declared bounds."
988
+ };
989
+ }
812
990
  id = type.element;
813
991
  }
814
992
  }
@@ -816,22 +994,28 @@ function placeType(place, types, variables, ranges = new Map, writable = false)
816
994
  }
817
995
  function aggregateIssue(value, types) {
818
996
  const type = types.get(value.type);
819
- if (!type)
997
+ if (!type) {
820
998
  return "Unknown expression type.";
821
- if (value.kind === "constant")
999
+ }
1000
+ if (value.kind === "constant") {
822
1001
  return valueFits(value.value, type, types) ? undefined : "Constant does not fit its closed PLC layout.";
823
- if (value.kind === "record")
1002
+ }
1003
+ if (value.kind === "record") {
824
1004
  return type.kind === "record" && Object.keys(value.fields).length === type.fields.length && type.fields.every((field) => Object.hasOwn(value.fields, field.name) && value.fields[field.name]?.type === field.type) ? undefined : "Record expression differs from its layout.";
825
- if (value.kind === "array")
1005
+ }
1006
+ if (value.kind === "array") {
826
1007
  return type.kind === "array" && value.items.length === type.length && value.items.every((item) => item.type === type.element) ? undefined : "Array expression differs from its layout.";
827
- if (value.kind === "copy")
1008
+ }
1009
+ if (value.kind === "copy") {
828
1010
  return aggregate(type) && value.operand.type === value.type ? undefined : "Copy requires one matching fixed aggregate.";
1011
+ }
829
1012
  if (value.kind === "convert") {
830
1013
  const source = types.get(value.operand.type);
831
1014
  return type.kind === "string" && source?.kind === "string" && source.encoding === type.encoding && source.capacity <= type.capacity && value.policy === "exact" ? undefined : "Unsupported aggregate/domain conversion.";
832
1015
  }
833
- if (value.kind === "load" || value.kind === "call" || value.kind === "conditional")
1016
+ if (value.kind === "load" || value.kind === "call" || value.kind === "conditional") {
834
1017
  return;
1018
+ }
835
1019
  if (value.kind === "binary" && comparisonOperators.has(value.operator)) {
836
1020
  const left = types.get(value.left.type);
837
1021
  return value.type === "BOOL" && left && ["enum", "string"].includes(left.kind) && value.left.type === value.right.type && (left.kind !== "enum" || ["equal", "notEqual"].includes(value.operator)) ? undefined : "Comparison requires compatible scalar domains; object identity is unsupported.";
@@ -839,183 +1023,288 @@ function aggregateIssue(value, types) {
839
1023
  return "Operation is unsupported for this PLC domain.";
840
1024
  }
841
1025
  function expressionIssue(value, types, variables, ranges) {
842
- const kinds = [value.type, ...value.kind === "binary" ? [value.left.type] : []].map((id) => types.get(id)?.kind ?? "");
843
- if (kinds.some((kind) => ["duration", "calendar"].includes(kind)))
1026
+ const kinds = [
1027
+ value.type,
1028
+ ...value.kind === "binary" ? [value.left.type] : []
1029
+ ].map((id) => types.get(id)?.kind ?? "");
1030
+ if (kinds.some((kind) => ["duration", "calendar"].includes(kind))) {
844
1031
  return domainIssue(value, types);
845
- if (["copy", "record", "array"].includes(value.kind) || kinds.some((kind) => ["record", "array", "enum", "string"].includes(kind)))
1032
+ }
1033
+ if (["copy", "record", "array"].includes(value.kind) || kinds.some((kind) => ["record", "array", "enum", "string"].includes(kind))) {
846
1034
  return aggregateIssue(value, types);
1035
+ }
847
1036
  return scalarIssue(value, types, variables, ranges);
848
1037
  }
849
- function layoutIssue(types) {
850
- for (const type of types.values()) {
851
- const canonical = primitiveTypes.find((item) => item.id === type.id);
852
- if (canonical) {
853
- if (type.kind !== canonical.kind || "bits" in canonical && (!("bits" in type) || type.bits !== canonical.bits) || "signed" in canonical && (!("signed" in type) || type.signed !== canonical.signed) || "domain" in canonical && (!("domain" in type) || type.domain !== canonical.domain))
854
- return `Conflicting primitive type ${type.id}`;
855
- continue;
1038
+
1039
+ // packages/compiler/src/ir/layouts.ts
1040
+ import { elementaryType as elementaryType2, integerRange as integerRange3 } from "@tsplc/iec";
1041
+
1042
+ // packages/compiler/src/ir/diagnostics.ts
1043
+ function error(code, message, span) {
1044
+ return {
1045
+ origin: "plc",
1046
+ code,
1047
+ severity: "error",
1048
+ message,
1049
+ ...span && { span }
1050
+ };
1051
+ }
1052
+ function hasErrors(diagnostics) {
1053
+ return diagnostics.some((diagnostic) => diagnostic.severity === "error");
1054
+ }
1055
+ function formatDiagnostic(diagnostic, source) {
1056
+ const { span } = diagnostic;
1057
+ const location = span ? `${span.file}:${span.line}:${span.column}: ` : "";
1058
+ let result = `${location}${diagnostic.code}: ${diagnostic.message}`;
1059
+ if (source !== undefined && span) {
1060
+ const line = source.split(/\r?\n/)[span.line - 1];
1061
+ if (line !== undefined) {
1062
+ const width = Math.max(1, Math.min(span.end - span.start, line.length - span.column + 2));
1063
+ result += `
1064
+ ${span.line} | ${line}
1065
+ ${" ".repeat(String(span.line).length + 3 + span.column - 1)}${"^".repeat(width)}`;
856
1066
  }
857
- if (type.kind === "record") {
858
- if (!type.fields.length || new Set(type.fields.map((field) => field.name)).size !== type.fields.length || type.fields.some((field) => !field.name || typeof field.readonly !== "boolean" || field.mode && field.mode !== "inOut" || !types.has(field.type)))
859
- return `Invalid closed record layout ${type.id}`;
860
- } else if (type.kind === "array") {
861
- if (!types.has(type.element) || !Number.isSafeInteger(type.length) || type.length < 1 || type.length > 1e6 || !Number.isInteger(type.lowerBound) || type.lowerBound < -2147483648 || type.lowerBound + type.length - 1 > 2147483647)
1067
+ }
1068
+ for (const related of diagnostic.related ?? []) {
1069
+ result += `
1070
+ ${related.span.file}:${related.span.line}:${related.span.column}: ${related.message}`;
1071
+ }
1072
+ for (const note of diagnostic.notes ?? []) {
1073
+ result += `
1074
+ ${note}`;
1075
+ }
1076
+ return result;
1077
+ }
1078
+
1079
+ // packages/compiler/src/ir/normalization-error.ts
1080
+ class InvalidCore extends Error {
1081
+ diagnostic;
1082
+ constructor(diagnostic) {
1083
+ super(diagnostic.message);
1084
+ this.diagnostic = diagnostic;
1085
+ }
1086
+ }
1087
+ function reject(message, span) {
1088
+ throw new InvalidCore(error("PLC6001", message, span));
1089
+ }
1090
+
1091
+ // packages/compiler/src/ir/layouts.ts
1092
+ var maxScalarElements = 1e6;
1093
+ var maxNestingDepth = 64;
1094
+ var [firstIndex, lastIndex] = integerRange3(elementaryType2("DINT"));
1095
+ var definitionIssue = (type, types) => {
1096
+ const canonical = primitiveTypes.find((item) => item.id === type.id);
1097
+ if (canonical) {
1098
+ return type.kind !== canonical.kind || "bits" in canonical && (!("bits" in type) || type.bits !== canonical.bits) || "signed" in canonical && (!("signed" in type) || type.signed !== canonical.signed) || "domain" in canonical && (!("domain" in type) || type.domain !== canonical.domain) ? `Conflicting primitive type ${type.id}` : undefined;
1099
+ }
1100
+ switch (type.kind) {
1101
+ case "record":
1102
+ return !type.fields.length || new Set(type.fields.map((field) => field.name)).size !== type.fields.length || type.fields.some((field) => !field.name || typeof field.readonly !== "boolean" || field.mode && field.mode !== "inOut" || !types.has(field.type)) ? `Invalid closed record layout ${type.id}` : undefined;
1103
+ case "array": {
1104
+ if (!types.has(type.element) || !Number.isSafeInteger(type.length) || type.length < 1 || type.length > maxScalarElements || !Number.isInteger(type.lowerBound) || BigInt(type.lowerBound) < firstIndex || BigInt(type.lowerBound + type.length - 1) > lastIndex) {
862
1105
  return `Invalid fixed array layout ${type.id}`;
863
- if (type.index !== undefined) {
864
- const index = types.get(type.index);
865
- if (index?.kind !== "enum" || index.members.length !== type.length || index.members.some((member) => Number(member.value) < type.lowerBound || Number(member.value) >= type.lowerBound + type.length))
866
- return `Invalid enum-keyed array layout ${type.id}`;
867
1106
  }
868
- } else if (type.kind === "enum") {
869
- if (type.base !== "DINT" || types.get(type.base)?.kind !== "integer" || !type.members.length || new Set(type.members.map((member) => member.name)).size !== type.members.length || new Set(type.members.map((member) => member.value)).size !== type.members.length || type.members.some((member) => !member.name || !constantFits({ kind: "integer", value: member.value }, types.get(type.base))))
870
- return `Invalid enum layout ${type.id}`;
871
- } else if (type.kind === "string") {
872
- if (!Number.isInteger(type.capacity) || type.capacity < 1 || type.capacity > 65535 || !["utf8", "utf16"].includes(type.encoding))
873
- return `Invalid bounded string layout ${type.id}`;
874
- } else if (type.kind === "block") {
875
- if (!type.block || type.output && types.get(type.output)?.kind !== "record")
876
- return `Invalid block type ${type.id}`;
877
- } else
1107
+ if (type.index === undefined) {
1108
+ return;
1109
+ }
1110
+ const index = types.get(type.index);
1111
+ return index?.kind !== "enum" || index.members.length !== type.length || index.members.some((member) => Number(member.value) < type.lowerBound || Number(member.value) >= type.lowerBound + type.length) ? `Invalid enum-keyed array layout ${type.id}` : undefined;
1112
+ }
1113
+ case "enum": {
1114
+ const base = types.get(type.base);
1115
+ return type.base !== "DINT" || base?.kind !== "integer" || !type.members.length || new Set(type.members.map((member) => member.name)).size !== type.members.length || new Set(type.members.map((member) => member.value)).size !== type.members.length || type.members.some((member) => !member.name || !constantFits({ kind: "integer", value: member.value }, base)) ? `Invalid enum layout ${type.id}` : undefined;
1116
+ }
1117
+ case "string":
1118
+ return !Number.isInteger(type.capacity) || type.capacity < 1 || type.capacity > 65535 || !["utf8", "utf16"].includes(type.encoding) ? `Invalid bounded string layout ${type.id}` : undefined;
1119
+ case "block":
1120
+ return !type.block || type.output && types.get(type.output)?.kind !== "record" ? `Invalid block type ${type.id}` : undefined;
1121
+ default:
878
1122
  return `Unsupported core type definition ${type.id}`;
879
1123
  }
880
- const active = new Set, layouts = new Map;
881
- const count = (id, depth) => {
882
- if (active.has(id) || depth > 64)
883
- throw new Error(`Recursive or excessively nested by-value layout ${id}`);
1124
+ };
1125
+ var admitLayouts = (types) => {
1126
+ for (const type of types.values()) {
1127
+ const issue = definitionIssue(type, types);
1128
+ if (issue) {
1129
+ reject(issue);
1130
+ }
1131
+ }
1132
+ const active = new Set;
1133
+ const layouts = new Map;
1134
+ const measure = (id, depth) => {
1135
+ if (active.has(id) || depth > maxNestingDepth) {
1136
+ reject(`Recursive or excessively nested by-value layout ${id}`);
1137
+ }
884
1138
  const cached = layouts.get(id);
885
1139
  if (cached) {
886
- if (depth + cached.height > 64)
887
- throw new Error(`Layout nesting exceeds 64 levels ${id}`);
1140
+ if (depth + cached.height > maxNestingDepth) {
1141
+ reject(`Layout nesting exceeds ${maxNestingDepth} levels ${id}`);
1142
+ }
888
1143
  return cached;
889
1144
  }
890
1145
  active.add(id);
891
- const type = types.get(id);
892
- const children = type.kind === "array" ? [count(type.element, depth + 1)] : type.kind === "record" ? type.fields.map((field) => count(field.type, depth + 1)) : [];
893
- const size = type.kind === "array" ? type.length * children[0].size : type.kind === "record" ? children.reduce((sum, child) => sum + child.size, 0) : 1;
894
- const height = children.length ? 1 + children.reduce((maximum, child) => Math.max(maximum, child.height), 0) : 0;
1146
+ const layout = composite(types.get(id), depth);
895
1147
  active.delete(id);
896
- if (size > 1e6)
897
- throw new Error(`Layout exceeds one million scalar elements ${id}`);
898
- if (depth + height > 64)
899
- throw new Error(`Layout nesting exceeds 64 levels ${id}`);
900
- const layout = { size, height };
1148
+ if (layout.size > maxScalarElements) {
1149
+ reject(`Layout exceeds one million scalar elements ${id}`);
1150
+ }
1151
+ if (depth + layout.height > maxNestingDepth) {
1152
+ reject(`Layout nesting exceeds ${maxNestingDepth} levels ${id}`);
1153
+ }
901
1154
  layouts.set(id, layout);
902
1155
  return layout;
903
1156
  };
1157
+ const composite = (type, depth) => {
1158
+ if (type.kind === "array") {
1159
+ const element = measure(type.element, depth + 1);
1160
+ return { size: type.length * element.size, height: 1 + element.height };
1161
+ }
1162
+ if (type.kind === "record") {
1163
+ const fields = type.fields.map((field) => measure(field.type, depth + 1));
1164
+ return {
1165
+ size: fields.reduce((sum, field) => sum + field.size, 0),
1166
+ height: 1 + fields.reduce((maximum, field) => Math.max(maximum, field.height), 0)
1167
+ };
1168
+ }
1169
+ return { size: 1, height: 0 };
1170
+ };
1171
+ for (const id of types.keys()) {
1172
+ measure(id, 0);
1173
+ }
1174
+ return new Map([...layouts].map(([id, layout]) => [id, layout.size]));
1175
+ };
1176
+ var layoutIssue = (types) => {
904
1177
  try {
905
- for (const id of types.keys())
906
- count(id, 0);
1178
+ admitLayouts(types);
1179
+ return;
907
1180
  } catch (cause) {
908
- return cause instanceof Error ? cause.message : "Invalid layout";
1181
+ if (cause instanceof InvalidCore) {
1182
+ return cause.diagnostic.message;
1183
+ }
1184
+ throw cause;
909
1185
  }
910
- return;
911
- }
1186
+ };
912
1187
 
913
- // packages/compiler/ir/normalization-error.ts
914
- class InvalidCore extends Error {
915
- diagnostic;
916
- constructor(diagnostic) {
917
- super(diagnostic.message);
918
- this.diagnostic = diagnostic;
1188
+ // packages/compiler/src/ir/declarations.ts
1189
+ var matchesPorts = (variables, schema) => variables.length === schema.length && schema.every(([name, , type]) => variables.some((variable) => variable.name === name && variable.type === type && !variable.mode && !variable.retain));
1190
+ var checkStandardBlock = (block, standard) => {
1191
+ const expected = Object.hasOwn(standardBlocks, standard) ? standardBlocks[standard] : undefined;
1192
+ if (!expected || block.name !== standard || block.body.length || block.state.length || block.locals.length || !matchesPorts(block.inputs, expected.inputs) || !matchesPorts(block.outputs, expected.outputs) || block.outputs.some(({ initial }) => {
1193
+ switch (initial?.kind) {
1194
+ case "bool":
1195
+ return initial.value !== false;
1196
+ case "duration":
1197
+ return initial.nanoseconds !== "0";
1198
+ case "integer":
1199
+ return initial.value !== "0";
1200
+ default:
1201
+ return true;
1202
+ }
1203
+ })) {
1204
+ reject("Invalid canonical standard block definition.", block.span);
919
1205
  }
920
- }
921
- function reject(message, span) {
922
- throw new InvalidCore(error("PLC6001", message, span));
923
- }
1206
+ };
924
1207
 
925
- // packages/compiler/ir/declarations.ts
926
1208
  class ModuleDeclarations {
927
1209
  ids = new Set;
928
1210
  types = new Map;
1211
+ layoutSizes;
929
1212
  globals = new Map;
930
1213
  blocks;
931
1214
  signatures;
932
1215
  constructor(module) {
933
1216
  for (const type of module.types) {
934
- if (this.types.has(type.id))
1217
+ if (this.types.has(type.id)) {
935
1218
  reject(`Duplicate type ${type.id}.`);
1219
+ }
936
1220
  this.types.set(type.id, type);
937
1221
  }
938
- const invalidLayout = layoutIssue(this.types);
939
- if (invalidLayout)
940
- reject(invalidLayout);
941
- if (this.types.get("BOOL")?.kind !== "bool")
1222
+ this.layoutSizes = admitLayouts(this.types);
1223
+ if (this.types.get("BOOL")?.kind !== "bool") {
942
1224
  reject("Missing canonical BOOL type.");
1225
+ }
943
1226
  this.blocks = new Map(module.blocks.map((block) => [block.id, block]));
944
1227
  for (const item of module.variables) {
945
- this.checkVariable(item, ["module", "instance", "input", "output", "constant"]);
1228
+ this.checkVariable(item, [
1229
+ "module",
1230
+ "instance",
1231
+ "input",
1232
+ "output",
1233
+ "constant"
1234
+ ]);
946
1235
  this.globals.set(item.id, item);
947
1236
  }
948
1237
  this.signatures = new Map(module.functions.map((fn) => [fn.id, fn]));
949
1238
  for (const fn of module.functions) {
950
1239
  this.claimId(fn.id, fn.span);
951
- if (fn.owner && (!this.blocks.has(fn.owner.block) || this.blocks.get(fn.owner.block)?.standard || !["public", "private", "protected"].includes(fn.owner.access)))
1240
+ if (fn.owner && (!this.blocks.has(fn.owner.block) || this.blocks.get(fn.owner.block)?.standard || !["public", "private", "protected"].includes(fn.owner.access))) {
952
1241
  reject("Methods require a user block owner and a valid access modifier.", fn.span);
953
- if (fn.result && !this.isValueType(fn.result))
1242
+ }
1243
+ if (fn.result && !this.isValueType(fn.result)) {
954
1244
  reject("Unknown or non-value function result type.", fn.span);
1245
+ }
955
1246
  for (const parameter of fn.parameters) {
956
1247
  this.checkVariable(parameter, ["parameter"], true);
957
- if (parameter.mutable && !parameter.mode)
1248
+ if (parameter.mutable && !parameter.mode) {
958
1249
  reject("Value parameters are readonly.", parameter.span);
1250
+ }
959
1251
  }
960
- for (const local of fn.locals)
1252
+ for (const local of fn.locals) {
961
1253
  this.checkVariable(local, ["local"]);
1254
+ }
962
1255
  }
963
1256
  for (const block of module.blocks) {
964
1257
  this.claimId(block.id, block.span);
965
1258
  for (const input of block.inputs) {
966
1259
  this.checkVariable(input, ["parameter"], true);
967
- if (!input.mode && input.mutable)
1260
+ if (!input.mode && input.mutable) {
968
1261
  reject("Value block inputs are readonly.", input.span);
1262
+ }
969
1263
  }
970
- for (const output of block.outputs)
1264
+ for (const output of block.outputs) {
971
1265
  this.checkVariable(output, ["blockOutput"]);
972
- for (const state of block.state)
1266
+ }
1267
+ for (const state of block.state) {
973
1268
  this.checkVariable(state, ["field", "instance"]);
974
- for (const local of block.locals)
1269
+ }
1270
+ for (const local of block.locals) {
975
1271
  this.checkVariable(local, ["local"]);
1272
+ }
976
1273
  for (const ports of [block.inputs, block.outputs]) {
977
- if (new Set(ports.map((variable) => variable.name)).size !== ports.length)
1274
+ if (new Set(ports.map((variable) => variable.name)).size !== ports.length) {
978
1275
  reject("Block input and output names must each be unique within their schema.", block.span);
1276
+ }
979
1277
  }
980
1278
  const result = block.result ? this.types.get(block.result) : undefined;
981
- if (block.outputs.length ? result?.kind !== "record" || !this.isValueType(result.id) || result.fields.length !== block.outputs.length || result.fields.some((field) => !block.outputs.some((output) => output.name === field.name && output.type === field.type)) : Boolean(block.result))
1279
+ if (block.outputs.length ? result?.kind !== "record" || !this.isValueType(result.id) || result.fields.length !== block.outputs.length || result.fields.some((field) => !block.outputs.some((output) => output.name === field.name && output.type === field.type)) : Boolean(block.result)) {
982
1280
  reject("Block output schema differs from its result record.", block.span);
1281
+ }
983
1282
  if (block.standard) {
984
- const expected = Object.hasOwn(standardBlocks, block.standard) ? standardBlocks[block.standard] : undefined;
985
- const matches = (variables, schema) => variables.length === schema.length && schema.every(([name, , type]) => variables.some((variable) => variable.name === name && variable.type === type && !variable.mode && !variable.retain));
986
- if (!expected || block.name !== block.standard || block.body.length || block.state.length || block.locals.length || !matches(block.inputs, expected.inputs) || !matches(block.outputs, expected.outputs) || block.outputs.some(({ initial }) => {
987
- switch (initial?.kind) {
988
- case "bool":
989
- return initial.value !== false;
990
- case "duration":
991
- return initial.nanoseconds !== "0";
992
- case "integer":
993
- return initial.value !== "0";
994
- default:
995
- return true;
996
- }
997
- }))
998
- reject("Invalid canonical standard block definition.", block.span);
1283
+ checkStandardBlock(block, block.standard);
999
1284
  }
1000
1285
  }
1001
- for (const type of this.types.values())
1286
+ for (const type of this.types.values()) {
1002
1287
  if (type.kind === "block") {
1003
1288
  const definition = this.blocks.get(type.block);
1004
- if (!definition || definition.result !== type.output)
1289
+ if (!definition || definition.result !== type.output) {
1005
1290
  reject("Block type differs from its definition.");
1291
+ }
1006
1292
  }
1293
+ }
1007
1294
  }
1008
1295
  hasId(id) {
1009
1296
  return this.ids.has(id);
1010
1297
  }
1011
1298
  claimId(id, span) {
1012
- if (this.ids.has(id))
1299
+ if (this.ids.has(id)) {
1013
1300
  reject(`Duplicate symbol ${id}.`, span);
1301
+ }
1014
1302
  this.ids.add(id);
1015
1303
  }
1016
1304
  isValueType(id, seen = new Set) {
1017
- if (seen.has(id))
1305
+ if (seen.has(id)) {
1018
1306
  return true;
1307
+ }
1019
1308
  seen.add(id);
1020
1309
  const type = this.types.get(id);
1021
1310
  return Boolean(type && type.kind !== "block" && (type.kind !== "record" || type.fields.every((field) => !field.mode && this.isValueType(field.type, seen))) && (type.kind !== "array" || this.isValueType(type.element, seen)));
@@ -1023,56 +1312,60 @@ class ModuleDeclarations {
1023
1312
  checkVariable(item, storage, allowBorrow = false) {
1024
1313
  this.claimId(item.id, item.span);
1025
1314
  const type = this.types.get(item.type);
1026
- if (!type || !storage.includes(item.storage))
1315
+ if (!type || !storage.includes(item.storage)) {
1027
1316
  reject("Invalid storage type or class.", item.span);
1028
- if (item.mode && (item.mode !== "inOut" || !allowBorrow || !item.mutable || item.storage !== "parameter"))
1317
+ }
1318
+ if (item.mode && (item.mode !== "inOut" || !allowBorrow || !item.mutable || item.storage !== "parameter")) {
1029
1319
  reject("InOut belongs only on mutable parameters.", item.span);
1320
+ }
1030
1321
  const mutableState = item.mutable || type.kind === "array" || type.kind === "record" && type.fields.some((field) => !field.readonly);
1031
- if (item.retain && !(item.storage === "instance" || ["module", "field"].includes(item.storage) && mutableState))
1322
+ if (item.retain && !(item.storage === "instance" || ["module", "field"].includes(item.storage) && mutableState)) {
1032
1323
  reject("Only mutable static state or block instances may retain.", item.span);
1324
+ }
1033
1325
  if (item.storage === "instance") {
1034
1326
  const instanced = instancedBlock(item.type, this.types);
1035
- if (!instanced || !this.blocks.has(instanced.block) || item.initial || item.mode)
1327
+ if (!instanced || !this.blocks.has(instanced.block) || item.initial || item.mode) {
1036
1328
  reject("Instances require a known static block and cannot have value initializers.", item.span);
1037
- } else if (!this.isValueType(item.type) && !(allowBorrow && item.mode === "inOut" && type.kind === "block"))
1329
+ }
1330
+ } else if (!this.isValueType(item.type) && !(allowBorrow && item.mode === "inOut" && type.kind === "block")) {
1038
1331
  reject("Block instances and reference schemas cannot be stored as values.", item.span);
1039
- if (item.storage === "parameter" && item.initial)
1332
+ }
1333
+ if (item.storage === "parameter" && item.initial) {
1040
1334
  reject("Inputs are supplied at each invocation and cannot have stored initializers.", item.span);
1041
- if (item.initial && !valueFits(item.initial, type, this.types))
1335
+ }
1336
+ if (item.initial && !valueFits(item.initial, type, this.types)) {
1042
1337
  reject("Initializer has the wrong type or is out of range.", item.span);
1043
- if (["module", "field", "constant", "blockOutput"].includes(item.storage) && !item.initial)
1338
+ }
1339
+ if (["module", "field", "constant", "blockOutput"].includes(item.storage) && !item.initial) {
1044
1340
  reject("Persistent storage requires initialization.", item.span);
1045
- if (["input", "constant", "blockOutput"].includes(item.storage) && item.mutable)
1341
+ }
1342
+ if (["input", "constant", "blockOutput"].includes(item.storage) && item.mutable) {
1046
1343
  reject("Readonly storage marked mutable.", item.span);
1344
+ }
1047
1345
  }
1048
1346
  }
1049
1347
 
1050
- // packages/compiler/ir/allocation.ts
1348
+ // packages/compiler/src/ir/allocation.ts
1051
1349
  function checkStaticAllocation(module, declarations) {
1052
- const { types, blocks } = declarations;
1053
- const payloads = new Map;
1054
- const payload = (id) => {
1055
- const cached = payloads.get(id);
1056
- if (cached !== undefined)
1057
- return cached;
1058
- const type = types.get(id);
1059
- const size = type.kind === "array" ? type.length * payload(type.element) : type.kind === "record" ? type.fields.reduce((sum, field) => sum + payload(field.type), 0) : 1;
1060
- payloads.set(id, size);
1061
- return size;
1062
- };
1350
+ const { types, blocks, layoutSizes } = declarations;
1351
+ const payload = (id) => layoutSizes.get(id);
1063
1352
  const instanceSize = (id) => {
1064
1353
  const type = types.get(id);
1065
1354
  return type.kind === "array" ? type.length * instanceSize(type.element) : allocation(type.kind === "block" ? type.block : "").size;
1066
1355
  };
1067
- const allocations = new Map, allocating = new Set;
1356
+ const allocations = new Map;
1357
+ const allocating = new Set;
1068
1358
  const allocation = (id) => {
1069
- if (allocating.size >= 64)
1070
- reject("Static block allocation nesting exceeds 64 levels.", blocks.get(id)?.span);
1071
- if (allocating.has(id))
1359
+ if (allocating.size >= maxNestingDepth) {
1360
+ reject(`Static block allocation nesting exceeds ${maxNestingDepth} levels.`, blocks.get(id)?.span);
1361
+ }
1362
+ if (allocating.has(id)) {
1072
1363
  reject("Recursive static block allocation.", blocks.get(id)?.span);
1364
+ }
1073
1365
  const cached = allocations.get(id);
1074
- if (cached)
1366
+ if (cached) {
1075
1367
  return cached;
1368
+ }
1076
1369
  allocating.add(id);
1077
1370
  const block = blocks.get(id);
1078
1371
  const children = block.state.filter((item) => item.storage === "instance").map((item) => ({
@@ -1084,34 +1377,42 @@ function checkStaticAllocation(module, declarations) {
1084
1377
  ...block.outputs,
1085
1378
  ...block.state.filter((item) => item.storage !== "instance")
1086
1379
  ].reduce((sum, item) => sum + (item.mode === "inOut" ? 1 : payload(item.type)), 1);
1087
- const size = own + children.reduce((sum, child) => sum + child.size, 0), height = children.length ? 1 + Math.max(...children.map((child) => child.height)) : 1;
1088
- if (size > 1e6 || height > 64)
1380
+ const size = own + children.reduce((sum, child) => sum + child.size, 0);
1381
+ const height = children.length ? 1 + Math.max(...children.map((child) => child.height)) : 1;
1382
+ if (size > maxScalarElements || height > maxNestingDepth) {
1089
1383
  reject("Static block allocation exceeds its finite budget.", block.span);
1384
+ }
1090
1385
  allocating.delete(id);
1091
1386
  const result = { size, height };
1092
1387
  allocations.set(id, result);
1093
1388
  return result;
1094
1389
  };
1095
- for (const block of module.blocks)
1390
+ for (const block of module.blocks) {
1096
1391
  allocation(block.id);
1392
+ }
1097
1393
  const staticPayload = module.variables.reduce((sum, variable) => {
1098
1394
  return sum + (instancedBlock(variable.type, types) ? instanceSize(variable.type) : payload(variable.type));
1099
1395
  }, 0);
1100
- if (staticPayload > 1e6)
1396
+ if (staticPayload > maxScalarElements) {
1101
1397
  reject("Static module storage exceeds one million scalar elements.");
1398
+ }
1102
1399
  }
1103
1400
 
1104
- // packages/compiler/ir/routine.ts
1105
- function join(branches, initialized) {
1106
- const falling = branches.filter((branch) => branch.flow === "fallthrough");
1107
- if (falling.length)
1401
+ // packages/compiler/src/ir/routine.ts
1402
+ var join = (branches, initialized) => {
1403
+ const [falling, ...others] = branches.filter((branch) => branch.flow === "fallthrough");
1404
+ if (falling) {
1108
1405
  return {
1109
1406
  flow: "fallthrough",
1110
- initialized: new Set([...falling[0].initialized].filter((id) => falling.every((branch) => branch.initialized.has(id))))
1407
+ initialized: new Set([...falling.initialized].filter((id) => others.every((branch) => branch.initialized.has(id))))
1111
1408
  };
1112
- const flow = branches[0].flow;
1113
- return { flow: branches.every((branch) => branch.flow === flow) ? flow : "mixed", initialized };
1114
- }
1409
+ }
1410
+ const [{ flow }] = branches;
1411
+ return {
1412
+ flow: branches.every((branch) => branch.flow === flow) ? flow : "mixed",
1413
+ initialized
1414
+ };
1415
+ };
1115
1416
 
1116
1417
  class RoutineNormalizer {
1117
1418
  declarations;
@@ -1146,17 +1447,20 @@ class RoutineNormalizer {
1146
1447
  ...parameters,
1147
1448
  ...this.owner ? [...this.owner.state, ...this.owner.outputs] : [],
1148
1449
  ...routine.locals
1149
- ])
1450
+ ]) {
1150
1451
  this.scope.set(item.id, item);
1452
+ }
1151
1453
  this.sourceScope = new Map(this.scope);
1152
1454
  this.locals = [...routine.locals];
1153
1455
  }
1154
1456
  normalize() {
1155
- if (this.block?.standard)
1457
+ if (this.block?.standard) {
1156
1458
  return { routine: { ...this.block, body: [] }, callees: this.callees };
1459
+ }
1157
1460
  const normalized = this.body(this.fn.body, new Set(this.fn.parameters.map((item) => item.id)));
1158
- if (this.fn.result && normalized.flow !== "return")
1461
+ if (this.fn.result && normalized.flow !== "return") {
1159
1462
  reject("A typed helper must return on every path.", this.fn.span);
1463
+ }
1160
1464
  const routine = this.block ? { ...this.block, locals: this.locals, body: normalized.body } : { ...this.fn, locals: this.locals, body: normalized.body };
1161
1465
  return { routine, callees: this.callees };
1162
1466
  }
@@ -1182,47 +1486,64 @@ class RoutineNormalizer {
1182
1486
  load(variable, span) {
1183
1487
  return { kind: "load", root: variable.id, type: variable.type, span };
1184
1488
  }
1489
+ receiverBlock(id) {
1490
+ const variable = this.sourceScope.get(id);
1491
+ if (variable?.storage !== "instance" && variable?.mode !== "inOut") {
1492
+ return;
1493
+ }
1494
+ return instancedBlock(variable.type, this.declarations.types)?.block;
1495
+ }
1185
1496
  verifyCall(id, arguments_, span, instance) {
1186
1497
  const called = this.declarations.signatures.get(id);
1187
- if (!called || called.parameters.length !== arguments_.length)
1498
+ if (!called || called.parameters.length !== arguments_.length) {
1188
1499
  reject("Unknown helper or wrong argument count.", span);
1500
+ }
1189
1501
  if (called.owner) {
1190
1502
  if (instance) {
1191
- const variable = this.sourceScope.get(instance);
1192
- const type = variable && instancedBlock(variable.type, this.declarations.types);
1193
- if (variable?.storage !== "instance" && variable?.mode !== "inOut" || type?.block !== called.owner.block)
1503
+ if (this.receiverBlock(instance) !== called.owner.block) {
1194
1504
  reject("Method calls require a matching static block instance.", span);
1195
- } else if (this.owner?.id !== called.owner.block)
1505
+ }
1506
+ } else if (this.owner?.id !== called.owner.block) {
1196
1507
  reject("An implicit method call requires its owning block scope.", span);
1197
- if (called.owner.access !== "public" && this.owner?.id !== called.owner.block)
1508
+ }
1509
+ if (called.owner.access !== "public" && this.owner?.id !== called.owner.block) {
1198
1510
  reject("Private and protected methods require their owning block scope.", span);
1199
- } else if (instance)
1511
+ }
1512
+ } else if (instance) {
1200
1513
  reject("Ordinary functions cannot have an instance receiver.", span);
1514
+ }
1201
1515
  this.callees.add(id);
1202
1516
  arguments_.forEach((argument, index) => {
1203
- if (argument.type !== called.parameters[index]?.type)
1517
+ if (argument.type !== called.parameters[index]?.type) {
1204
1518
  reject("Helper argument has the wrong PLC type.", argument.span);
1519
+ }
1205
1520
  });
1206
1521
  return called;
1207
1522
  }
1208
1523
  expression(value, initialized, output, allowAggregateLoad = false) {
1209
1524
  const type = this.declarations.types.get(value.type);
1210
- if (!type || !this.declarations.isValueType(value.type))
1525
+ if (!type || !this.declarations.isValueType(value.type)) {
1211
1526
  reject("Unknown or non-value expression type.", value.span);
1212
- if (value.kind === "borrow")
1527
+ }
1528
+ if (value.kind === "borrow") {
1213
1529
  reject("Borrowed places are only valid in block update arguments.", value.span);
1530
+ }
1214
1531
  const common = { type: value.type, span: value.span };
1215
1532
  if (value.kind === "length") {
1216
1533
  const array = this.declarations.types.get(value.operand.type);
1217
- if (array?.kind !== "array" || value.type !== "DINT")
1534
+ if (array?.kind !== "array" || value.type !== "DINT") {
1218
1535
  reject("Length requires a fixed array and DINT result.", value.span);
1536
+ }
1219
1537
  if (value.operand.kind === "load") {
1220
- const source = this.sourceScope.get(value.operand.place.root), checked = placeType(value.operand.place, this.declarations.types, this.sourceScope, this.ranges);
1221
- if (!source || checked.issue || checked.type !== value.operand.type || source.storage === "local" && !initialized.has(source.id))
1538
+ const source = this.sourceScope.get(value.operand.place.root);
1539
+ const checked = placeType(value.operand.place, this.declarations.types, this.sourceScope, this.ranges);
1540
+ if (!source || checked.issue || checked.type !== value.operand.type || source.storage === "local" && !initialized.has(source.id)) {
1222
1541
  reject(checked.issue ?? "Invalid array receiver.", value.span);
1542
+ }
1223
1543
  this.normalizePath(value.operand.place, initialized, output);
1224
- } else
1544
+ } else {
1225
1545
  this.expression(value.operand, initialized, output, true);
1546
+ }
1226
1547
  return {
1227
1548
  ...common,
1228
1549
  kind: "constant",
@@ -1230,13 +1551,20 @@ class RoutineNormalizer {
1230
1551
  };
1231
1552
  }
1232
1553
  if (value.kind === "conditional") {
1233
- if (value.condition.type !== "BOOL" || value.then.type !== value.type || value.else.type !== value.type)
1554
+ if (value.condition.type !== "BOOL" || value.then.type !== value.type || value.else.type !== value.type) {
1234
1555
  reject("Invalid conditional types.", value.span);
1235
- const condition = this.expression(value.condition, initialized, output), result = this.temporary(value.type, value.span);
1556
+ }
1557
+ const condition = this.expression(value.condition, initialized, output);
1558
+ const result = this.temporary(value.type, value.span);
1236
1559
  const branch = (operand) => {
1237
1560
  const statements = [];
1238
1561
  const evaluated = this.expression(operand, new Set(initialized), statements);
1239
- statements.push({ kind: "assign", root: result.id, value: evaluated, span: value.span });
1562
+ statements.push({
1563
+ kind: "assign",
1564
+ root: result.id,
1565
+ value: evaluated,
1566
+ span: value.span
1567
+ });
1240
1568
  return statements;
1241
1569
  };
1242
1570
  output.push({
@@ -1251,8 +1579,9 @@ class RoutineNormalizer {
1251
1579
  }
1252
1580
  if (value.kind === "call") {
1253
1581
  const called = this.verifyCall(value.function, value.arguments, value.span, value.instance);
1254
- if (called.result !== value.type)
1582
+ if (called.result !== value.type) {
1255
1583
  reject("Expression call requires a matching result type.", value.span);
1584
+ }
1256
1585
  const index = value.instance && this.instanceIndex(value.instance, value.index, initialized, output, value.span);
1257
1586
  const arguments_ = this.arguments(called.parameters, value.arguments, initialized, output);
1258
1587
  const result = this.temporary(value.type, value.span);
@@ -1269,8 +1598,9 @@ class RoutineNormalizer {
1269
1598
  return this.load(result, value.span);
1270
1599
  }
1271
1600
  const issue = expressionIssue(value, this.declarations.types, this.scope, this.ranges);
1272
- if (issue)
1601
+ if (issue) {
1273
1602
  reject(issue, value.span);
1603
+ }
1274
1604
  switch (value.kind) {
1275
1605
  case "copy":
1276
1606
  return this.expression(value.operand, initialized, output, true);
@@ -1278,7 +1608,7 @@ class RoutineNormalizer {
1278
1608
  case "array": {
1279
1609
  const result = this.temporary(value.type, value.span);
1280
1610
  if (value.kind === "record") {
1281
- for (const [name, operand] of Object.entries(value.fields))
1611
+ for (const [name, operand] of Object.entries(value.fields)) {
1282
1612
  output.push({
1283
1613
  kind: "assign",
1284
1614
  root: result.id,
@@ -1286,10 +1616,11 @@ class RoutineNormalizer {
1286
1616
  value: this.expression(operand, initialized, output),
1287
1617
  span: operand.span
1288
1618
  });
1619
+ }
1289
1620
  } else {
1290
- const array = this.declarations.types.get(value.type);
1291
- if (array.kind !== "array")
1621
+ if (type.kind !== "array") {
1292
1622
  reject("Invalid array construction.", value.span);
1623
+ }
1293
1624
  value.items.forEach((operand, index) => {
1294
1625
  output.push({
1295
1626
  kind: "assign",
@@ -1300,7 +1631,10 @@ class RoutineNormalizer {
1300
1631
  value: {
1301
1632
  kind: "constant",
1302
1633
  type: "DINT",
1303
- value: { kind: "integer", value: String(array.lowerBound + index) },
1634
+ value: {
1635
+ kind: "integer",
1636
+ value: String(type.lowerBound + index)
1637
+ },
1304
1638
  span: operand.span
1305
1639
  }
1306
1640
  }
@@ -1314,8 +1648,9 @@ class RoutineNormalizer {
1314
1648
  return this.load(result, value.span);
1315
1649
  }
1316
1650
  case "constant": {
1317
- if (!aggregate(type))
1651
+ if (!aggregate(type)) {
1318
1652
  return { ...common, kind: "constant", value: value.value };
1653
+ }
1319
1654
  const result = this.temporary(value.type, value.span);
1320
1655
  output.push({
1321
1656
  kind: "assign",
@@ -1327,13 +1662,17 @@ class RoutineNormalizer {
1327
1662
  return this.load(result, value.span);
1328
1663
  }
1329
1664
  case "load": {
1330
- const source = this.sourceScope.get(value.place.root), checked = placeType(value.place, this.declarations.types, this.sourceScope, this.ranges);
1331
- if (!source || checked.issue || checked.type !== value.type)
1665
+ const source = this.sourceScope.get(value.place.root);
1666
+ const checked = placeType(value.place, this.declarations.types, this.sourceScope, this.ranges);
1667
+ if (!source || checked.issue || checked.type !== value.type) {
1332
1668
  reject(checked.issue ?? "Invalid PLC load.", value.span);
1333
- if (aggregate(type) && !allowAggregateLoad)
1669
+ }
1670
+ if (aggregate(type) && !allowAggregateLoad) {
1334
1671
  reject("Aggregate loads require explicit copy or a readonly value argument.", value.span);
1335
- if (source.storage === "local" && !initialized.has(source.id))
1672
+ }
1673
+ if (source.storage === "local" && !initialized.has(source.id)) {
1336
1674
  reject("Local read before initialization.", value.span);
1675
+ }
1337
1676
  const first = value.place.path[0];
1338
1677
  if (source.storage === "instance" && value.place.path.length === 1 && first?.kind === "field" && first.name === "out" && type.kind === "record") {
1339
1678
  const result = this.temporary(value.type, value.span);
@@ -1343,7 +1682,10 @@ class RoutineNormalizer {
1343
1682
  type: field.type,
1344
1683
  place: {
1345
1684
  root: source.id,
1346
- path: [...value.place.path, { kind: "field", name: field.name }]
1685
+ path: [
1686
+ ...value.place.path,
1687
+ { kind: "field", name: field.name }
1688
+ ]
1347
1689
  },
1348
1690
  span: value.span
1349
1691
  };
@@ -1360,38 +1702,59 @@ class RoutineNormalizer {
1360
1702
  return this.load(result, value.span);
1361
1703
  }
1362
1704
  const path = this.normalizePath(value.place, initialized, output);
1363
- if (source.storage === "constant" && source.initial && !path.length)
1705
+ if (source.storage === "constant" && source.initial && !path.length) {
1364
1706
  return { ...common, kind: "constant", value: source.initial };
1707
+ }
1365
1708
  const result = this.temporary(value.type, value.span);
1366
1709
  output.push({
1367
1710
  kind: "assign",
1368
1711
  root: result.id,
1369
- value: { ...common, kind: "load", root: source.id, ...path.length && { path } },
1712
+ value: {
1713
+ ...common,
1714
+ kind: "load",
1715
+ root: source.id,
1716
+ ...path.length && { path }
1717
+ },
1370
1718
  span: value.span
1371
1719
  });
1372
1720
  const bound = interval(value, this.declarations.types, this.scope, this.ranges);
1373
- if (bound)
1721
+ if (bound) {
1374
1722
  this.ranges.set(result.id, bound);
1723
+ }
1375
1724
  initialized.add(result.id);
1376
1725
  return this.load(result, value.span);
1377
1726
  }
1378
1727
  case "unary": {
1379
- const operand = this.expression(value.operand, initialized, output), constant = fold(value, this.scope, this.declarations.types);
1728
+ const operand = this.expression(value.operand, initialized, output);
1729
+ const constant = fold(value, this.scope, this.declarations.types);
1380
1730
  return constant ? { ...common, kind: "constant", value: constant } : { ...common, kind: "unary", operator: value.operator, operand };
1381
1731
  }
1382
1732
  case "convert": {
1383
- const operand = this.expression(value.operand, initialized, output), constant = fold(value, this.scope, this.declarations.types);
1384
- if (value.type === value.operand.type)
1733
+ const operand = this.expression(value.operand, initialized, output);
1734
+ const constant = fold(value, this.scope, this.declarations.types);
1735
+ if (value.type === value.operand.type) {
1385
1736
  return operand;
1737
+ }
1386
1738
  return constant ? { ...common, kind: "constant", value: constant } : { ...common, kind: "convert", operand, policy: value.policy };
1387
1739
  }
1388
1740
  case "binary": {
1389
1741
  const left = this.expression(value.left, initialized, output);
1390
1742
  if (value.operator === "and" || value.operator === "or") {
1391
- const result = this.temporary("BOOL", value.span), branch = [];
1392
- output.push({ kind: "assign", root: result.id, value: left, span: value.span });
1743
+ const result = this.temporary("BOOL", value.span);
1744
+ const branch = [];
1745
+ output.push({
1746
+ kind: "assign",
1747
+ root: result.id,
1748
+ value: left,
1749
+ span: value.span
1750
+ });
1393
1751
  const right = this.expression(value.right, new Set(initialized), branch);
1394
- branch.push({ kind: "assign", root: result.id, value: right, span: value.span });
1752
+ branch.push({
1753
+ kind: "assign",
1754
+ root: result.id,
1755
+ value: right,
1756
+ span: value.span
1757
+ });
1395
1758
  const condition = value.operator === "and" ? this.load(result, value.span) : {
1396
1759
  kind: "unary",
1397
1760
  operator: "not",
@@ -1409,9 +1772,11 @@ class RoutineNormalizer {
1409
1772
  initialized.add(result.id);
1410
1773
  return this.load(result, value.span);
1411
1774
  }
1412
- const right = this.expression(value.right, initialized, output), constant = fold(value, this.scope, this.declarations.types);
1413
- if (constant)
1775
+ const right = this.expression(value.right, initialized, output);
1776
+ const constant = fold(value, this.scope, this.declarations.types);
1777
+ if (constant) {
1414
1778
  return { ...common, kind: "constant", value: constant };
1779
+ }
1415
1780
  return {
1416
1781
  ...common,
1417
1782
  kind: "binary",
@@ -1424,84 +1789,101 @@ class RoutineNormalizer {
1424
1789
  }
1425
1790
  }
1426
1791
  normalizePath(place, initialized, output) {
1427
- return place.path.map((segment) => segment.kind === "field" ? segment : { kind: "index", value: this.expression(segment.value, initialized, output) });
1792
+ return place.path.map((segment) => segment.kind === "field" ? segment : {
1793
+ kind: "index",
1794
+ value: this.expression(segment.value, initialized, output)
1795
+ });
1428
1796
  }
1429
1797
  destination(place, type, initialized, span) {
1430
- const target = this.sourceScope.get(place.root), initializing = target?.storage === "local" && !initialized.has(place.root) && !place.path.length;
1798
+ const target = this.sourceScope.get(place.root);
1799
+ const initializing = target?.storage === "local" && !initialized.has(place.root) && !place.path.length;
1431
1800
  const checked = placeType(place, this.declarations.types, this.sourceScope, this.ranges, !initializing);
1432
- if (!target || checked.issue || checked.type !== type || this.counters.has(place.root))
1801
+ if (!target || checked.issue || checked.type !== type || this.counters.has(place.root)) {
1433
1802
  reject(checked.issue ?? "Invalid assignment destination.", span);
1434
- if (place.path.length && target.storage === "local" && !initialized.has(target.id))
1803
+ }
1804
+ if (place.path.length && target.storage === "local" && !initialized.has(target.id)) {
1435
1805
  reject("Initialize the whole aggregate before assigning fields.", span);
1806
+ }
1436
1807
  return target;
1437
1808
  }
1438
1809
  instanceIndex(instance, index, initialized, output, span) {
1439
- if (!index)
1810
+ if (!index) {
1440
1811
  return;
1812
+ }
1441
1813
  const checked = placeType({ root: instance, path: [{ kind: "index", value: index }] }, this.declarations.types, this.sourceScope, this.ranges);
1442
- if (checked.issue)
1814
+ if (checked.issue) {
1443
1815
  reject(checked.issue, span);
1816
+ }
1444
1817
  return this.expression(index, initialized, output);
1445
1818
  }
1446
1819
  blockUpdate(item, initialized, output) {
1447
- const instance = this.sourceScope.get(item.instance), type = instance && instancedBlock(instance.type, this.declarations.types);
1448
- const called = type && this.declarations.blocks.get(type.block);
1449
- if (instance?.storage !== "instance" && instance?.mode !== "inOut" || !called)
1820
+ const block = this.receiverBlock(item.instance);
1821
+ const called = block && this.declarations.blocks.get(block);
1822
+ if (!called) {
1450
1823
  reject("Updates require a statically allocated block instance.", item.span);
1824
+ }
1451
1825
  const index = this.instanceIndex(item.instance, item.index, initialized, output, item.span);
1452
- const keys = Object.keys(item.inputs);
1453
- if (keys.length !== called.inputs.length || called.inputs.some((input) => !Object.hasOwn(item.inputs, input.name)))
1826
+ const supplied = Object.entries(item.inputs).flatMap(([name, value]) => {
1827
+ const input = called.inputs.find((port) => port.name === name);
1828
+ return input ? [{ input, value }] : [];
1829
+ });
1830
+ if (Object.keys(item.inputs).length !== called.inputs.length || supplied.length !== called.inputs.length) {
1454
1831
  reject("Block update must supply every named input exactly once.", item.span);
1832
+ }
1455
1833
  this.callees.add(called.id);
1456
- const arguments_ = this.arguments(keys.map((name) => called.inputs.find((input) => input.name === name)), keys.map((name) => item.inputs[name]), initialized, output);
1457
- const inputs = Object.fromEntries(keys.map((name, index) => [name, arguments_[index]]));
1834
+ const inputs = Object.fromEntries(supplied.map(({ input, value }) => [
1835
+ input.name,
1836
+ this.argument(input, value, initialized, output)
1837
+ ]));
1458
1838
  output.push({
1459
1839
  kind: "blockUpdate",
1460
- instance: instance.id,
1840
+ instance: item.instance,
1461
1841
  ...index && { index },
1462
1842
  inputs,
1463
1843
  span: item.span
1464
1844
  });
1465
1845
  }
1466
1846
  arguments(parameters, values, initialized, output) {
1467
- const arguments_ = [];
1468
- for (const [index, value] of values.entries()) {
1469
- const input = parameters[index];
1470
- if (value.type !== input.type)
1471
- reject("Block input differs from its concrete PLC type.", value.span);
1472
- const block = this.declarations.types.get(value.type)?.kind === "block";
1473
- if (input.mode === "inOut" && value.kind !== "borrow") {
1474
- if (block)
1475
- reject("Pass a block instance by name.", value.span);
1476
- const temporary = this.temporary(value.type, value.span);
1477
- output.push({
1478
- kind: "assign",
1479
- root: temporary.id,
1480
- value: this.expression(value, initialized, output),
1481
- span: value.span
1482
- });
1483
- initialized.add(temporary.id);
1484
- arguments_.push({
1485
- kind: "borrow",
1486
- type: value.type,
1487
- place: { root: temporary.id, path: [] },
1488
- span: value.span
1489
- });
1490
- } else if (input.mode === "inOut" && value.kind === "borrow") {
1491
- arguments_.push(this.borrow(value, initialized, output));
1492
- } else {
1493
- if (value.kind === "borrow")
1494
- reject("Readonly value inputs cannot receive borrowed references.", value.span);
1495
- arguments_.push(this.expression(value, initialized, output, true));
1847
+ return values.map((value, index) => this.argument(parameters[index], value, initialized, output));
1848
+ }
1849
+ argument(input, value, initialized, output) {
1850
+ if (value.type !== input.type) {
1851
+ reject("Block input differs from its concrete PLC type.", value.span);
1852
+ }
1853
+ if (input.mode === "inOut" && value.kind === "borrow") {
1854
+ return this.borrow(value, initialized, output);
1855
+ }
1856
+ if (input.mode === "inOut") {
1857
+ if (this.declarations.types.get(value.type)?.kind === "block") {
1858
+ reject("Pass a block instance by name.", value.span);
1496
1859
  }
1860
+ const temporary = this.temporary(value.type, value.span);
1861
+ output.push({
1862
+ kind: "assign",
1863
+ root: temporary.id,
1864
+ value: this.expression(value, initialized, output),
1865
+ span: value.span
1866
+ });
1867
+ initialized.add(temporary.id);
1868
+ return {
1869
+ kind: "borrow",
1870
+ type: value.type,
1871
+ place: { root: temporary.id, path: [] },
1872
+ span: value.span
1873
+ };
1497
1874
  }
1498
- return arguments_;
1875
+ if (value.kind === "borrow") {
1876
+ reject("Readonly value inputs cannot receive borrowed references.", value.span);
1877
+ }
1878
+ return this.expression(value, initialized, output, true);
1499
1879
  }
1500
1880
  borrow(value, initialized, output) {
1501
1881
  const block = this.declarations.types.get(value.type)?.kind === "block";
1502
- const root = this.sourceScope.get(value.place.root), checked = placeType(value.place, this.declarations.types, this.sourceScope, this.ranges, !block);
1503
- if (!root || checked.issue || checked.type !== value.type || !block && !this.declarations.isValueType(value.type) || this.counters.has(root.id) || root.storage === "local" && !initialized.has(root.id))
1882
+ const root = this.sourceScope.get(value.place.root);
1883
+ const checked = placeType(value.place, this.declarations.types, this.sourceScope, this.ranges, !block);
1884
+ if (!root || checked.issue || checked.type !== value.type || !block && !this.declarations.isValueType(value.type) || this.counters.has(root.id) || root.storage === "local" && !initialized.has(root.id)) {
1504
1885
  reject(checked.issue ?? "Borrow requires initialized mutable value storage of the exact type.", value.span);
1886
+ }
1505
1887
  return {
1506
1888
  kind: "borrow",
1507
1889
  type: value.type,
@@ -1512,432 +1894,547 @@ class RoutineNormalizer {
1512
1894
  span: value.span
1513
1895
  };
1514
1896
  }
1515
- body(statements, initialized, inLoop = false) {
1897
+ body(statements, initialized) {
1516
1898
  const output = [];
1517
- let flow = "fallthrough";
1899
+ let state = { flow: "fallthrough", initialized };
1518
1900
  for (const item of statements) {
1519
- if (flow !== "fallthrough")
1901
+ if (state.flow !== "fallthrough") {
1520
1902
  break;
1521
- switch (item.kind) {
1522
- case "assign": {
1523
- this.destination(item.destination, item.value.type, initialized, item.span);
1524
- const path = this.normalizePath(item.destination, initialized, output);
1525
- const bound = !path.length && this.scope.get(item.destination.root)?.mutable === false && valueRange(item.value, this.declarations.types, this.scope, this.ranges, this.declarations.signatures);
1526
- const value = this.expression(item.value, initialized, output);
1527
- if (bound)
1528
- this.ranges.set(item.destination.root, bound);
1529
- if (!path.length)
1530
- initialized.add(item.destination.root);
1531
- output.push({
1532
- kind: "assign",
1533
- root: item.destination.root,
1534
- ...path.length && { path },
1535
- value,
1536
- span: item.span
1537
- });
1538
- break;
1903
+ }
1904
+ state = this.statement(item, state.initialized, output);
1905
+ }
1906
+ return { body: output, ...state };
1907
+ }
1908
+ statement(item, initialized, output) {
1909
+ switch (item.kind) {
1910
+ case "assign":
1911
+ this.assign(item, initialized, output);
1912
+ return { flow: "fallthrough", initialized };
1913
+ case "blockUpdate":
1914
+ this.blockUpdate(item, initialized, output);
1915
+ return { flow: "fallthrough", initialized };
1916
+ case "invoke":
1917
+ this.invoke(item, initialized, output);
1918
+ return { flow: "fallthrough", initialized };
1919
+ case "if":
1920
+ return this.ifStatement(item, initialized, output);
1921
+ case "switch":
1922
+ return this.switchStatement(item, initialized, output);
1923
+ case "for":
1924
+ this.forStatement(item, initialized, output);
1925
+ return { flow: "fallthrough", initialized };
1926
+ case "return": {
1927
+ if (item.value?.type !== this.fn.result) {
1928
+ reject("Return differs from the function signature.", item.span);
1539
1929
  }
1540
- case "blockUpdate": {
1541
- this.blockUpdate(item, initialized, output);
1542
- break;
1930
+ const value = item.value && this.expression(item.value, initialized, output);
1931
+ output.push({
1932
+ kind: "return",
1933
+ span: item.span,
1934
+ ...value && { value }
1935
+ });
1936
+ return { flow: "return", initialized };
1937
+ }
1938
+ case "telemetry":
1939
+ this.telemetry(item, initialized, output);
1940
+ return { flow: "fallthrough", initialized };
1941
+ case "break":
1942
+ case "continue":
1943
+ if (!this.counters.size) {
1944
+ reject("Loop control appears outside a bounded loop.", item.span);
1543
1945
  }
1544
- case "invoke": {
1545
- const called = this.verifyCall(item.function, item.arguments, item.span, item.instance);
1546
- if (item.destination) {
1547
- if (item.destination.path.length || !called.result)
1548
- reject("Invalid helper destination.", item.span);
1549
- this.destination(item.destination, called.result, initialized, item.span);
1550
- }
1551
- const index = item.instance && this.instanceIndex(item.instance, item.index, initialized, output, item.span);
1552
- const arguments_ = this.arguments(called.parameters, item.arguments, initialized, output);
1553
- output.push({
1554
- kind: "invoke",
1555
- function: item.function,
1556
- ...item.instance && { instance: item.instance },
1557
- ...index && { index },
1558
- arguments: arguments_,
1559
- span: item.span,
1560
- ...item.destination && { destination: item.destination.root }
1561
- });
1562
- if (item.destination)
1563
- initialized.add(item.destination.root);
1564
- break;
1946
+ output.push({ kind: item.kind, span: item.span });
1947
+ return { flow: "loop", initialized };
1948
+ default:
1949
+ reject("Unknown PLC statement.");
1950
+ }
1951
+ }
1952
+ assign(item, initialized, output) {
1953
+ this.destination(item.destination, item.value.type, initialized, item.span);
1954
+ const path = this.normalizePath(item.destination, initialized, output);
1955
+ const bound = !path.length && this.scope.get(item.destination.root)?.mutable === false && valueRange(item.value, this.declarations.types, this.scope, this.ranges, this.declarations.signatures);
1956
+ const value = this.expression(item.value, initialized, output);
1957
+ if (bound) {
1958
+ this.ranges.set(item.destination.root, bound);
1959
+ }
1960
+ if (!path.length) {
1961
+ initialized.add(item.destination.root);
1962
+ }
1963
+ output.push({
1964
+ kind: "assign",
1965
+ root: item.destination.root,
1966
+ ...path.length && { path },
1967
+ value,
1968
+ span: item.span
1969
+ });
1970
+ }
1971
+ invoke(item, initialized, output) {
1972
+ const called = this.verifyCall(item.function, item.arguments, item.span, item.instance);
1973
+ if (item.destination) {
1974
+ if (item.destination.path.length || !called.result) {
1975
+ reject("Invalid helper destination.", item.span);
1976
+ }
1977
+ this.destination(item.destination, called.result, initialized, item.span);
1978
+ }
1979
+ const index = item.instance && this.instanceIndex(item.instance, item.index, initialized, output, item.span);
1980
+ const arguments_ = this.arguments(called.parameters, item.arguments, initialized, output);
1981
+ output.push({
1982
+ kind: "invoke",
1983
+ function: item.function,
1984
+ ...item.instance && { instance: item.instance },
1985
+ ...index && { index },
1986
+ arguments: arguments_,
1987
+ span: item.span,
1988
+ ...item.destination && { destination: item.destination.root }
1989
+ });
1990
+ if (item.destination) {
1991
+ initialized.add(item.destination.root);
1992
+ }
1993
+ }
1994
+ ifStatement(item, initialized, output) {
1995
+ if (item.condition.type !== "BOOL") {
1996
+ reject("Conditions require BOOL.", item.span);
1997
+ }
1998
+ const condition = this.expression(item.condition, initialized, output);
1999
+ const originalRanges = new Map(this.ranges);
2000
+ const branch = (statements, truth) => {
2001
+ this.ranges.clear();
2002
+ for (const [root, range] of narrowRanges(item.condition, truth, this.declarations.types, this.sourceScope, originalRanges)) {
2003
+ this.ranges.set(root, range);
2004
+ }
2005
+ try {
2006
+ return this.body(statements, new Set(initialized));
2007
+ } finally {
2008
+ this.ranges.clear();
2009
+ for (const [root, range] of originalRanges) {
2010
+ this.ranges.set(root, range);
1565
2011
  }
1566
- case "if": {
1567
- if (item.condition.type !== "BOOL")
1568
- reject("Conditions require BOOL.", item.span);
1569
- const condition = this.expression(item.condition, initialized, output);
1570
- const originalRanges = new Map(this.ranges);
1571
- const branch = (statements, truth) => {
1572
- this.ranges.clear();
1573
- for (const [root, range] of narrowRanges(item.condition, truth, this.declarations.types, this.sourceScope, originalRanges))
1574
- this.ranges.set(root, range);
1575
- try {
1576
- return this.body(statements, new Set(initialized), inLoop);
1577
- } finally {
1578
- this.ranges.clear();
1579
- for (const [root, range] of originalRanges)
1580
- this.ranges.set(root, range);
1581
- }
1582
- };
1583
- const yes = branch(item.then, true), no = branch(item.else, false);
1584
- ({ flow, initialized } = join([yes, no], initialized));
1585
- output.push({
1586
- kind: "if",
1587
- condition,
1588
- then: yes.body,
1589
- else: no.body,
1590
- span: item.span
1591
- });
1592
- break;
2012
+ }
2013
+ };
2014
+ const yes = branch(item.then, true);
2015
+ const no = branch(item.else, false);
2016
+ output.push({
2017
+ kind: "if",
2018
+ condition,
2019
+ then: yes.body,
2020
+ else: no.body,
2021
+ span: item.span
2022
+ });
2023
+ return join([yes, no], initialized);
2024
+ }
2025
+ switchStatement(item, initialized, output) {
2026
+ const value = this.expression(item.value, initialized, output);
2027
+ const type = this.declarations.types.get(item.value.type);
2028
+ const seen = new Set;
2029
+ const cases = item.cases.map((branch) => {
2030
+ for (const constant of branch.values) {
2031
+ if (!valueFits(constant, type, this.declarations.types)) {
2032
+ reject("Invalid case constant.", item.span);
1593
2033
  }
1594
- case "switch": {
1595
- const value = this.expression(item.value, initialized, output), seen = new Set;
1596
- const branches = item.cases.map((branch) => {
1597
- for (const constant of branch.values) {
1598
- if (!valueFits(constant, this.declarations.types.get(item.value.type), this.declarations.types))
1599
- reject("Invalid case constant.", item.span);
1600
- const key = JSON.stringify(constant);
1601
- if (seen.has(key))
1602
- reject("Duplicate case constant.", item.span);
1603
- seen.add(key);
1604
- }
1605
- return {
1606
- values: branch.values,
1607
- result: this.body(branch.body, new Set(initialized), inLoop)
1608
- };
1609
- });
1610
- const fallback = this.body(item.fallback, new Set(initialized), inLoop);
1611
- ({ flow, initialized } = join([...branches.map((branch) => branch.result), fallback], initialized));
1612
- output.push({
1613
- kind: "switch",
1614
- value,
1615
- cases: branches.map((branch) => ({ values: branch.values, body: branch.result.body })),
1616
- fallback: fallback.body,
1617
- span: item.span
1618
- });
1619
- break;
2034
+ const key = JSON.stringify(constant);
2035
+ if (seen.has(key)) {
2036
+ reject("Duplicate case constant.", item.span);
1620
2037
  }
1621
- case "for": {
1622
- const counter = this.sourceScope.get(item.counter);
1623
- const counterType = counter && this.declarations.types.get(counter.type);
1624
- if (!counter || !(item.counterScope === "existing" ? ["local", "module", "field"].includes(counter.storage) : counter.storage === "local") || !counter.mutable || counterType?.kind !== "integer" || this.counters.has(counter.id) || item.start.type !== counter.type || item.limit.type !== counter.type || !/^(-?[1-9][0-9]*)$/.test(item.step))
1625
- reject("Invalid bounded loop.", item.span);
1626
- const start = fold(item.start, this.scope, this.declarations.types);
1627
- const limit = fold(item.limit, this.scope, this.declarations.types);
1628
- const startRange = interval(item.start, this.declarations.types, this.sourceScope, this.ranges);
1629
- const limitRange = interval(item.limit, this.declarations.types, this.sourceScope, this.ranges);
1630
- if (!startRange || !limitRange)
1631
- reject("Loop bounds require finite integer ranges.", item.span);
1632
- const step = BigInt(item.step);
1633
- const proof = loopBounds(startRange, limitRange, step, item.exclusive);
1634
- const dynamic = start?.kind !== "integer" || limit?.kind !== "integer";
1635
- const { first, last, count } = proof;
1636
- if (count > 1000000n || Number(count) !== item.maxIterations || !Number.isSafeInteger(item.maxIterations))
1637
- reject("Loop iteration proof differs from its bounds.", item.span);
1638
- if (item.counterScope === "existing") {
1639
- const terminal = dynamic ? (step > 0n ? proof.range[1] : proof.range[0]) + step : first + count * step;
1640
- const [minimum, maximum] = integerRange(counterType);
1641
- if (count > 0n && (terminal < minimum || terminal > maximum))
1642
- reject("The existing loop counter overflows on termination.", item.span);
1643
- }
1644
- const evaluatedStart = this.expression(item.start, initialized, output);
1645
- const evaluatedLimit = this.expression(item.limit, initialized, output);
1646
- initialized.add(counter.id);
1647
- this.counters.add(counter.id);
1648
- this.ranges.set(counter.id, proof.range);
1649
- const nested = this.body(item.body, new Set(initialized), true);
1650
- this.counters.delete(counter.id);
1651
- this.ranges.delete(counter.id);
1652
- if (item.counterScope !== "existing")
1653
- initialized.delete(counter.id);
1654
- output.push({
1655
- kind: "for",
1656
- counter: counter.id,
1657
- ...item.counterScope && { counterScope: item.counterScope },
1658
- start: { kind: "integer", value: String(first) },
1659
- limit: { kind: "integer", value: String(last) },
1660
- ...dynamic && {
1661
- dynamic: {
1662
- start: evaluatedStart,
1663
- limit: evaluatedLimit,
1664
- ...item.exclusive && { exclusive: item.exclusive }
1665
- }
1666
- },
1667
- step: item.step,
1668
- maxIterations: item.maxIterations,
1669
- body: nested.body,
1670
- span: item.span
1671
- });
1672
- break;
2038
+ seen.add(key);
2039
+ }
2040
+ return {
2041
+ values: branch.values,
2042
+ result: this.body(branch.body, new Set(initialized))
2043
+ };
2044
+ });
2045
+ const fallback = this.body(item.fallback, new Set(initialized));
2046
+ output.push({
2047
+ kind: "switch",
2048
+ value,
2049
+ cases: cases.map((branch) => ({
2050
+ values: branch.values,
2051
+ body: branch.result.body
2052
+ })),
2053
+ fallback: fallback.body,
2054
+ span: item.span
2055
+ });
2056
+ return join([fallback, ...cases.map((branch) => branch.result)], initialized);
2057
+ }
2058
+ forStatement(item, initialized, output) {
2059
+ const counter = this.sourceScope.get(item.counter);
2060
+ const counterType = counter && this.declarations.types.get(counter.type);
2061
+ const storage = item.counterScope === "existing" ? ["local", "module", "field"] : ["local"];
2062
+ if (!counter || !storage.includes(counter.storage) || !counter.mutable || counterType?.kind !== "integer" || this.counters.has(counter.id) || item.start.type !== counter.type || item.limit.type !== counter.type || !canonicalInteger.test(item.step) || item.step === "0") {
2063
+ reject("Invalid bounded loop.", item.span);
2064
+ }
2065
+ const start = fold(item.start, this.scope, this.declarations.types);
2066
+ const limit = fold(item.limit, this.scope, this.declarations.types);
2067
+ const startRange = interval(item.start, this.declarations.types, this.sourceScope, this.ranges);
2068
+ const limitRange = interval(item.limit, this.declarations.types, this.sourceScope, this.ranges);
2069
+ if (!startRange || !limitRange) {
2070
+ reject("Loop bounds require finite integer ranges.", item.span);
2071
+ }
2072
+ const step = BigInt(item.step);
2073
+ const { first, last, count, range } = loopBounds(startRange, limitRange, step, item.exclusive);
2074
+ const dynamic = start?.kind !== "integer" || limit?.kind !== "integer";
2075
+ if (count > maxLoopIterations || Number(count) !== item.maxIterations || !Number.isSafeInteger(item.maxIterations)) {
2076
+ reject("Loop iteration proof differs from its bounds.", item.span);
2077
+ }
2078
+ if (item.counterScope === "existing") {
2079
+ const lastValue = step > 0n ? range[1] : range[0];
2080
+ const terminal = dynamic ? lastValue + step : first + count * step;
2081
+ if (count > 0n && !admits(integerRange(counterType), terminal)) {
2082
+ reject("The existing loop counter overflows on termination.", item.span);
2083
+ }
2084
+ }
2085
+ const evaluatedStart = this.expression(item.start, initialized, output);
2086
+ const evaluatedLimit = this.expression(item.limit, initialized, output);
2087
+ initialized.add(counter.id);
2088
+ this.counters.add(counter.id);
2089
+ this.ranges.set(counter.id, range);
2090
+ const nested = this.body(item.body, new Set(initialized));
2091
+ this.counters.delete(counter.id);
2092
+ this.ranges.delete(counter.id);
2093
+ if (item.counterScope !== "existing") {
2094
+ initialized.delete(counter.id);
2095
+ }
2096
+ output.push({
2097
+ kind: "for",
2098
+ counter: counter.id,
2099
+ ...item.counterScope && { counterScope: item.counterScope },
2100
+ start: { kind: "integer", value: String(first) },
2101
+ limit: { kind: "integer", value: String(last) },
2102
+ ...dynamic && {
2103
+ dynamic: {
2104
+ start: evaluatedStart,
2105
+ limit: evaluatedLimit,
2106
+ ...item.exclusive && { exclusive: item.exclusive }
1673
2107
  }
1674
- case "return": {
1675
- if (item.value?.type !== this.fn.result)
1676
- reject("Return differs from the function signature.", item.span);
1677
- const value = item.value && this.expression(item.value, initialized, output);
1678
- output.push({ kind: "return", span: item.span, ...value && { value } });
1679
- flow = "return";
1680
- break;
2108
+ },
2109
+ step: item.step,
2110
+ maxIterations: item.maxIterations,
2111
+ body: nested.body,
2112
+ span: item.span
2113
+ });
2114
+ }
2115
+ telemetry(item, initialized, output) {
2116
+ const evaluate = (value) => this.expression(value, initialized, output);
2117
+ const { record } = item;
2118
+ output.push({
2119
+ kind: "telemetry",
2120
+ record: record.kind === "exception" ? { kind: "exception", code: evaluate(record.code) } : record,
2121
+ properties: item.properties.map(({ name, value, length }) => {
2122
+ if (!length) {
2123
+ return { name, value: evaluate(value) };
1681
2124
  }
1682
- case "telemetry": {
1683
- const evaluate = (value) => this.expression(value, initialized, output);
1684
- const { record } = item;
1685
- output.push({
1686
- kind: "telemetry",
1687
- record: record.kind === "exception" ? { kind: "exception", code: evaluate(record.code) } : record,
1688
- properties: item.properties.map(({ name, value, length }) => {
1689
- if (!length)
1690
- return { name, value: evaluate(value) };
1691
- if (value.kind !== "borrow")
1692
- reject("Telemetry text reads a byte array in place.", value.span);
1693
- return {
1694
- name,
1695
- value: this.borrow(value, initialized, output),
1696
- length: evaluate(length)
1697
- };
1698
- }),
1699
- span: item.span
1700
- });
1701
- break;
2125
+ if (value.kind !== "borrow") {
2126
+ reject("Telemetry text reads a byte array in place.", value.span);
1702
2127
  }
1703
- case "break":
1704
- case "continue":
1705
- if (!inLoop)
1706
- reject("Loop control appears outside a bounded loop.", item.span);
1707
- output.push({ kind: item.kind, span: item.span });
1708
- flow = "loop";
1709
- break;
1710
- default:
1711
- reject("Unknown PLC statement.");
1712
- }
1713
- }
1714
- return { body: output, initialized, flow };
2128
+ return {
2129
+ name,
2130
+ value: this.borrow(value, initialized, output),
2131
+ length: evaluate(length)
2132
+ };
2133
+ }),
2134
+ span: item.span
2135
+ });
1715
2136
  }
1716
2137
  }
1717
2138
 
1718
- // packages/compiler/ir/link.ts
2139
+ // packages/compiler/src/ir/link.ts
1719
2140
  function linkModule(module, declarations, functions, normalizedBlocks, edges) {
1720
- const { signatures, blocks, types } = declarations;
1721
- const names = new Set, entries = new Set;
2141
+ const entries = checkPrograms(module, declarations);
2142
+ const routines = new Map([...functions, ...normalizedBlocks].map((fn) => [fn.id, fn]));
2143
+ checkRecursion(routines, edges, entries, declarations);
2144
+ checkLoopCounterWrites(module, declarations, routines, edges);
2145
+ const reachable = reachableRoutines(module, declarations, functions, entries, edges);
2146
+ const linkedFunctions = functions.filter((fn) => reachable.has(fn.id));
2147
+ const linkedBlocks = normalizedBlocks.filter((block) => reachable.has(block.id));
2148
+ const usedTypes = usedTypeIds(module, declarations.types, linkedFunctions, linkedBlocks);
2149
+ return {
2150
+ types: module.types.filter((type) => usedTypes.has(type.id)),
2151
+ variables: module.variables,
2152
+ functions: linkedFunctions,
2153
+ blocks: linkedBlocks,
2154
+ programs: module.programs,
2155
+ ...module.folded && { folded: module.folded }
2156
+ };
2157
+ }
2158
+ var checkPrograms = (module, declarations) => {
2159
+ const names = new Set;
2160
+ const entries = new Set;
1722
2161
  for (const program of module.programs) {
1723
2162
  declarations.claimId(program.id);
1724
- const entry = signatures.get(program.entry);
1725
- if (!entry || entry.owner || entry.parameters.length || entry.result)
2163
+ const entry = declarations.signatures.get(program.entry);
2164
+ if (!entry || entry.owner || entry.parameters.length || entry.result) {
1726
2165
  reject("Program entry must be a parameterless void helper.");
1727
- if (names.has(program.name))
2166
+ }
2167
+ if (names.has(program.name)) {
1728
2168
  reject(`Duplicate program ${program.name}.`);
2169
+ }
1729
2170
  names.add(program.name);
1730
2171
  entries.add(program.entry);
1731
2172
  }
1732
- if (!module.programs.length)
2173
+ if (!module.programs.length) {
1733
2174
  reject("At least one program is required.");
1734
- const visited = new Set, active = new Set;
2175
+ }
2176
+ return entries;
2177
+ };
2178
+ var checkRecursion = (routines, edges, entries, { signatures }) => {
2179
+ const visited = new Set;
2180
+ const active = new Set;
1735
2181
  const visit = (id) => {
1736
- if (active.has(id))
2182
+ if (active.has(id)) {
1737
2183
  reject("Recursive scan calls are prohibited.", signatures.get(id)?.span);
1738
- if (visited.has(id))
2184
+ }
2185
+ if (visited.has(id)) {
1739
2186
  return;
2187
+ }
1740
2188
  active.add(id);
1741
2189
  for (const child of edges.get(id) ?? []) {
1742
- if (entries.has(child))
2190
+ if (entries.has(child)) {
1743
2191
  reject("Program entries cannot be called as ordinary helpers.", signatures.get(id)?.span);
2192
+ }
1744
2193
  visit(child);
1745
2194
  }
1746
2195
  active.delete(id);
1747
2196
  visited.add(id);
1748
2197
  };
1749
- for (const fn of [...functions, ...normalizedBlocks])
1750
- visit(fn.id);
1751
- const routines = new Map([...functions, ...normalizedBlocks].map((fn) => [fn.id, fn]));
2198
+ for (const id of routines.keys()) {
2199
+ visit(id);
2200
+ }
2201
+ };
2202
+ var checkLoopCounterWrites = (module, { types }, routines, edges) => {
1752
2203
  const variables = new Map([
1753
2204
  ...module.variables,
1754
- ...functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
1755
- ...normalizedBlocks.flatMap((block) => [
1756
- ...block.inputs,
1757
- ...block.outputs,
1758
- ...block.state,
1759
- ...block.locals
1760
- ])
2205
+ ...[...routines.values()].flatMap((routine) => ("inputs" in routine) ? [
2206
+ ...routine.inputs,
2207
+ ...routine.outputs,
2208
+ ...routine.state,
2209
+ ...routine.locals
2210
+ ] : [...routine.parameters, ...routine.locals])
1761
2211
  ].map((variable) => [variable.id, variable]));
1762
2212
  const calledRoutine = (item) => {
1763
- if (item.kind === "invoke")
2213
+ if (item.kind === "invoke") {
1764
2214
  return item.function;
1765
- if (item.kind !== "blockUpdate")
2215
+ }
2216
+ if (item.kind !== "blockUpdate") {
1766
2217
  return;
2218
+ }
1767
2219
  const variable = variables.get(item.instance);
1768
2220
  return variable && instancedBlock(variable.type, types)?.block;
1769
2221
  };
1770
2222
  const writes = new Map;
1771
2223
  const routineWrites = (id) => {
1772
2224
  const cached = writes.get(id);
1773
- if (cached)
2225
+ if (cached) {
1774
2226
  return cached;
2227
+ }
1775
2228
  const result = new Set;
1776
2229
  const inspect = (body) => {
1777
2230
  for (const item of body) {
1778
- if (item.kind === "assign")
2231
+ if (item.kind === "assign") {
1779
2232
  result.add(item.root);
1780
- if (item.kind === "for")
2233
+ }
2234
+ if (item.kind === "for") {
1781
2235
  result.add(item.counter);
2236
+ }
1782
2237
  if (item.kind === "invoke") {
1783
- if (item.destination)
2238
+ if (item.destination) {
1784
2239
  result.add(item.destination);
1785
- for (const argument of item.arguments)
1786
- if (argument.kind === "borrow")
2240
+ }
2241
+ for (const argument of item.arguments) {
2242
+ if (argument.kind === "borrow") {
1787
2243
  result.add(argument.place.root);
2244
+ }
2245
+ }
1788
2246
  }
1789
2247
  if (item.kind === "blockUpdate") {
1790
- for (const input of Object.values(item.inputs))
1791
- if (input.kind === "borrow")
2248
+ for (const input of Object.values(item.inputs)) {
2249
+ if (input.kind === "borrow") {
1792
2250
  result.add(input.place.root);
2251
+ }
2252
+ }
1793
2253
  }
1794
- for (const nested of nestedBodies(item))
2254
+ for (const nested of nestedBodies(item)) {
1795
2255
  inspect(nested);
2256
+ }
1796
2257
  }
1797
2258
  };
1798
2259
  inspect(routines.get(id).body);
1799
- for (const child of edges.get(id) ?? [])
1800
- for (const root of routineWrites(child))
2260
+ for (const child of edges.get(id) ?? []) {
2261
+ for (const root of routineWrites(child)) {
1801
2262
  result.add(root);
2263
+ }
2264
+ }
1802
2265
  writes.set(id, result);
1803
2266
  return result;
1804
2267
  };
1805
2268
  const checkCalls = (body, counters) => {
1806
2269
  for (const item of body) {
1807
2270
  const called = calledRoutine(item);
1808
- if (called && [...counters].some((counter) => routineWrites(called).has(counter)))
2271
+ if (called && [...counters].some((counter) => routineWrites(called).has(counter))) {
1809
2272
  reject("A called routine may mutate an active loop counter.", item.span);
2273
+ }
1810
2274
  const nestedCounters = item.kind === "for" ? new Set([...counters, item.counter]) : counters;
1811
- for (const nested of nestedBodies(item))
2275
+ for (const nested of nestedBodies(item)) {
1812
2276
  checkCalls(nested, nestedCounters);
2277
+ }
1813
2278
  }
1814
2279
  };
1815
- for (const routine of routines.values())
2280
+ for (const routine of routines.values()) {
1816
2281
  checkCalls(routine.body, new Set);
2282
+ }
2283
+ };
2284
+ var reachableRoutines = (module, { signatures, blocks, types }, functions, entries, edges) => {
1817
2285
  const reachable = new Set;
1818
2286
  const link = (id) => {
1819
- if (reachable.has(id))
2287
+ if (reachable.has(id)) {
1820
2288
  return;
2289
+ }
1821
2290
  reachable.add(id);
1822
- for (const child of edges.get(id) ?? [])
2291
+ for (const child of edges.get(id) ?? []) {
1823
2292
  link(child);
2293
+ }
1824
2294
  const owner = signatures.get(id)?.owner;
1825
- if (owner)
2295
+ if (owner) {
1826
2296
  link(owner.block);
1827
- for (const method of functions.filter((fn) => fn.owner?.block === id))
2297
+ }
2298
+ for (const method of functions.filter((fn) => fn.owner?.block === id)) {
1828
2299
  link(method.id);
2300
+ }
1829
2301
  for (const instance of blocks.get(id)?.state.filter((variable) => variable.storage === "instance") ?? []) {
1830
2302
  const type = instancedBlock(instance.type, types);
1831
- if (type)
2303
+ if (type) {
1832
2304
  link(type.block);
2305
+ }
1833
2306
  }
1834
2307
  };
1835
- for (const entry of entries)
2308
+ for (const entry of entries) {
1836
2309
  link(entry);
2310
+ }
1837
2311
  for (const variable of module.variables) {
1838
2312
  const type = instancedBlock(variable.type, types);
1839
- if (type)
2313
+ if (type) {
1840
2314
  link(type.block);
2315
+ }
1841
2316
  }
1842
- const linkedFunctions = functions.filter((fn) => reachable.has(fn.id)), linkedBlocks = normalizedBlocks.filter((block) => reachable.has(block.id));
2317
+ return reachable;
2318
+ };
2319
+ var usedTypeIds = (module, types, linkedFunctions, linkedBlocks) => {
1843
2320
  const usedTypes = new Set;
1844
2321
  const useType = (id) => {
1845
- if (usedTypes.has(id))
2322
+ if (usedTypes.has(id)) {
1846
2323
  return;
2324
+ }
1847
2325
  usedTypes.add(id);
1848
2326
  const type = types.get(id);
1849
2327
  if (type.kind === "record") {
1850
- for (const field of type.fields)
2328
+ for (const field of type.fields) {
1851
2329
  useType(field.type);
2330
+ }
1852
2331
  }
1853
2332
  if (type.kind === "array") {
1854
2333
  useType(type.element);
1855
- if (type.index)
2334
+ if (type.index) {
1856
2335
  useType(type.index);
2336
+ }
1857
2337
  }
1858
- if (type.kind === "enum")
2338
+ if (type.kind === "enum") {
1859
2339
  useType(type.base);
1860
- if (type.kind === "block" && type.output)
2340
+ }
2341
+ if (type.kind === "block" && type.output) {
1861
2342
  useType(type.output);
2343
+ }
1862
2344
  };
1863
2345
  types.forEach((type) => {
1864
- if (["bool", "integer", "bits", "float", "duration", "calendar"].includes(type.kind))
2346
+ if (["bool", "integer", "bits", "float", "duration", "calendar"].includes(type.kind)) {
1865
2347
  useType(type.id);
2348
+ }
1866
2349
  });
1867
- for (const variable of module.variables)
2350
+ for (const variable of module.variables) {
1868
2351
  useType(variable.type);
2352
+ }
1869
2353
  for (const fn of linkedFunctions) {
1870
- if (fn.result)
2354
+ if (fn.result) {
1871
2355
  useType(fn.result);
1872
- for (const variable of [...fn.parameters, ...fn.locals])
2356
+ }
2357
+ for (const variable of [...fn.parameters, ...fn.locals]) {
1873
2358
  useType(variable.type);
2359
+ }
1874
2360
  }
1875
2361
  for (const block of linkedBlocks) {
1876
- if (block.result)
2362
+ if (block.result) {
1877
2363
  useType(block.result);
1878
- for (const variable of [...block.inputs, ...block.outputs, ...block.state, ...block.locals]) {
2364
+ }
2365
+ for (const variable of [
2366
+ ...block.inputs,
2367
+ ...block.outputs,
2368
+ ...block.state,
2369
+ ...block.locals
2370
+ ]) {
1879
2371
  useType(variable.type);
1880
2372
  }
1881
2373
  }
1882
2374
  const useTelemetryTypes = (body) => {
1883
2375
  for (const item of body) {
1884
- if (item.kind === "telemetry")
1885
- for (const operand of telemetryOperands(item))
2376
+ if (item.kind === "telemetry") {
2377
+ for (const operand of telemetryOperands(item)) {
1886
2378
  useType(operand.type);
1887
- for (const nested of nestedBodies(item))
2379
+ }
2380
+ }
2381
+ for (const nested of nestedBodies(item)) {
1888
2382
  useTelemetryTypes(nested);
2383
+ }
1889
2384
  }
1890
2385
  };
1891
- for (const routine of [...linkedFunctions, ...linkedBlocks])
2386
+ for (const routine of [...linkedFunctions, ...linkedBlocks]) {
1892
2387
  useTelemetryTypes(routine.body);
1893
- return {
1894
- types: module.types.filter((type) => usedTypes.has(type.id)),
1895
- variables: module.variables,
1896
- functions: linkedFunctions,
1897
- blocks: linkedBlocks,
1898
- programs: module.programs,
1899
- ...module.folded && { folded: module.folded }
1900
- };
1901
- }
2388
+ }
2389
+ return usedTypes;
2390
+ };
1902
2391
 
1903
- // packages/compiler/ir/core.ts
2392
+ // packages/compiler/src/ir/normalize.ts
1904
2393
  var verifiedModules = new WeakSet;
1905
2394
  function isVerifiedCore(value) {
1906
2395
  return typeof value === "object" && value !== null && verifiedModules.has(value);
1907
2396
  }
1908
2397
  function freeze(value) {
1909
- if (typeof value !== "object" || value === null || Object.isFrozen(value))
2398
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
1910
2399
  return;
1911
- for (const child of Object.values(value))
2400
+ }
2401
+ for (const child of Object.values(value)) {
1912
2402
  freeze(child);
2403
+ }
1913
2404
  Object.freeze(value);
1914
2405
  }
1915
2406
  function normalizeModule(module) {
1916
2407
  try {
1917
2408
  const declarations = new ModuleDeclarations(module);
1918
2409
  checkStaticAllocation(module, declarations);
1919
- const functions = [], blocks = [];
2410
+ const functions = [];
2411
+ const blocks = [];
1920
2412
  const edges = new Map;
1921
2413
  for (const source of [...module.functions, ...module.blocks]) {
1922
2414
  const normalized = new RoutineNormalizer(source, declarations).normalize();
1923
2415
  edges.set(source.id, normalized.callees);
1924
- if ("inputs" in normalized.routine)
2416
+ if ("inputs" in normalized.routine) {
1925
2417
  blocks.push(normalized.routine);
1926
- else
2418
+ } else {
1927
2419
  functions.push(normalized.routine);
2420
+ }
1928
2421
  }
1929
2422
  const linked = linkModule(module, declarations, functions, blocks, edges);
1930
- const core = { ...structuredClone(linked), [verified]: true };
2423
+ const core = {
2424
+ ...structuredClone(linked),
2425
+ [verified]: true
2426
+ };
1931
2427
  freeze(core);
1932
2428
  verifiedModules.add(core);
1933
2429
  return { core, diagnostics: [] };
1934
2430
  } catch (cause) {
1935
- if (cause instanceof InvalidCore)
2431
+ if (cause instanceof InvalidCore) {
1936
2432
  return { diagnostics: [cause.diagnostic] };
2433
+ }
1937
2434
  throw cause;
1938
2435
  }
1939
2436
  }
1940
- // packages/compiler/ir/errors.ts
2437
+ // packages/compiler/src/ir/job-errors.ts
1941
2438
  var jobErrors = {
1942
2439
  "1": "cancelled",
1943
2440
  "2": "timeout",
@@ -1950,8 +2447,9 @@ var jobErrors = {
1950
2447
  };
1951
2448
  var httpErrors = { base: 1e4, last: 10999 };
1952
2449
  var errorName = (code) => {
1953
- if (code > httpErrors.base && code <= httpErrors.last)
2450
+ if (code > httpErrors.base && code <= httpErrors.last) {
1954
2451
  return `HTTP ${code - httpErrors.base}`;
2452
+ }
1955
2453
  return code < httpErrors.base ? jobErrors[code] : undefined;
1956
2454
  };
1957
2455
  export {
@@ -1983,12 +2481,17 @@ export {
1983
2481
  layoutIssue,
1984
2482
  loopBounds,
1985
2483
  loopIterations,
2484
+ maxLoopIterations,
2485
+ maxNestingDepth,
2486
+ maxScalarElements,
2487
+ nanosecondsPerMillisecond,
1986
2488
  narrowRanges,
1987
2489
  nestedBodies,
1988
2490
  normalizeModule,
1989
2491
  parseInteger,
1990
2492
  placeType,
1991
2493
  primitiveTypes,
2494
+ roundFloat,
1992
2495
  saturateFloat,
1993
2496
  scalarIssue,
1994
2497
  standardBlocks,
@@ -1998,5 +2501,5 @@ export {
1998
2501
  wrapsNatively
1999
2502
  };
2000
2503
 
2001
- //# debugId=43D0B7CC8A03DD5164756E2164756E21
2504
+ //# debugId=AD6AE5E0818FE34A64756E2164756E21
2002
2505
  //# sourceMappingURL=ir.js.map