@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,43 +1,37 @@
1
1
  import {
2
- type Constant,
3
- type CoreExpression,
4
2
  type CoreFunction,
5
3
  type CoreFunctionBlock,
6
- type CoreStatement,
7
- defaultValue,
4
+ coreTables,
8
5
  type GeneratedObject,
9
6
  instancedBlock,
7
+ isBlockRoutine,
10
8
  type SourceSpan,
11
9
  type Variable,
12
10
  } from "@tsplc/compiler/ir";
13
- import type { SourceMapping } from "./emit";
11
+ import { instrumentationFields } from "@tsplc/debug/manifest";
12
+ import { type StorageScope, storageName } from "./expressions";
13
+ import { jobField, jobTracking, type RoutineProbes } from "./instrumentation";
14
+ import { required } from "./required";
15
+ import type { ObjectMapping } from "./st-files";
14
16
  import {
15
- expressionText,
16
- placeText,
17
- type StorageScope,
18
- storageName,
19
- } from "./expressions";
20
- import {
21
- jobField,
22
- jobTracking,
23
- type RoutineProbes,
24
- ringTarget,
25
- writeProbes,
26
- } from "./instrumentation";
17
+ noResult,
18
+ type RoutineWriter,
19
+ writeAcquire,
20
+ writeRelease,
21
+ writeStatements,
22
+ } from "./statements";
27
23
  import {
28
24
  type CodesysSymbols,
29
25
  type EmissionContext,
30
- instrumentationFieldTypes,
31
- required,
26
+ owningBlock,
32
27
  } from "./symbols";
33
- import { callParameters } from "./telemetry";
34
28
 
