@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -1,5 +1,3 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
-
3
1
  import {
4
2
  aggregate,
5
3
  type Constant,
@@ -13,12 +11,11 @@ import {
13
11
  type Statement,
14
12
  type Variable,
15
13
  } from "@tsplc/compiler/ir";
16
- import { loopIterations } from "@tsplc/iec/arithmetic";
17
14
  import ts from "typescript";
18
15
  import type { AnalysisContext, ExpressionLowering } from "./expressions";
19
16
  import type { Positions } from "./positions";
20
17
  import { telemetryStatement } from "./telemetry";
21
- import { type Fail, numericLiteral, type TypeResolver } from "./types";
18
+ import { type Fail, inferredStorageType, type TypeResolver } from "./types";
22
19
 
23
20
  type IterationForm = "elements" | "entries" | "recordValues" | "recordEntries";
24
21
 
@@ -31,8 +28,8 @@ interface LoopHeader {
31
28
  }
32
29
 
33
30
  /**
34
- * A case's statements, out of the braces that scope its declarations, as elaboration writes every case: they end where the
35
- * braces do, and blocks lower without a scope of their own.
31
+ * A case's statements, out of the braces that scope its declarations, as control-flow lowering
32
+ * writes every case: they end where the braces do, and blocks lower without a scope of their own.
36
33
  */
37
34
  const unbraced = (
38
35
  statements: readonly ts.Statement[],
@@ -43,6 +40,16 @@ const unbraced = (
43
40
  : statements;
44
41
  };
45
42
 
43
+ const caseEndMessage = (last: ts.Statement | undefined): string => {
44
+ if (last && ts.isThrowStatement(last)) {
45
+ return "A switch case cannot end in throw; end it with break or return.";
46
+ }
47
+ if (last && ts.isContinueStatement(last)) {
48
+ return "A switch case cannot end in continue; end it with break or return.";
49
+ }
50
+ return "The last switch case must end with break or return.";
51
+ };
52
+
46
53
  /**
47
54
  * Lowers one routine's statements. Expressions, and the scope facts that
48
55
  * declarations, branches and loops establish, go through its ExpressionLowering.
@@ -129,18 +136,17 @@ export class StatementLowering {
129
136
  return [{ ...origin, kind: "return", ...(value && { value }) }];
130
137
  }
131
138
  if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) {
132
- if (ts.isBreakStatement(node) && this.breakTargets.at(-1) === "switch") {
133
- this.fail(
134
- node,
135
- "PLC1001",
136
- "Switch break must terminate its case; nested conditional switch breaks are unsupported.",
137
- );
138
- }
139
- if (node.label || !this.breakTargets.includes("loop")) {
139
+ // Control-flow lowering has turned every jump Structured Text cannot make into flags; what
140
+ // is left here is a jump TypeScript rejects too.
141
+ if (
142
+ node.label ||
143
+ !this.breakTargets.includes("loop") ||
144
+ (ts.isBreakStatement(node) && this.breakTargets.at(-1) === "switch")
145
+ ) {
140
146
  this.fail(
141
147
  node,
142
148
  "PLC1001",
143
- "Loop control requires an enclosing bounded loop and cannot use a label.",
149
+ "break and continue must leave an enclosing loop.",
144
150
  );
145
151
  }
146
152
  return [
@@ -226,7 +232,7 @@ export class StatementLowering {
226
232
  type,
227
233
  storage: "local",
228
234
  mutable,
229
- retain: false,
235
+ retention: "none",
230
236
  span: this.positions.node(declaration),
231
237
  };
232
238
  this.locals.push(variable);
@@ -239,32 +245,32 @@ export class StatementLowering {
239
245
  this.breakTargets.push("switch");
240
246
  try {
241
247
  const value = this.expressions.expression(node.expression);
248
+ const { clauses } = node.caseBlock;
242
249
  const cases: { values: Constant[]; body: Statement[] }[] = [];
243
250
  const labels: Constant[] = [];
244
- let fallback: Statement[] = [];
245
- let defaultLabel = false;
246
- for (const clause of node.caseBlock.clauses) {
247
- if (ts.isDefaultClause(clause)) {
248
- defaultLabel = true;
249
- } else {
251
+ const bodies = clauses.map((clause) => {
252
+ if (!ts.isDefaultClause(clause)) {
250
253
  labels.push(this.caseValue(clause, value.type));
251
254
  }
252
255
  const statements = unbraced(clause.statements);
253
- if (!statements.length) {
254
- continue;
255
- }
256
- const body = this.caseBody(clause, statements);
257
- if (labels.length) {
256
+ const body = statements.length
257
+ ? this.caseBody(clause, statements)
258
+ : undefined;
259
+ if (body && labels.length) {
258
260
  cases.push({ values: labels.splice(0), body });
259
261
  }
260
- if (defaultLabel) {
261
- fallback = body;
262
- }
263
- defaultLabel = false;
264
- }
262
+ return body;
263
+ });
265
264
  if (labels.length) {
266
265
  cases.push({ values: labels, body: [] });
267
266
  }
267
+ // The default label shares the body of the clause that ends its group.
268
+ const fallbackIndex = clauses.findIndex(ts.isDefaultClause);
269
+ const fallback =
270
+ fallbackIndex < 0
271
+ ? []
272
+ : (bodies.slice(fallbackIndex).find((body) => body !== undefined) ??
273
+ []);
268
274
  return [{ ...origin, kind: "switch", value, cases, fallback }];
269
275
  } finally {
270
276
  this.breakTargets.pop();
@@ -294,14 +300,12 @@ export class StatementLowering {
294
300
  if (last && ts.isBreakStatement(last) && !last.label) {
295
301
  return this.statements(statements.slice(0, -1));
296
302
  }
297
- if (!(last && ts.isReturnStatement(last))) {
298
- this.fail(
299
- clause,
300
- "PLC1001",
301
- "Switch cases must end with break or return; fallthrough is prohibited.",
302
- );
303
+ if (last && ts.isReturnStatement(last)) {
304
+ return this.statements(statements);
303
305
  }
304
- return this.statements(statements);
306
+ // Control-flow lowering gives a case that runs on into the next its own break, so only the
307
+ // last case can still run off the end.
308
+ this.fail(clause, "PLC1001", caseEndMessage(last));
305
309
  }
306
310
 
307
311
  private localDeclarations(node: ts.VariableStatement): Statement[] {
@@ -343,10 +347,7 @@ export class StatementLowering {
343
347
  if (
344
348
  !annotation &&
345
349
  !immutable &&
346
- numericLiteral(declaration.initializer) === undefined &&
347
- ![ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword].includes(
348
- declaration.initializer.kind,
349
- )
350
+ inferredStorageType(declaration.initializer) === undefined
350
351
  ) {
351
352
  this.fail(
352
353
  declaration,
@@ -390,7 +391,6 @@ export class StatementLowering {
390
391
  { mutable: !immutable },
391
392
  );
392
393
  this.expressions.bind(this.resolver.symbol(declaration.name), variable);
393
- // A const is assigned once, so its initializer's range holds wherever it is read.
394
394
  if (!variable.mutable) {
395
395
  this.expressions.holdRange(variable.id, value);
396
396
  }
@@ -459,11 +459,7 @@ export class StatementLowering {
459
459
  const proof = loopBounds(startRange, limitRange, step, exclusive);
460
460
  this.checkIterations(node, proof.count);
461
461
  if (existing && proof.count > 0n) {
462
- this.checkFinalIncrement(
463
- node,
464
- plcType,
465
- (step > 0n ? proof.range[1] : proof.range[0]) + step,
466
- );
462
+ this.checkFinalIncrement(node, plcType, proof.terminal);
467
463
  }
468
464
  return this.inLoop([counter.id], counter.id, proof.range, () => [
469
465
  {
@@ -480,20 +476,20 @@ export class StatementLowering {
480
476
  },
481
477
  ]);
482
478
  }
483
- // A constant exclusive bound becomes the inclusive limit one unit inside it.
484
- const direction = ascending ? 1n : -1n;
485
- const finish = BigInt(bound.value) - (exclusive ? direction : 0n);
486
479
  const first = BigInt(start.value);
487
- const count = loopIterations(first, BigInt(bound.value), exclusive, step);
480
+ const limit = BigInt(bound.value);
481
+ const { last, count, range, terminal } = loopBounds(
482
+ [first, first],
483
+ [limit, limit],
484
+ step,
485
+ exclusive,
486
+ );
488
487
  this.checkIterations(node, count);
489
488
  if (existing) {
490
- this.checkFinalIncrement(node, plcType, first + count * step);
489
+ this.checkFinalIncrement(node, plcType, terminal);
491
490
  }
492
- const body = this.inLoop(
493
- [counter.id],
494
- counter.id,
495
- first <= finish ? [first, finish] : [finish, first],
496
- () => this.body(node.statement),
491
+ const body = this.inLoop([counter.id], counter.id, range, () =>
492
+ this.body(node.statement),
497
493
  );
498
494
  const startConstant: Expression = {
499
495
  kind: "constant",
@@ -524,7 +520,7 @@ export class StatementLowering {
524
520
  limit: {
525
521
  kind: "constant",
526
522
  type,
527
- value: { kind: "integer", value: String(finish) },
523
+ value: { kind: "integer", value: String(last) },
528
524
  span: this.positions.node(condition.right),
529
525
  },
530
526
  step: String(step),
@@ -579,8 +575,9 @@ export class StatementLowering {
579
575
  header.operatorToken.kind === ts.SyntaxKind.EqualsToken
580
576
  ) {
581
577
  const target = this.expressions.target(header.left);
582
- const counter = this.expressions.byId().get(target.place.root)!;
578
+ const counter = this.expressions.byId().get(target.place.root);
583
579
  if (
580
+ !counter ||
584
581
  target.place.path.length ||
585
582
  !["local", "module", "field"].includes(counter.storage)
586
583
  ) {
@@ -652,7 +649,7 @@ export class StatementLowering {
652
649
  this.fail(
653
650
  node,
654
651
  "PLC2001",
655
- "A scan loop cannot exceed 1,000,000 iterations.",
652
+ `A scan loop cannot exceed ${maxLoopIterations.toLocaleString("en-US")} iterations.`,
656
653
  );
657
654
  }
658
655
  }
@@ -772,7 +769,6 @@ export class StatementLowering {
772
769
  ? this.resolver.types.get(array.index)
773
770
  : undefined;
774
771
  if (indexName && enumeration?.kind === "enum") {
775
- // The enum key follows the counter: a CASE at the top of each iteration selects its member.
776
772
  const key = this.local(indexName, indexName.text, enumeration.id, {
777
773
  mutable: true,
778
774
  });
@@ -858,7 +854,7 @@ export class StatementLowering {
858
854
  return { form: "elements", iterated: expression };
859
855
  }
860
856
 
861
- /** Lowers a loop body with `counters` read-only and `counter` proved to lie in `range`. */
857
+ /** Lowers a loop body as `counting` does, inside a loop that break and continue leave. */
862
858
  private inLoop<T>(
863
859
  counters: readonly string[],
864
860
  counter: string,
@@ -1,16 +1,14 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import { resolve } from "node:path";
3
- import {
4
- durationLiteral,
5
- jobError,
6
- nanosecondsPerMillisecond,
7
- } from "@tsplc/compiler/ir";
2
+ import { jobError } from "@tsplc/compiler/ir";
3
+ import { taskPriority } from "@tsplc/config/build";
8
4
  import ts from "typescript";
9
- import type { AsyncContext, Routine, SourceRewrite } from "./async";
5
+ import type { AsyncContext, SourceRewrite } from "./async";
10
6
  import { cooperativeSite, copyValue, type Site, taskSite } from "./cooperative";
11
- import { aliasPrefix } from "./coroutines";
12
- import { importSpecifier } from "./module-graph";
7
+ import { durationScales, literalDuration } from "./intrinsics";
8
+ import { loweringKey } from "./lowering-key";
9
+ import type { NamedRoutine } from "./module-graph";
13
10
  import { from } from "./positions";
11
+ import { isAggregateType, promisedType } from "./types";
14
12
 
15
13
  /** A `<tasks>.define(...)` initializer, the declaration holding it, and that declaration's block. */
16
14
  interface TaskDefinition {
@@ -19,6 +17,46 @@ interface TaskDefinition {
19
17
  owner: ts.ClassLikeDeclaration | undefined;
20
18
  }
21
19
 
20
+ const taskCollections = [
21
+ "tasks",
22
+ "cooperativeTasks",
23
+ "backgroundTasks",
24
+ ] as const;
25
+ type TaskCollection = (typeof taskCollections)[number];
26
+
27
+ /** The SDK task collection a `<tasks>.define(...)` initializer defines a task on, and the call. */
28
+ const definedTask = (
29
+ context: Pick<AsyncContext, "namesSdk">,
30
+ node: ts.Expression | undefined,
31
+ ): { collection: TaskCollection; init: ts.CallExpression } | undefined => {
32
+ if (
33
+ !node ||
34
+ !ts.isCallExpression(node) ||
35
+ !ts.isPropertyAccessExpression(node.expression) ||
36
+ node.expression.name.text !== "define"
37
+ ) {
38
+ return undefined;
39
+ }
40
+ const receiver = node.expression.expression;
41
+ const collection = taskCollections.find((name) =>
42
+ context.namesSdk(receiver, name),
43
+ );
44
+ return collection && { collection, init: node };
45
+ };
46
+
47
+ /** The `backgroundTasks.define(...)` call that initializes the variable or field `symbol` names, if it is one. */
48
+ export const backgroundJob = (
49
+ context: Pick<AsyncContext, "namesSdk">,
50
+ symbol: ts.Symbol | undefined,
51
+ ): ts.CallExpression | undefined => {
52
+ const declaration = symbol?.declarations?.find(
53
+ (node): node is ts.VariableDeclaration | ts.PropertyDeclaration =>
54
+ ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node),
55
+ );
56
+ const task = definedTask(context, declaration?.initializer);
57
+ return task?.collection === "backgroundTasks" ? task.init : undefined;
58
+ };
59
+
22
60
  /**
23
61
  * Lowers `tasks.define`, `cooperativeTasks.define` and `backgroundTasks.define` in one
24
62
  * source: each becomes a generated site or mailbox block, with the entry points that run it.
@@ -28,33 +66,43 @@ export function lowerTaskDefinitions(
28
66
  file: SourceRewrite,
29
67
  ): void {
30
68
  for (const declaration of declarations(file.source)) {
31
- const init = declaration.initializer;
69
+ const task = definedTask(context, declaration.initializer);
70
+ if (!task) {
71
+ continue;
72
+ }
73
+ // A module's task nothing starts has no scan task to run it in, so it is left out.
74
+ const statement = declaration.parent.parent;
32
75
  if (
33
- !init ||
34
- !ts.isCallExpression(init) ||
35
- !ts.isPropertyAccessExpression(init.expression) ||
36
- (!context.namesSdk(init.expression.expression, "backgroundTasks") &&
37
- !context.namesSdk(init.expression.expression, "cooperativeTasks") &&
38
- !context.namesSdk(init.expression.expression, "tasks")) ||
39
- init.expression.name.text !== "define"
76
+ task.collection === "tasks" &&
77
+ ts.isVariableDeclaration(declaration) &&
78
+ ts.isVariableStatement(statement) &&
79
+ statement.declarationList.declarations.length === 1 &&
80
+ !context.referenced(declaration)
40
81
  ) {
82
+ file.replacements.push({
83
+ start: statement.getStart(file.source),
84
+ end: statement.end,
85
+ text: "",
86
+ });
41
87
  continue;
42
88
  }
43
89
  const definition = {
44
90
  declaration,
45
- init,
91
+ init: task.init,
46
92
  owner: ts.isPropertyDeclaration(declaration)
47
93
  ? declaration.parent
48
94
  : undefined,
49
95
  };
50
- if (context.namesSdk(init.expression.expression, "tasks")) {
51
- taskDefinition(context, file, definition);
52
- } else if (
53
- context.namesSdk(init.expression.expression, "cooperativeTasks")
54
- ) {
55
- cooperativeDefinition(context, file, definition);
56
- } else {
57
- backgroundDefinition(context, file, definition);
96
+ switch (task.collection) {
97
+ case "tasks":
98
+ taskDefinition(context, file, definition);
99
+ break;
100
+ case "cooperativeTasks":
101
+ cooperativeDefinition(context, file, definition);
102
+ break;
103
+ case "backgroundTasks":
104
+ backgroundDefinition(context, file, definition);
105
+ break;
58
106
  }
59
107
  }
60
108
  }
@@ -136,10 +184,8 @@ function cooperativeDefinition(
136
184
  }
137
185
  const params = routine.parameters.map((parameter, index) => ({
138
186
  name: `argument${index}`,
139
- type: parameter.type!.getText(routine.getSourceFile()),
140
- aggregate: Boolean(
141
- context.checker.getTypeAtLocation(parameter).flags & ts.TypeFlags.Object,
142
- ),
187
+ type: parameterType(context, parameter),
188
+ aggregate: isAggregateType(context.checker.getTypeAtLocation(parameter)),
143
189
  }));
144
190
  // An async method runs as members of the owner itself; a helper runs in its own block.
145
191
  const method = context.methods.get(symbol);
@@ -172,14 +218,16 @@ function cooperativeDefinition(
172
218
  */
173
219
  function placeSite(
174
220
  context: AsyncContext,
175
- { source, replacements, extra }: SourceRewrite,
221
+ file: SourceRewrite,
176
222
  { declaration, init, owner }: TaskDefinition,
177
223
  name: string,
178
224
  site: Site,
179
225
  { siteClass, unnamedOwner }: { siteClass: string; unnamedOwner: string },
180
226
  ): void {
227
+ const { source, replacements, extra } = file;
181
228
  if (owner) {
182
- if (!owner.name) {
229
+ const block = owner.name && context.symbol(owner.name);
230
+ if (!block) {
183
231
  context.fail(owner, unnamedOwner);
184
232
  }
185
233
  replacements.push({
@@ -187,9 +235,8 @@ function placeSite(
187
235
  end: declaration.end,
188
236
  text: site.body,
189
237
  });
190
- const block = context.symbol(owner.name)!;
191
- context.ownedContinuations.set(block, [
192
- ...(context.ownedContinuations.get(block) ?? []),
238
+ file.ownedPolls.set(block, [
239
+ ...(file.ownedPolls.get(block) ?? []),
193
240
  site.poll,
194
241
  ]);
195
242
  const field = context.symbol(declaration.name);
@@ -230,11 +277,8 @@ export function ${entry}():void{${name}.poll();}`,
230
277
  end: init.end,
231
278
  text: `new ${block}()`,
232
279
  });
233
- context.result.programs[entry] = {
234
- module: resolve(source.fileName),
235
- export: entry,
236
- };
237
- context.result.continuations.set(entry, {
280
+ file.programs[entry] = { module: resolve(source.fileName), export: entry };
281
+ file.continuations.set(entry, {
238
282
  instance: name,
239
283
  file: context.positions.node(declaration).file,
240
284
  });
@@ -303,8 +347,9 @@ protected execute(input:{}):void {}
303
347
  : declaration.name.text;
304
348
  const workerReceiver = owner ? `this.${worker}` : worker;
305
349
  const run = `const request=${receiver}.take();if(request.ready){const accepted:BOOL=${workerReceiver}.start(${params.map((p) => `request.${p.field}`).join(",")});}const control=${receiver}.snapshot();if(!control.valid)return;${workerReceiver}.update({cancel:control.cancelRequested});const state=${workerReceiver}.snapshot();if(state.done){const published:BOOL=${receiver}.publish(state.result,state.error);if(published)${workerReceiver}.reset();}`;
350
+ const block = owner?.name && context.symbol(owner.name);
306
351
  if (owner) {
307
- if (!owner.name) {
352
+ if (!owner.name || !block) {
308
353
  context.fail(owner, "Background job owners need a named function block.");
309
354
  }
310
355
  replacements.push({
@@ -315,7 +360,7 @@ protected execute(input:{}):void {}
315
360
  `private ${worker}=new ${work.getText(source)}();public ${entry}():void{${run}}`,
316
361
  ),
317
362
  });
318
- context.result.blocks.set(`${source.fileName}:${owner.name.text}`, {
363
+ file.blocks.set(loweringKey(source.fileName, owner.name.text), {
319
364
  kind: "backgroundHost",
320
365
  });
321
366
  } else {
@@ -326,7 +371,7 @@ protected execute(input:{}):void {}
326
371
  ),
327
372
  );
328
373
  }
329
- context.result.blocks.set(`${source.fileName}:${mailbox}`, {
374
+ file.blocks.set(loweringKey(source.fileName, mailbox), {
330
375
  kind: "mailbox",
331
376
  });
332
377
  const schedule = {
@@ -334,18 +379,14 @@ protected execute(input:{}):void {}
334
379
  mailbox: declaration.name.text,
335
380
  worker,
336
381
  };
337
- if (owner) {
338
- const block = context.symbol(owner.name!)!;
339
- context.ownedJobs.set(block, [
340
- ...(context.ownedJobs.get(block) ?? []),
382
+ if (block) {
383
+ file.ownedJobs.set(block, [
384
+ ...(file.ownedJobs.get(block) ?? []),
341
385
  { method: entry, schedule },
342
386
  ]);
343
387
  } else {
344
- context.result.programs[entry] = {
345
- module: resolve(source.fileName),
346
- export: entry,
347
- };
348
- context.result.schedules.set(entry, schedule);
388
+ file.programs[entry] = { module: resolve(source.fileName), export: entry };
389
+ file.schedules.set(entry, schedule);
349
390
  }
350
391
  replacements.push({
351
392
  start: init.getStart(source),
@@ -370,46 +411,44 @@ function scheduleTiming(
370
411
  const priority = properties.get("priority");
371
412
  const [amount, ...rest] =
372
413
  interval && ts.isCallExpression(interval) ? interval.arguments : [];
414
+ const unit =
415
+ interval &&
416
+ ts.isCallExpression(interval) &&
417
+ ["ms", "seconds"].find((name) =>
418
+ context.namesSdk(interval.expression, name),
419
+ );
420
+ const scale = unit && durationScales.get(unit);
373
421
  if (
374
- !interval ||
375
- !ts.isCallExpression(interval) ||
422
+ !scale ||
376
423
  !amount ||
377
424
  rest.length ||
378
425
  !ts.isNumericLiteral(amount) ||
379
426
  !priority ||
380
- !ts.isNumericLiteral(priority) ||
381
- !["ms", "seconds"].some((name) =>
382
- context.namesSdk(interval.expression, name),
383
- )
427
+ !ts.isNumericLiteral(priority)
384
428
  ) {
385
429
  context.fail(
386
430
  init,
387
431
  "Background schedules require a literal ms/seconds interval and priority.",
388
432
  );
389
433
  }
390
- const milliseconds =
391
- Number(amount.text) *
392
- (context.namesSdk(interval.expression, "seconds") ? 1000 : 1);
393
- const taskPriority = Number(priority.text);
394
- // A whole number of milliseconds, held to the TIME range.
395
- const period =
396
- Number.isSafeInteger(milliseconds) && milliseconds > 0
397
- ? durationLiteral(String(milliseconds), nanosecondsPerMillisecond)
398
- : undefined;
434
+ const period = literalDuration(amount.text, scale);
435
+ const level = Number(priority.text);
399
436
  if (
400
437
  period?.kind !== "duration" ||
401
- !Number.isInteger(taskPriority) ||
402
- taskPriority < 1 ||
403
- taskPriority > 31
438
+ period.nanoseconds === "0" ||
439
+ !taskPriority.safeParse(level).success ||
440
+ // CODESYS runs priority 0 ahead of everything; a background task stays below it, so a scan
441
+ // task can always be given a higher priority than the background work it hands off.
442
+ level < 1
404
443
  ) {
405
444
  context.fail(
406
445
  init,
407
- "Background interval must be positive and priority must be an integer in 1..31.",
446
+ `Background interval must be positive and priority must be an integer in 1..${taskPriority.maxValue}.`,
408
447
  );
409
448
  }
410
449
  return {
411
450
  intervalNanoseconds: period.nanoseconds,
412
- priority: taskPriority,
451
+ priority: level,
413
452
  };
414
453
  }
415
454
 
@@ -419,20 +458,27 @@ function scheduleTiming(
419
458
  */
420
459
  function workTypes(
421
460
  context: AsyncContext,
422
- { source, extra }: SourceRewrite,
423
- fn: Routine,
461
+ file: SourceRewrite,
462
+ fn: NamedRoutine,
424
463
  declaration: ts.VariableDeclaration | ts.PropertyDeclaration,
425
464
  ) {
426
465
  const { checker } = context;
427
- const reference = fn.type as ts.TypeReferenceNode;
466
+ const result = fn.type && promisedType(fn.type);
467
+ const signature = checker.getSignatureFromDeclaration(fn);
468
+ const promised =
469
+ signature &&
470
+ checker.getAwaitedType(checker.getReturnTypeOfSignature(signature));
471
+ if (!result || !promised) {
472
+ context.fail(
473
+ fn,
474
+ "Async functions require concrete parameters and an explicit Promise<T> result.",
475
+ );
476
+ }
428
477
  const returnType =
429
- reference.typeArguments![0]!.kind === ts.SyntaxKind.VoidKeyword
478
+ result.kind === ts.SyntaxKind.VoidKeyword
430
479
  ? "BOOL"
431
- : reference.typeArguments![0]!.getText(fn.getSourceFile());
432
- const promised = checker.getAwaitedType(
433
- checker.getReturnTypeOfSignature(checker.getSignatureFromDeclaration(fn)!),
434
- )!;
435
- const valueAggregate = Boolean(promised.flags & ts.TypeFlags.Object);
480
+ : result.getText(fn.getSourceFile());
481
+ const valueAggregate = isAggregateType(promised);
436
482
  const parameter = (
437
483
  node: ts.ParameterDeclaration,
438
484
  index: number,
@@ -440,32 +486,41 @@ function workTypes(
440
486
  ) => ({
441
487
  field: `argument${index}`,
442
488
  name: `argument${index}`,
443
- aggregate: Boolean(
444
- checker.getTypeAtLocation(node).flags & ts.TypeFlags.Object,
445
- ),
489
+ aggregate: isAggregateType(checker.getTypeAtLocation(node)),
446
490
  type,
447
491
  });
448
- if (fn.getSourceFile() === source) {
492
+ if (fn.getSourceFile() === file.source) {
449
493
  // The annotations keep the PLC widths the TypeScript checker erases.
450
494
  return {
451
495
  params: fn.parameters.map((node, index) =>
452
- parameter(node, index, node.type!.getText(source)),
496
+ parameter(node, index, parameterType(context, node)),
453
497
  ),
454
498
  valueType: returnType,
455
499
  valueAggregate,
456
500
  };
457
501
  }
458
- // Another module's types are named through the aliases its coroutine exports.
459
- const prefix = aliasPrefix(context.names, fn);
502
+ const aliases = context.aliases(fn);
460
503
  const params = fn.parameters.map((node, index) =>
461
- parameter(node, index, `${prefix}Argument${index}`),
462
- );
463
- const valueType = `${prefix}Result`;
464
- extra.push(
465
- from(
466
- declaration,
467
- `import type {${valueType},${params.map((p) => p.type).join(",")}} from ${importSpecifier(source.fileName, fn.getSourceFile().fileName)};`,
468
- ),
504
+ parameter(node, index, aliases.argument(index)),
469
505
  );
506
+ const valueType = aliases.result;
507
+ context.importAliases(file, declaration, fn, [
508
+ valueType,
509
+ ...params.map((param) => param.type),
510
+ ]);
470
511
  return { params, valueType, valueAggregate };
471
512
  }
513
+
514
+ /** An async routine's parameter type as its module writes it. */
515
+ const parameterType = (
516
+ context: AsyncContext,
517
+ parameter: ts.ParameterDeclaration,
518
+ ): string => {
519
+ if (!parameter.type) {
520
+ context.fail(
521
+ parameter,
522
+ "Async parameters require explicit concrete value types.",
523
+ );
524
+ }
525
+ return parameter.type.getText(parameter.getSourceFile());
526
+ };
@@ -5,7 +5,7 @@ import { namedProperty, type TelemetryMethod } from "./types";
5
5
 
6
6
  type Telemetry = Extract<Statement, { kind: "telemetry" }>;
7
7
 
8
- /** A `@tsplc/compiler/telemetry` call, which the backend encodes as one record (docs/language/telemetry.md). */
8
+ /** A `@tsplc/compiler/telemetry` call, which the backend encodes as one record (docs/03-guides/telemetry.md). */
9
9
  export function telemetryStatement(
10
10
  lowering: ExpressionLowering,
11
11
  node: ts.CallExpression,