35
29
  function routineHeader(
36
30
  symbols: CodesysSymbols,
37
31
  fn: CoreFunction | CoreFunctionBlock,
38
32
  name: string,
39
33
  ): { kind: GeneratedObject["kind"]; declaration: string } {
40
- if ("inputs" in fn) {
34
+ if (isBlockRoutine(fn)) {
41
35
  return { kind: "functionBlock", declaration: `FUNCTION_BLOCK ${name}` };
42
36
  }
43
37
  if (fn.owner) {
@@ -51,7 +45,7 @@ function routineHeader(
51
45
  }
52
46
  return {
53
47
  kind: "function",
54
- declaration: `FUNCTION ${name} : ${fn.result ? symbols.targetTypes.name(fn.result) : "BOOL"}`,
48
+ declaration: `FUNCTION ${name} : ${fn.result ? symbols.targetTypes.name(fn.result) : noResult.type}`,
55
49
  };
56
50
  }
57
51
 
@@ -59,489 +53,103 @@ function routineHeader(
59
53
  export function emitRoutine(
60
54
  context: EmissionContext,
61
55
  fn: CoreFunction | CoreFunctionBlock,
62
- ): { objects: GeneratedObject[]; mappings: SourceMapping[] } {
56
+ ): { objects: GeneratedObject[]; mappings: ObjectMapping[] } {
63
57
  const { plan, symbols, instrumentation } = context;
64
- const { core } = plan;
65
- const {
66
- blockNames,
67
- functionNames,
68
- references,
69
- targetTypes,
70
- typeMap,
71
- blocks,
72
- blockFields,
73
- retainedVariables,
74
- } = symbols;
75
- const objects: GeneratedObject[] = [];
76
- const mappings: SourceMapping[] = [];
77
- const block = "inputs" in fn ? fn : undefined;
78
- const method = "owner" in fn ? fn.owner : undefined;
58
+ const { targetTypes, typeMap } = symbols;
59
+ const mappings: ObjectMapping[] = [];
60
+ const block = isBlockRoutine(fn) ? fn : undefined;
61
+ const method = isBlockRoutine(fn) ? undefined : fn.owner;
79
62
  const program = symbols.programRoutines.has(fn.id);
80
- const owner = method ? required(blocks.get(method.block)) : block;
63
+ const owner = owningBlock(symbols, fn);
81
64
  const name = block
82
- ? required(blockNames.get(block.id))
83
- : required(functionNames.get(fn.id));
84
- const inputs = "parameters" in fn ? fn.parameters : fn.inputs;
85
- const state = owner ? [...owner.outputs, ...owner.state] : [];
86
- const mappingName = method ? fn.id : name;
87
- const routineScope = required(symbols.routineScopes.get(fn.id));
88
- const scope = new Map([...references, ...routineScope.references]);
89
- const locals = routineScope.names;
90
- const declarations = fn.locals.map(
91
- (item) =>
92
- ` ${required(scope.get(item.id))} : ${targetTypes.name(item.type)};`,
93
- );
94
- const declarationSpans = fn.locals.map((item) => item.span);
65
+ ? required(symbols.blockNames.get(block.id))
66
+ : required(symbols.functionNames.get(fn.id));
67
+ const inputs = isBlockRoutine(fn) ? fn.inputs : fn.parameters;
68
+ const map = (
69
+ file: ObjectMapping["file"],
70
+ line: number,
71
+ span: SourceSpan,
72
+ ): void => {
73
+ mappings.push({ object: fn.id, file, line, span });
74
+ };
75
+ const scope = required(symbols.routineScopes.get(fn.id));
76
+ const storage: StorageScope = {
77
+ symbols,
78
+ names: new Map([...symbols.references, ...scope.references]),
79
+ variableOf: coreTables(plan.core).variableOf,
80
+ };
81
+ const temporaries = fn.locals.map((item) => ({
82
+ declaration: ` ${storageName(storage, item.id)} : ${targetTypes.name(item.type)};`,
83
+ span: item.span,
84
+ }));
85
+ const declare = (declaration: string, span: SourceSpan): void => {
86
+ temporaries.push({ declaration, span });
87
+ };
95
88
  const mutex =
96
89
  method && owner?.runtime?.kind === "mailbox"
97
90
  ? required(symbols.mailboxLocks.get(owner.id))
98
91
  : undefined;
99
- const acquired = mutex ? locals.allocate("plc_acquired") : undefined;
100
- const unavailable =
101
- mutex && fn.result ? locals.allocate("plc_unavailable") : undefined;
102
- if (acquired) {
103
- declarations.push(` ${acquired} : BOOL;`);
104
- declarationSpans.push(fn.span);
105
- }
106
- if (unavailable && fn.result) {
107
- declarations.push(
108
- ` ${unavailable} : ${targetTypes.name(fn.result)} := ${targetTypes.literal(defaultValue(fn.result, typeMap), fn.result)};`,
109
- );
110
- declarationSpans.push(fn.span);
111
- }
112
- // Count target lines as they are appended; diagnostics use these exact offsets.
113
92
  const lines: string[] = [];
114
- const write = (line: string, depth: number, source?: SourceSpan): void => {
115
- lines.push(" ".repeat(depth) + line);
116
- if (source) {
117
- mappings.push({
118
- path: `${mappingName}/implementation.st`,
119
- line: lines.length,
120
- span: source,
121
- });
122
- }
123
- };
124
-
125
- // Only the holder releases, so a failed swap is spurious (see the acquire above); retry it.
126
- const release = (lock: string, depth: number, source?: SourceSpan) => {
127
- write(`WHILE NOT __COMPARE_AND_SWAP(ADR(${lock}), 1, 0) DO`, depth, source);
128
- write(";", depth + 1);
129
- write("END_WHILE;", depth);
130
- };
131
-
132
- const storage: StorageScope = {
133
- symbols,
134
- names: scope,
135
- types: new Map(
136
- [...core.variables, ...inputs, ...state, ...fn.locals].map((variable) => [
137
- variable.id,
138
- variable.type,
139
- ]),
140
- ),
141
- };
142
93
  const probes: RoutineProbes = {
143
94
  context,
144
95
  storage,
145
96
  task: instrumentation.analysis.tasks.get(fn.id),
146
97
  };
147
- // Aggregate constants are expanded into legal leaf assignments for ST.
148
- const assignConstant = (
149
- destination: string,
150
- value: Constant,
151
- id: string,
152
- depth: number,
153
- span: SourceSpan,
154
- ): void => {
155
- const type = required(typeMap.get(id));
156
- if (type.kind === "record" && value.kind === "record") {
157
- type.fields.forEach((field) => {
158
- assignConstant(
159
- `${destination}.${targetTypes.field(id, field.name)}`,
160
- required(value.fields[field.name]),
161
- field.type,
162
- depth,
163
- span,
164
- );
165
- });
166
- } else if (type.kind === "array" && value.kind === "array") {
167
- value.items.forEach((item, index) => {
168
- assignConstant(
169
- `${destination}[${type.lowerBound + index}]`,
170
- item,
171
- type.element,
172
- depth,
173
- span,
174
- );
175
- });
176
- } else {
177
- write(
178
- `${destination} := ${targetTypes.literal(value, id)};`,
179
- depth,
180
- span,
181
- );
182
- }
183
- };
184
-
185
- const assignResult = (
186
- destination: string,
187
- value: CoreExpression,
188
- depth: number,
189
- span: SourceSpan,
190
- ): void => {
191
- if (value.kind === "constant") {
192
- assignConstant(destination, value.value, value.type, depth, span);
193
- } else {
194
- write(
195
- `${destination} := ${expressionText(storage, value)};`,
196
- depth,
197
- span,
198
- );
199
- }
200
- };
201
-
202
98
  const tracked = block && instrumentation.fields.get(block.id);
203
- const body = (items: readonly CoreStatement[], depth: number): void => {
204
- for (const item of items) {
205
- switch (item.kind) {
206
- case "assign":
207
- writeProbes(probes, write, item, depth);
208
- if (
209
- tracked?.step &&
210
- block?.job &&
211
- item.root === block.state.find((field) => field.name === "step")?.id
212
- ) {
213
- write(
214
- `${tracked.step} := ${jobField(storage, block, "step")};`,
215
- depth,
216
- item.span,
217
- );
218
- }
219
- if (item.value.kind === "constant") {
220
- assignConstant(
221
- placeText(storage, item.root, item.path),
222
- item.value.value,
223
- item.value.type,
224
- depth,
225
- item.span,
226
- );
227
- } else {
228
- write(
229
- `${placeText(storage, item.root, item.path)} := ${expressionText(storage, item.value)};`,
230
- depth,
231
- item.span,
232
- );
233
- }
234
- break;
235
- case "blockUpdate": {
236
- const instance = instancedBlock(
237
- required(storage.types.get(item.instance)),
238
- typeMap,
239
- );
240
- if (!instance) {
241
- throw new Error("Invalid verified block receiver");
242
- }
243
- const target = required(blocks.get(instance.block));
244
- const arguments_ = Object.entries(item.inputs).map(
245
- ([input, value]) => {
246
- const formal = required(
247
- target.inputs.find((field) => field.name === input),
248
- );
249
- return `${required(required(blockFields.get(target.id)).get(formal.id))} := ${expressionText(storage, value)}`;
250
- },
251
- );
252
- // Service calls report the job that made them: a single-instance job passes its own id,
253
- // and everything between it and the call passes the id it was given.
254
- const job = instrumentation.fields.get(target.id)?.job;
255
- const id = instrumentation.jobIds.get(item.instance);
256
- const given = owner && instrumentation.fields.get(owner.id)?.job;
257
- if (job && (id || given)) {
258
- arguments_.push(`${job} := ${id ? `UDINT#${id}` : given}`);
259
- }
260
- const receiver = item.index
261
- ? `${storageName(storage, item.instance)}[${expressionText(storage, item.index)}]`
262
- : storageName(storage, item.instance);
263
- write(`${receiver}(${arguments_.join(", ")});`, depth, item.span);
264
- break;
265
- }
266
- case "invoke": {
267
- const receiver = item.instance
268
- ? `${storageName(storage, item.instance)}${item.index ? `[${expressionText(storage, item.index)}]` : ""}.`
269
- : "";
270
- const called = required(
271
- core.functions.find((fn) => fn.id === item.function),
272
- );
273
- const programCall = symbols.programRoutines.has(called.id);
274
- const arguments_ = item.arguments.map((value, index) => {
275
- if (
276
- !called.owner &&
277
- !programCall &&
278
- !called.parameters.some((parameter) => parameter.mode === "inOut")
279
- ) {
280
- return expressionText(storage, value);
281
- }
282
- const parameter = required(called.parameters[index]);
283
- const formal = required(
284
- required(symbols.routineScopes.get(called.id)).references.get(
285
- parameter.id,
286
- ),
287
- );
288
- return `${formal} := ${expressionText(storage, value)}`;
289
- });
290
- const call = `${receiver}${required(functionNames.get(item.function))}(${arguments_.join(", ")})`;
291
- if (programCall) {
292
- write(`${call};`, depth, item.span);
293
- if (item.destination) {
294
- write(
295
- `${storageName(storage, item.destination)} := ${required(functionNames.get(called.id))}.${required(symbols.programResults.get(called.id))};`,
296
- depth,
297
- item.span,
298
- );
299
- }
300
- break;
301
- }
302
- write(
303
- item.destination
304
- ? `${storageName(storage, item.destination)} := ${call};`
305
- : `${call};`,
306
- depth,
307
- item.span,
308
- );
309
- break;
310
- }
311
- case "if":
312
- write(
313
- `IF ${expressionText(storage, item.condition)} THEN`,
314
- depth,
315
- item.span,
316
- );
317
- body(item.then, depth + 1);
318
- if (item.else.length) {
319
- write("ELSE", depth, item.span);
320
- body(item.else, depth + 1);
321
- }
322
- write("END_IF;", depth, item.span);
323
- break;
324
- case "switch": {
325
- for (const [index, branch] of item.cases.entries()) {
326
- const conditions = branch.values.map(
327
- (value) =>
328
- `(${expressionText(storage, item.value)} = ${targetTypes.literal(value, item.value.type)})`,
329
- );
330
- write(
331
- `${index ? "ELSIF" : "IF"} ${conditions.join(" OR ")} THEN`,
332
- depth,
333
- item.span,
334
- );
335
- body(branch.body, depth + 1);
336
- }
337
- if (item.cases.length) {
338
- if (item.fallback.length) {
339
- write("ELSE", depth, item.span);
340
- }
341
- body(item.fallback, depth + 1);
342
- write("END_IF;", depth, item.span);
343
- } else {
344
- body(item.fallback, depth);
345
- }
346
- break;
347
- }
348
- case "for": {
349
- // Iterate with a DINT ordinal rather than overflowing the authored
350
- // counter at a width boundary. Reconstruct its typed value each scan.
351
- const counterType = storage.types.get(item.counter);
352
- if (!counterType || item.start.kind !== "integer") {
353
- throw new Error("Invalid verified loop");
354
- }
355
- if (!item.maxIterations) {
356
- if (item.counterScope === "existing") {
357
- write(
358
- `${storageName(storage, item.counter)} := ${item.dynamic ? expressionText(storage, item.dynamic.start) : targetTypes.literal(item.start, counterType)};`,
359
- depth,
360
- item.span,
361
- );
362
- }
363
- break;
364
- }
365
- const ordinal = locals.allocate("iteration");
366
- declarations.push(` ${ordinal} : DINT;`);
367
- declarationSpans.push(item.span);
368
- const wide = counterType === "ULINT" ? "ULINT" : "LINT";
369
- const ascending = BigInt(item.step) > 0n;
370
- const step =
371
- BigInt(item.step) < 0n ? -BigInt(item.step) : BigInt(item.step);
372
- const { dynamic } = item;
373
- const first = dynamic
374
- ? `TO_${wide}(${expressionText(storage, dynamic.start)})`
375
- : `${wide}#${item.start.value}`;
376
- // A dynamic range's iteration count is computed once, before the loop.
377
- const countIterations = ({
378
- limit,
379
- exclusive,
380
- }: NonNullable<typeof dynamic>): string => {
381
- const last = `TO_${wide}(${expressionText(storage, limit)})`;
382
- const count = locals.allocate("iterationCount");
383
- declarations.push(` ${count} : DINT;`);
384
- declarationSpans.push(item.span);
385
- const comparison = ascending ? "<" : ">";
386
- const inclusive = exclusive ? "" : "=";
387
- const distance = ascending
388
- ? `${last} - ${first}`
389
- : `${first} - ${last}`;
390
- const excluded = exclusive ? ` - ${wide}#1` : "";
391
- write(`${count} := DINT#0;`, depth, item.span);
392
- write(
393
- `IF ${first} ${comparison}${inclusive} ${last} THEN`,
394
- depth,
395
- item.span,
396
- );
397
- write(
398
- `${count} := ${wide}_TO_DINT(((${distance}${excluded}) / ${wide}#${step}) + ${wide}#1);`,
399
- depth + 1,
400
- item.span,
401
- );
402
- write("END_IF;", depth, item.span);
403
- return count;
404
- };
405
- const lastOrdinal = dynamic
406
- ? `${countIterations(dynamic)} - DINT#1`
407
- : `DINT#${item.maxIterations - 1}`;
408
- write(
409
- `FOR ${ordinal} := DINT#0 TO ${lastOrdinal} DO`,
410
- depth,
411
- item.span,
412
- );
413
- const counterValue = `${storageName(storage, item.counter)} := TO_${counterType}(${first} ${ascending ? "+" : "-"} (${wide}#${step} * DINT_TO_${wide}(${ordinal})));`;
414
- write(counterValue, depth + 1, item.span);
415
- body(item.body, depth + 1);
416
- write("END_FOR;", depth, item.span);
417
- // CODESYS keeps the ordinal at EXIT and advances it on normal
418
- // completion/CONTINUE. Reconstructing here preserves that distinction.
419
- if (item.counterScope === "existing") {
420
- write(counterValue, depth, item.span);
421
- }
422
- break;
423
- }
424
- case "return":
425
- writeProbes(probes, write, item, depth);
426
- if (block) {
427
- const { value } = item;
428
- if (value?.kind === "constant" && value.value.kind === "record") {
429
- for (const output of block.outputs) {
430
- assignConstant(
431
- storageName(storage, output.id),
432
- required(value.value.fields[output.name]),
433
- output.type,
434
- depth,
435
- item.span,
436
- );
437
- }
438
- } else if (value) {
439
- const returned = expressionText(storage, value);
440
- for (const output of block.outputs) {
441
- write(
442
- `${storageName(storage, output.id)} := ${returned}.${targetTypes.field(required(block.result), output.name)};`,
443
- depth,
444
- item.span,
445
- );
446
- }
447
- }
448
- } else if (program) {
449
- if (item.value) {
450
- assignResult(
451
- required(symbols.programResults.get(fn.id)),
452
- item.value,
453
- depth,
454
- item.span,
455
- );
456
- }
457
- } else if (!method || fn.result) {
458
- if (item.value) {
459
- assignResult(name, item.value, depth, item.span);
460
- } else {
461
- write(`${name} := TRUE;`, depth, item.span);
462
- }
463
- }
464
- if (mutex) {
465
- release(mutex, depth, item.span);
466
- }
467
- if (tracked?.track) {
468
- write(`${tracked.track}();`, depth);
469
- }
470
- write("RETURN;", depth, item.span);
471
- break;
472
- case "break":
473
- write("EXIT;", depth, item.span);
474
- break;
475
- case "continue":
476
- write("CONTINUE;", depth, item.span);
477
- break;
478
- case "telemetry": {
479
- const site = required(plan.telemetry?.calls.get(item));
480
- const arguments_ = callParameters(item).map(
481
- ({ name, value }) => `${name} := ${expressionText(storage, value)}`,
482
- );
483
- write(
484
- `${ringTarget(instrumentation, site.task)}.Record${site.id}(${arguments_.join(", ")});`,
485
- depth,
486
- item.span,
487
- );
488
- break;
489
- }
99
+ const routine: RoutineWriter = {
100
+ context,
101
+ fn,
102
+ name,
103
+ block,
104
+ owner,
105
+ method: method !== undefined,
106
+ program,
107
+ storage,
108
+ probes,
109
+ locals: scope.names,
110
+ mutex,
111
+ tracked,
112
+ write: (line, depth, source) => {
113
+ lines.push(" ".repeat(depth) + line);
114
+ if (source) {
115
+ map("implementation", lines.length, source);
490
116
  }
491
- }
117
+ },
118
+ declare,
492
119
  };
120
+ const { write } = routine;
493
121
 
494
- if (mutex && acquired) {
495
- // ARM64 implements __COMPARE_AND_SWAP with load-linked/store-conditional, which can fail
496
- // even when the word holds the expected value. Retry while the lock reads free.
497
- write(`${acquired} := FALSE;`, 0);
498
- write(`WHILE NOT ${acquired} AND ${mutex} = 0 DO`, 0);
499
- write(`${acquired} := __COMPARE_AND_SWAP(ADR(${mutex}), 0, 1);`, 1);
500
- write("END_WHILE;", 0);
501
- write(`IF NOT ${acquired} THEN`, 0);
502
- if (unavailable) {
503
- write(`${name} := ${unavailable};`, 1);
504
- }
505
- write("RETURN;", 1);
506
- write("END_IF;", 0);
122
+ if (mutex) {
123
+ writeAcquire(routine);
507
124
  }
508
125
  if (block && tracked?.track) {
509
126
  // Before the job's own early return, so a job started since its last call is seen.
510
127
  write(`${tracked.track}();`, 0);
511
- // The step it was in when it finished.
512
128
  if (tracked.step) {
513
129
  write(`${tracked.step} := ${jobField(storage, block, "step")};`, 0);
514
130
  }
515
131
  }
516
- body(fn.body, 0);
132
+ writeStatements(routine, fn.body, 0);
517
133
  if (tracked?.track) {
518
134
  write(`${tracked.track}();`, 0);
519
135
  }
520
136
  if (mutex) {
521
- release(mutex, 0);
137
+ writeRelease(routine, 0);
522
138
  }
523
139
  if (!block && !method && !program && !fn.result) {
524
- write(`${name} := TRUE;`, 0);
140
+ write(`${name} := ${noResult.value};`, 0);
525
141
  }
526
142
 
527
143
  const header = routineHeader(symbols, fn, name);
528
144
  const declaration = [header.declaration];
529
- mappings.push({
530
- path: `${mappingName}/declaration.st`,
531
- line: 1,
532
- span: fn.span,
533
- });
145
+ map("declaration", 1, fn.span);
534
146
  const section = (keyword: string, items: readonly Variable[]): void => {
535
147
  if (!items.length) {
536
148
  return;
537
149
  }
538
150
  declaration.push(keyword);
539
151
  for (const item of items) {
540
- mappings.push({
541
- path: `${mappingName}/declaration.st`,
542
- line: declaration.length + 1,
543
- span: item.span,
544
- });
152
+ map("declaration", declaration.length + 1, item.span);
545
153
  const initial =
546
154
  item.initial && !instancedBlock(item.type, typeMap)
547
155
  ? targetTypes.declarationInitializer(item.initial, item.type)
@@ -564,11 +172,11 @@ export function emitRoutine(
564
172
  if (tracked?.job) {
565
173
  declaration.push(
566
174
  "VAR_INPUT",
567
- ` ${tracked.job} : ${instrumentationFieldTypes.job};`,
175
+ ` ${tracked.job} : ${instrumentationFields.job};`,
568
176
  "END_VAR",
569
177
  );
570
178
  }
571
- if (program && "parameters" in fn && fn.result) {
179
+ if (program && !block && fn.result) {
572
180
  declaration.push(
573
181
  "VAR_OUTPUT",
574
182
  ` ${required(symbols.programResults.get(fn.id))} : ${targetTypes.name(fn.result)};`,
@@ -586,48 +194,54 @@ export function emitRoutine(
586
194
  section("VAR_OUTPUT", block.outputs);
587
195
  section(
588
196
  "VAR",
589
- block.state.filter((item) => !retainedVariables.has(item.id)),
197
+ block.state.filter((item) => !symbols.retainedVariables.has(item.id)),
590
198
  );
591
199
  section(
592
200
  "VAR RETAIN",
593
- block.state.filter((item) => retainedVariables.has(item.id)),
201
+ block.state.filter((item) => symbols.retainedVariables.has(item.id)),
594
202
  );
595
203
  const fields = (["busy", "step", "startedAt"] as const).flatMap((key) => {
596
204
  const field = tracked?.[key];
597
- return field ? [` ${field} : ${instrumentationFieldTypes[key]};`] : [];
205
+ return field ? [` ${field} : ${instrumentationFields[key]};`] : [];
598
206
  });
599
207
  if (fields.length) {
600
208
  declaration.push("VAR", ...fields, "END_VAR");
601
209
  }
602
210
  }
603
- if (declarations.length) {
211
+ if (temporaries.length) {
604
212
  declaration.push(block || program ? "VAR_TEMP" : "VAR");
605
- declarationSpans.forEach((span, index) => {
606
- mappings.push({
607
- path: `${mappingName}/declaration.st`,
608
- line: declaration.length + index + 1,
609
- span,
610
- });
213
+ temporaries.forEach(({ span }, index) => {
214
+ map("declaration", declaration.length + index + 1, span);
611
215
  });
612
- declaration.push(...declarations, "END_VAR");
216
+ declaration.push(
217
+ ...temporaries.map((temporary) => temporary.declaration),
218
+ "END_VAR",
219
+ );
613
220
  }
614
221
 
615
- objects.push({
222
+ const routineObject: GeneratedObject = {
616
223
  id: fn.id,
224
+ ...(method ? { parent: method.block } : {}),
617
225
  kind: header.kind,
618
226
  name,
619
227
  declaration: `${declaration.join("\n")}\n`,
620
228
  implementation: `${lines.join("\n")}\n`,
621
- });
622
- if (block && tracked?.track) {
623
- objects.push({
624
- id: `${fn.id}:${tracked.track}`,
625
- parent: fn.id,
626
- kind: "method",
627
- name: tracked.track,
628
- declaration: `METHOD PRIVATE ${tracked.track}\n`,
629
- implementation: jobTracking(probes, block, tracked),
630
- });
229
+ };
230
+ if (!block || !tracked?.track) {
231
+ return { objects: [routineObject], mappings };
631
232
  }
632
- return { objects, mappings };
233
+ return {
234
+ objects: [
235
+ routineObject,
236
+ {
237
+ id: `${fn.id}:${tracked.track}`,
238
+ parent: fn.id,
239
+ kind: "method",
240
+ name: tracked.track,
241
+ declaration: `METHOD PRIVATE ${tracked.track}\n`,
242
+ implementation: jobTracking(probes, block, tracked),
243
+ },
244
+ ],
245
+ mappings,
246
+ };
633
247
  }