@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
package/src/ir/share.ts CHANGED
@@ -1,15 +1,20 @@
1
+ import { parse } from "node:path";
1
2
  import {
3
+ admitCore,
2
4
  type CoreExpression,
3
5
  type CoreFunction,
4
6
  type CoreFunctionBlock,
5
7
  type CorePath,
6
8
  type CoreStatement,
9
+ constantIndex,
10
+ mapBodies,
7
11
  nestedBodies,
8
12
  type VerifiedCoreModule,
9
13
  } from "./core-model";
10
14
  import type { Variable } from "./model";
11
- import { admitCore } from "./normalize";
12
- import type { PlcType } from "./types";
15
+ import { mapExpression, mapPath, mapStatementExpressions } from "./operands";
16
+ import { type CoreTables, coreTables, lookup } from "./tables";
17
+ import { isValueType, type PlcType } from "./types";
13
18
 
14
19
  /**
15
20
  * Routines that are the same code over different storage, such as one method elaborated once per
@@ -38,7 +43,7 @@ export function shareRoutines(
38
43
  core: VerifiedCoreModule,
39
44
  partition: (routine: CoreFunction) => string | undefined,
40
45
  ): SharedRoutines {
41
- const types = new Map(core.types.map((type) => [type.id, type]));
46
+ const tables = coreTables(core);
42
47
  const globals = new Map(core.variables.map((item) => [item.id, item]));
43
48
  const entries = new Set(core.programs.map((program) => program.entry));
44
49
  const bodies = new Map<string, readonly CoreStatement[]>(
@@ -49,52 +54,29 @@ export function shareRoutines(
49
54
  );
50
55
  const merged = new Map<string, string>();
51
56
  const shared = new Map<string, CoreFunction>();
57
+ const body = (id: string) => lookup(bodies, id, "routine");
52
58
 
53
- // A reference can only bind to plain data: a block instance or a stored reference stays where it is.
54
- const plainData = (id: string, seen = new Set<string>()): boolean => {
55
- const type = types.get(id);
56
- if (!type || seen.has(id)) {
57
- return type !== undefined;
58
- }
59
- seen.add(id);
60
- if (type.kind === "block") {
61
- return false;
62
- }
63
- if (type.kind === "array") {
64
- return plainData(type.element, seen);
65
- }
66
- if (type.kind === "record") {
67
- return type.fields.every(
68
- (field) => field.mode !== "inOut" && plainData(field.type, seen),
69
- );
70
- }
71
- return true;
72
- };
73
59
  const roots: Roots = {
74
60
  anchorable: (root) => {
75
61
  const variable = globals.get(root);
76
62
  return variable !== undefined && variable.storage !== "constant";
77
63
  },
78
- type: (root) => globals.get(root)?.type,
79
- name: (root) => globals.get(root)?.name ?? "anchor",
80
- plainData: (type) => plainData(type),
64
+ variable: (root) => lookup(globals, root, "variable"),
65
+ // A reference can only bind to plain data: a block instance or a stored reference stays where it is.
66
+ plainData: (type) => isValueType(type, tables.types),
81
67
  };
82
68
 
83
69
  const candidates = core.functions.filter(
84
70
  (fn) => !fn.owner && !entries.has(fn.id),
85
71
  );
86
- for (const level of callLevels(candidates, bodies)) {
72
+ for (const level of callLevels(candidates, body)) {
87
73
  const groups = new Map<string, Anchored[]>();
88
74
  for (const fn of level) {
89
75
  const group = partition(fn);
90
76
  if (group === undefined) {
91
77
  continue;
92
78
  }
93
- const anchored = anchor(
94
- { ...fn, body: bodies.get(fn.id) ?? fn.body },
95
- types,
96
- roots,
97
- );
79
+ const anchored = anchor({ ...fn, body: body(fn.id) }, tables, roots);
98
80
  if (!anchored) {
99
81
  continue;
100
82
  }
@@ -111,15 +93,12 @@ export function shareRoutines(
111
93
  anchors: first.anchors.map((slot, index) =>
112
94
  members.some((member) => member.anchors[index]?.key !== slot.key),
113
95
  ),
114
- constants: first.constants.map((constant, index) =>
115
- members.some(
116
- (member) =>
117
- JSON.stringify(member.constants[index]?.value) !==
118
- JSON.stringify(constant.value),
119
- ),
120
- ),
96
+ constants: constantParameters(members),
121
97
  };
122
- shared.set(first.fn.id, mergedRoutine(first, varying, roots, types));
98
+ shared.set(
99
+ first.fn.id,
100
+ mergedRoutine(members, varying, roots, core.folded ?? []),
101
+ );
123
102
  for (const [index, member] of members.entries()) {
124
103
  if (index) {
125
104
  merged.set(member.fn.id, first.fn.id);
@@ -127,15 +106,17 @@ export function shareRoutines(
127
106
  calls.set(member.fn.id, {
128
107
  target: first.fn.id,
129
108
  borrows: member.anchors.filter((_, slot) => varying.anchors[slot]),
130
- values: member.constants.filter((_, slot) => varying.constants[slot]),
109
+ values: member.constants.filter(
110
+ (_, slot) => varying.constants[slot] === slot,
111
+ ),
131
112
  });
132
113
  }
133
114
  }
134
115
  if (!calls.size) {
135
116
  continue;
136
117
  }
137
- for (const [id, body] of bodies) {
138
- bodies.set(id, rewriteCalls(body, calls));
118
+ for (const [id, items] of bodies) {
119
+ bodies.set(id, rewriteCalls(items, calls));
139
120
  }
140
121
  }
141
122
  if (!merged.size) {
@@ -146,17 +127,10 @@ export function shareRoutines(
146
127
  if (merged.has(fn.id)) {
147
128
  return [];
148
129
  }
149
- const routine = shared.get(fn.id);
150
- if (routine) {
151
- return [routine];
152
- }
153
- return [{ ...fn, body: bodies.get(fn.id) ?? fn.body }];
130
+ return [shared.get(fn.id) ?? { ...fn, body: body(fn.id) }];
154
131
  });
155
132
  const blocks = core.blocks.map(
156
- (block): CoreFunctionBlock => ({
157
- ...block,
158
- body: bodies.get(block.id) ?? block.body,
159
- }),
133
+ (block): CoreFunctionBlock => ({ ...block, body: body(block.id) }),
160
134
  );
161
135
  return {
162
136
  core: admitCore({ ...core, functions, blocks }),
@@ -167,8 +141,7 @@ export function shareRoutines(
167
141
  interface Roots {
168
142
  /** Whether a root is module storage, whose places a routine can borrow. */
169
143
  anchorable: (root: string) => boolean;
170
- type: (root: string) => string | undefined;
171
- name: (root: string) => string;
144
+ variable: (root: string) => Variable;
172
145
  /** Whether a type holds only data, which a reference can bind to. */
173
146
  plainData: (type: string) => boolean;
174
147
  }
@@ -180,19 +153,23 @@ interface Borrow {
180
153
  type: string;
181
154
  }
182
155
 
156
+ type ConstantExpression = Extract<CoreExpression, { kind: "constant" }>;
157
+
183
158
  /** A routine's body with its anchors numbered in the order it first reaches them. */
184
159
  interface Anchored {
185
160
  fn: CoreFunction;
186
161
  key: string;
187
162
  anchors: readonly (Borrow & { key: string })[];
188
- /** Each scalar constant the body evaluates, in order. */
189
- constants: readonly Extract<CoreExpression, { kind: "constant" }>[];
163
+ /** Each scalar constant the body evaluates, in the order it first reaches them. */
164
+ constants: readonly ConstantExpression[];
165
+ /** Each scalar constant's number, which the key writes in its place. */
166
+ slots: ReadonlyMap<ConstantExpression, number>;
190
167
  }
191
168
 
192
169
  /** Candidate routines, callees before their callers. A routine's level is one more than its deepest callee's. */
193
170
  function callLevels(
194
171
  candidates: readonly CoreFunction[],
195
- bodies: ReadonlyMap<string, readonly CoreStatement[]>,
172
+ body: (id: string) => readonly CoreStatement[],
196
173
  ): CoreFunction[][] {
197
174
  const levels = new Map<string, number>();
198
175
  const callees = (items: readonly CoreStatement[], found: Set<string>) => {
@@ -200,47 +177,37 @@ function callLevels(
200
177
  if (item.kind === "invoke") {
201
178
  found.add(item.function);
202
179
  }
203
- for (const body of nestedBodies(item)) {
204
- callees(body, found);
180
+ for (const nested of nestedBodies(item)) {
181
+ callees(nested, found);
205
182
  }
206
183
  }
207
184
  return found;
208
185
  };
209
- const level = (id: string, path: Set<string>): number => {
186
+ const level = (id: string): number => {
210
187
  const known = levels.get(id);
211
188
  if (known !== undefined) {
212
189
  return known;
213
190
  }
214
- // Verified routines do not recurse; a cycle would only stop merging, never recurse here.
215
- if (path.has(id)) {
216
- return 0;
217
- }
218
- path.add(id);
219
- const deepest = [...callees(bodies.get(id) ?? [], new Set())].reduce(
220
- (depth, callee) => Math.max(depth, level(callee, path) + 1),
191
+ const deepest = [...callees(body(id), new Set())].reduce(
192
+ (depth, callee) => Math.max(depth, level(callee) + 1),
221
193
  0,
222
194
  );
223
- path.delete(id);
224
195
  levels.set(id, deepest);
225
196
  return deepest;
226
197
  };
227
198
  const ordered: CoreFunction[][] = [];
228
199
  for (const fn of candidates) {
229
- const depth = level(fn.id, new Set());
200
+ const depth = level(fn.id);
230
201
  ordered[depth] = [...(ordered[depth] ?? []), fn];
231
202
  }
232
203
  return ordered.filter((items) => items !== undefined);
233
204
  }
234
205
 
235
- const staticIndex = (segment: CorePath[number]) =>
236
- segment.kind === "index" &&
237
- segment.value.kind === "constant" &&
238
- segment.value.value.kind === "integer";
239
-
240
206
  /** The fixed part of a place that an anchor holds, by the rule `shareRoutines` describes. */
241
207
  function anchorLength(path: CorePath): number {
242
208
  const dynamic = path.findIndex(
243
- (segment) => segment.kind === "index" && !staticIndex(segment),
209
+ (segment) =>
210
+ segment.kind === "index" && constantIndex(segment.value) === undefined,
244
211
  );
245
212
  if (dynamic >= 0) {
246
213
  return dynamic;
@@ -248,36 +215,21 @@ function anchorLength(path: CorePath): number {
248
215
  return path.at(-1)?.kind === "field" ? path.length - 1 : path.length;
249
216
  }
250
217
 
251
- const pathType = (
252
- root: string,
253
- path: CorePath,
254
- types: ReadonlyMap<string, PlcType>,
255
- ): string | undefined =>
256
- path.reduce<string | undefined>((id, segment) => {
257
- const type = id === undefined ? undefined : types.get(id);
258
- if (segment.kind === "field" && type?.kind === "record") {
259
- return type.fields.find((field) => field.name === segment.name)?.type;
260
- }
261
- if (segment.kind === "index" && type?.kind === "array") {
262
- return type.element;
263
- }
264
- return undefined;
265
- }, root);
266
-
267
218
  const constantText = (segment: CorePath[number]) =>
268
219
  segment.kind === "field"
269
220
  ? `.${segment.name}`
270
221
  : `[${segment.value.kind === "constant" ? JSON.stringify(segment.value.value) : "?"}]`;
271
222
 
272
223
  /**
273
- * Numbers a routine's anchors and writes its body with each anchored place as its anchor's number
274
- * and the rest of its path, and its own variables by position. Two routines with the same key run
275
- * the same statements over their own anchors. Undefined when a place cannot be anchored the same
276
- * way in every routine, such as a loop counter in module storage.
224
+ * Numbers a routine's anchors and scalar constants and writes its body with each anchored place
225
+ * as its anchor's number and the rest of its path, each constant as its number, and its own
226
+ * variables by position. Two routines with the same key run the same statements over their own
227
+ * anchors and constants. Undefined when a place cannot be anchored the same way in every routine,
228
+ * such as a loop counter in module storage.
277
229
  */
278
230
  function anchor(
279
231
  fn: CoreFunction,
280
- types: ReadonlyMap<string, PlcType>,
232
+ tables: CoreTables,
281
233
  roots: Roots,
282
234
  ): Anchored | undefined {
283
235
  const own = new Map(
@@ -287,34 +239,33 @@ function anchor(
287
239
  ]),
288
240
  );
289
241
  const anchors: (Borrow & { key: string })[] = [];
290
- const constants: Extract<CoreExpression, { kind: "constant" }>[] = [];
242
+ const slots = new Map<ConstantExpression, number>();
291
243
  const numbers = new Map<string, number>();
292
244
  const rewrite: PlaceRewrite = {
293
245
  constant: (value) => {
294
- if (!scalarConstant(value, types)) {
246
+ if (!scalarConstant(value, tables.types)) {
295
247
  return value;
296
248
  }
297
- constants.push(value);
249
+ const slot = slots.get(value) ?? slots.size;
250
+ slots.set(value, slot);
298
251
  return {
299
252
  kind: "load",
300
253
  type: value.type,
301
254
  span: value.span,
302
- root: `$${constants.length - 1}`,
255
+ root: `$${slot}`,
303
256
  };
304
257
  },
305
- place: (root, path) => {
258
+ place: (root, path, index) => {
306
259
  if (!roots.anchorable(root)) {
307
- return { root: own.get(root) ?? root, path: mapPath(path) };
260
+ return { root: own.get(root) ?? root, path: mapPath(path, index) };
308
261
  }
309
262
  const { fixed, key } = anchorOf(root, path);
310
- const rest = mapPath(path.slice(fixed.length));
263
+ const rest = mapPath(path.slice(fixed.length), index);
311
264
  const known = numbers.get(key);
312
265
  if (known !== undefined) {
313
266
  return { root: `@${known}`, path: rest };
314
267
  }
315
- const rootType = roots.type(root);
316
- const type =
317
- rootType === undefined ? undefined : pathType(rootType, fixed, types);
268
+ const type = tables.placeType(roots.variable(root).type, fixed)?.id;
318
269
  if (type === undefined) {
319
270
  throw new Unanchored();
320
271
  }
@@ -333,12 +284,6 @@ function anchor(
333
284
  return own.get(root) ?? root;
334
285
  },
335
286
  };
336
- const mapPath = (path: CorePath): CorePath =>
337
- path.map((segment) =>
338
- segment.kind === "field"
339
- ? segment
340
- : { kind: "index", value: rewriteExpression(segment.value, rewrite) },
341
- );
342
287
  try {
343
288
  const body = rewriteStatements(fn.body, rewrite);
344
289
  // Not the name: the elaborator numbers each instance's copy of a routine. The declaration
@@ -350,7 +295,13 @@ function anchor(
350
295
  locals: fn.locals.map(({ id, ...rest }) => rest),
351
296
  anchors: anchors.map((item) => item.type),
352
297
  };
353
- return { fn, key: JSON.stringify([signature, body]), anchors, constants };
298
+ return {
299
+ fn,
300
+ key: JSON.stringify([signature, body]),
301
+ anchors,
302
+ constants: [...slots.keys()],
303
+ slots,
304
+ };
354
305
  } catch (cause) {
355
306
  if (cause instanceof Unanchored) {
356
307
  return undefined;
@@ -365,87 +316,111 @@ const anchorOf = (root: string, path: CorePath) => {
365
316
  return { fixed, key: `${root}${fixed.map(constantText).join("")}` };
366
317
  };
367
318
 
319
+ /**
320
+ * Each constant's parameter, by number: undefined when every routine of the group evaluates the
321
+ * same value there, else the first constant whose values in every routine are the same as its
322
+ * own, so a value the routines take at several places is one parameter.
323
+ */
324
+ function constantParameters(
325
+ members: readonly Anchored[],
326
+ ): (number | undefined)[] {
327
+ const [first] = members;
328
+ const firstSlots = new Map<string, number>();
329
+ return (first?.constants ?? []).map((constant, index) => {
330
+ const values = members.map((member) => member.constants[index]?.value);
331
+ if (
332
+ values.every(
333
+ (value) => JSON.stringify(value) === JSON.stringify(constant.value),
334
+ )
335
+ ) {
336
+ return undefined;
337
+ }
338
+ const key = JSON.stringify([constant.type, values]);
339
+ const slot = firstSlots.get(key) ?? index;
340
+ firstSlots.set(key, slot);
341
+ return slot;
342
+ });
343
+ }
344
+
368
345
  /**
369
346
  * The first routine of a group, taking each anchor that differs between the routines as an
370
347
  * `InOut` parameter after its own parameters, then each constant that differs as a value
371
- * parameter. Anchors and constants all of them share stay in place.
348
+ * parameter. Anchors and constants all of them share stay in place. Each parameter is named for
349
+ * what it holds: an anchor for its path, a constant for the field setup folded it from.
372
350
  */
373
351
  function mergedRoutine(
374
- { fn, anchors, constants }: Anchored,
352
+ members: readonly Anchored[],
375
353
  varying: Varying,
376
354
  roots: Roots,
377
- types: ReadonlyMap<string, PlcType>,
355
+ folded: Folded,
378
356
  ): CoreFunction {
357
+ const [{ fn, anchors, constants, slots }] = required(members);
358
+ const anchorNames = borrowNames(members, varying, roots);
379
359
  const borrowed = new Map<number, Variable>();
380
360
  for (const [index, slot] of anchors.entries()) {
381
- if (!varying.anchors[index]) {
361
+ const name = anchorNames.get(index);
362
+ if (name === undefined) {
382
363
  continue;
383
364
  }
384
- const field = [...slot.path]
385
- .reverse()
386
- .find((segment) => segment.kind === "field");
387
365
  borrowed.set(index, {
388
366
  id: `${fn.id}:anchor${index}`,
389
- name: field?.kind === "field" ? field.name : roots.name(slot.root),
367
+ name,
390
368
  type: slot.type,
391
369
  storage: "parameter",
392
370
  mutable: true,
393
- retain: false,
371
+ retention: "none",
394
372
  mode: "inOut",
395
373
  span: fn.span,
396
374
  });
397
375
  }
398
376
  const values = new Map<number, Variable>();
399
377
  for (const [index, constant] of constants.entries()) {
400
- if (varying.constants[index]) {
378
+ if (varying.constants[index] === index) {
401
379
  values.set(index, {
402
380
  id: `${fn.id}:value${index}`,
403
- name: "value",
381
+ name: foldedName(members, index, folded) ?? "value",
404
382
  type: constant.type,
405
383
  storage: "parameter",
406
384
  mutable: false,
407
- retain: false,
385
+ retention: "none",
408
386
  span: fn.span,
409
387
  });
410
388
  }
411
389
  }
412
- const slots = new Map(anchors.map((slot, index) => [slot.key, index]));
413
- // Scalar constants come in the order `anchor` numbered them in.
414
- const order = constants.keys();
390
+ const anchorSlots = new Map(anchors.map((slot, index) => [slot.key, index]));
391
+ const parameter = (
392
+ parameters: ReadonlyMap<number, Variable>,
393
+ slot: number | undefined,
394
+ ) => (slot === undefined ? undefined : parameters.get(slot));
415
395
  const rewrite: PlaceRewrite = {
416
396
  constant: (value) => {
417
- if (!scalarConstant(value, types)) {
418
- return value;
419
- }
420
- const parameter = values.get(order.next().value ?? -1);
421
- return parameter
397
+ const slot = slots.get(value);
398
+ const replacement = parameter(
399
+ values,
400
+ slot === undefined ? undefined : varying.constants[slot],
401
+ );
402
+ return replacement
422
403
  ? {
423
404
  kind: "load",
424
405
  type: value.type,
425
406
  span: value.span,
426
- root: parameter.id,
407
+ root: replacement.id,
427
408
  }
428
409
  : value;
429
410
  },
430
- place: (root, path) => {
411
+ place: (root, path, index) => {
431
412
  if (!roots.anchorable(root)) {
432
- return { root, path: mapPath(path) };
413
+ return { root, path: mapPath(path, index) };
433
414
  }
434
415
  const { fixed, key } = anchorOf(root, path);
435
- const rest = mapPath(path.slice(fixed.length));
436
- const parameter = borrowed.get(slots.get(key) ?? -1);
437
- return parameter
438
- ? { root: parameter.id, path: rest }
416
+ const rest = mapPath(path.slice(fixed.length), index);
417
+ const borrow = parameter(borrowed, anchorSlots.get(key));
418
+ return borrow
419
+ ? { root: borrow.id, path: rest }
439
420
  : { root, path: [...fixed, ...rest] };
440
421
  },
441
422
  identity: (root) => root,
442
423
  };
443
- const mapPath = (path: CorePath): CorePath =>
444
- path.map((segment) =>
445
- segment.kind === "field"
446
- ? segment
447
- : { kind: "index", value: rewriteExpression(segment.value, rewrite) },
448
- );
449
424
  return {
450
425
  ...fn,
451
426
  parameters: [...fn.parameters, ...borrowed.values(), ...values.values()],
@@ -453,10 +428,110 @@ function mergedRoutine(
453
428
  };
454
429
  }
455
430
 
456
- /** Which anchors and constants differ between the routines of a group, by number. */
431
+ /** Which anchors differ between the routines of a group, and each constant's parameter, by number. */
457
432
  interface Varying {
458
433
  anchors: readonly boolean[];
459
- constants: readonly boolean[];
434
+ constants: readonly (number | undefined)[];
435
+ }
436
+
437
+ type Folded = NonNullable<VerifiedCoreModule["folded"]>;
438
+
439
+ const required = <T>(items: readonly T[]): [T, ...T[]] => {
440
+ const [first, ...rest] = items;
441
+ if (first === undefined) {
442
+ throw new Error("A merged group has routines.");
443
+ }
444
+ return [first, ...rest];
445
+ };
446
+
447
+ /**
448
+ * The field a constant parameter stands for: the one field of each routine's instance that setup
449
+ * folded to the value the routine evaluates there, as `settle.durationMs` of `pumps[0]` is 500.
450
+ * Undefined when a routine has no instance or no single field answers in every routine.
451
+ */
452
+ function foldedName(
453
+ members: readonly Anchored[],
454
+ slot: number,
455
+ folded: Folded,
456
+ ): string | undefined {
457
+ const fields = members.map((member) => {
458
+ const instance = member.fn.origin?.instance;
459
+ const constant = member.constants[slot];
460
+ if (instance === undefined || constant === undefined) {
461
+ return new Set<string>();
462
+ }
463
+ return new Set(
464
+ folded.flatMap((item) =>
465
+ item.path.startsWith(`${instance}.`) &&
466
+ JSON.stringify(item.value) === JSON.stringify(constant.value)
467
+ ? [item.path.slice(instance.length + 1)]
468
+ : [],
469
+ ),
470
+ );
471
+ });
472
+ const [first, ...rest] = fields;
473
+ const shared = [...(first ?? [])].filter((field) =>
474
+ rest.every((other) => other.has(field)),
475
+ );
476
+ const [only, ...others] = shared;
477
+ return only !== undefined && !others.length
478
+ ? only.replace(/[.[\]]+/g, "_").replace(/_$/, "")
479
+ : undefined;
480
+ }
481
+
482
+ /**
483
+ * Each borrowed anchor's name, by number: its full fixed path, as `track_bins`, where an index
484
+ * that differs between the routines reads `item`, since no one name can hold the index each call
485
+ * passes, and a root or field that differs is left out. Anchors of different modules that would
486
+ * share a name are told apart by their module.
487
+ */
488
+ function borrowNames(
489
+ members: readonly Anchored[],
490
+ varying: Varying,
491
+ roots: Roots,
492
+ ): Map<number, string> {
493
+ const words = (borrow: Borrow): string[] => [
494
+ roots.variable(borrow.root).name,
495
+ ...borrow.path.map((segment) =>
496
+ segment.kind === "field"
497
+ ? segment.name
498
+ : String(constantIndex(segment.value) ?? "item"),
499
+ ),
500
+ ];
501
+ const [first] = required(members);
502
+ const names = new Map<number, string>();
503
+ for (const [index, slot] of first.anchors.entries()) {
504
+ if (!varying.anchors[index]) {
505
+ continue;
506
+ }
507
+ const each = members.map((member) => {
508
+ const borrow = member.anchors[index];
509
+ return borrow ? words(borrow) : [];
510
+ });
511
+ const own = words(slot);
512
+ const name = own.flatMap((word, position) => {
513
+ if (each.every((other) => other[position] === word)) {
514
+ return [word];
515
+ }
516
+ const segment = slot.path[position - 1];
517
+ return segment?.kind === "index" ? ["item"] : [];
518
+ });
519
+ names.set(index, name.join("_") || "item");
520
+ }
521
+ const module = (index: number): string => {
522
+ const slot = first.anchors[index];
523
+ return slot ? parse(roots.variable(slot.root).span.file).name : "";
524
+ };
525
+ const modules = new Map<string, Set<string>>();
526
+ for (const [index, name] of names) {
527
+ modules.set(name, (modules.get(name) ?? new Set()).add(module(index)));
528
+ }
529
+ return new Map(
530
+ [...names].map(([index, name]) => [
531
+ index,
532
+ (modules.get(name)?.size ?? 0) > 1 ? `${module(index)}_${name}` : name,
533
+ ]),
534
+ );
460
535
  }
461
536
 
462
537
  /** What a call to a merged routine adds after its own arguments. */
@@ -472,68 +547,52 @@ function rewriteCalls(
472
547
  calls: ReadonlyMap<string, MergedCall>,
473
548
  ): CoreStatement[] {
474
549
  return items.map((item): CoreStatement => {
475
- if (item.kind === "invoke") {
476
- const call = calls.get(item.function);
477
- if (!call) {
478
- return item;
479
- }
480
- return {
481
- ...item,
482
- function: call.target,
483
- arguments: [
484
- ...item.arguments,
485
- ...call.borrows.map(
486
- (borrow): CoreExpression => ({
487
- kind: "borrow",
488
- type: borrow.type,
489
- span: item.span,
490
- place: { root: borrow.root, path: borrow.path },
491
- }),
492
- ),
493
- ...call.values,
494
- ],
495
- };
550
+ if (item.kind !== "invoke") {
551
+ return mapBodies(item, (body) => rewriteCalls(body, calls));
496
552
  }
497
- switch (item.kind) {
498
- case "if":
499
- return {
500
- ...item,
501
- // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
502
- then: rewriteCalls(item.then, calls),
503
- else: rewriteCalls(item.else, calls),
504
- };
505
- case "switch":
506
- return {
507
- ...item,
508
- cases: item.cases.map((branch) => ({
509
- ...branch,
510
- body: rewriteCalls(branch.body, calls),
511
- })),
512
- fallback: rewriteCalls(item.fallback, calls),
513
- };
514
- case "for":
515
- return { ...item, body: rewriteCalls(item.body, calls) };
516
- default:
517
- return item;
553
+ const call = calls.get(item.function);
554
+ if (!call) {
555
+ return item;
518
556
  }
557
+ return {
558
+ ...item,
559
+ function: call.target,
560
+ arguments: [
561
+ ...item.arguments,
562
+ ...call.borrows.map(
563
+ (borrow): CoreExpression => ({
564
+ kind: "borrow",
565
+ type: borrow.type,
566
+ span: item.span,
567
+ place: { root: borrow.root, path: borrow.path },
568
+ }),
569
+ ),
570
+ // A fresh constant per call site: every call to one routine shares `call.values`, and `anchor`
571
+ // gives a repeated constant object one slot.
572
+ ...call.values.map((value) => ({ ...value })),
573
+ ],
574
+ };
519
575
  });
520
576
  }
521
577
 
522
578
  class Unanchored extends Error {}
523
579
 
524
580
  interface PlaceRewrite {
525
- place: (root: string, path: CorePath) => { root: string; path: CorePath };
581
+ /** A place and the rewrite of each index along it. */
582
+ place: (
583
+ root: string,
584
+ path: CorePath,
585
+ index: (value: CoreExpression) => CoreExpression,
586
+ ) => { root: string; path: CorePath };
526
587
  /** A root a statement names without a path: a loop counter, call destination or block instance. */
527
588
  identity: (root: string) => string;
528
- /** A scalar constant the body evaluates; case labels and loop bounds are not expressions. */
529
- constant: (
530
- value: Extract<CoreExpression, { kind: "constant" }>,
531
- ) => CoreExpression;
589
+ /** A constant the body evaluates; case labels and loop bounds are not expressions. */
590
+ constant: (value: ConstantExpression) => CoreExpression;
532
591
  }
533
592
 
534
593
  /** Constants a routine can take as a value parameter instead: scalars of an elementary or enum type. */
535
594
  const scalarConstant = (
536
- value: Extract<CoreExpression, { kind: "constant" }>,
595
+ value: ConstantExpression,
537
596
  types: ReadonlyMap<string, PlcType>,
538
597
  ) =>
539
598
  ["bool", "integer", "float", "duration", "calendar"].includes(
@@ -544,56 +603,46 @@ function rewriteExpression(
544
603
  value: CoreExpression,
545
604
  rewrite: PlaceRewrite,
546
605
  ): CoreExpression {
547
- switch (value.kind) {
548
- case "constant":
549
- return rewrite.constant(value);
550
- case "load": {
551
- const place = rewrite.place(value.root, value.path ?? []);
552
- return {
553
- ...value,
554
- root: place.root,
555
- ...(value.path || place.path.length ? { path: place.path } : {}),
556
- };
557
- }
558
- case "borrow":
559
- return {
560
- ...value,
561
- place: rewrite.place(value.place.root, value.place.path),
562
- };
563
- case "unary":
564
- case "convert":
565
- return { ...value, operand: rewriteExpression(value.operand, rewrite) };
566
- case "binary":
567
- return {
568
- ...value,
569
- left: rewriteExpression(value.left, rewrite),
570
- right: rewriteExpression(value.right, rewrite),
571
- };
606
+ const index = (operand: CoreExpression) =>
607
+ rewriteExpression(operand, rewrite);
608
+ if (value.kind === "constant") {
609
+ return rewrite.constant(value);
572
610
  }
611
+ if (value.kind === "load") {
612
+ const place = rewrite.place(value.root, value.path ?? [], index);
613
+ return {
614
+ ...value,
615
+ root: place.root,
616
+ ...(value.path || place.path.length ? { path: place.path } : {}),
617
+ };
618
+ }
619
+ if (value.kind === "borrow") {
620
+ return {
621
+ ...value,
622
+ place: rewrite.place(value.place.root, value.place.path, index),
623
+ };
624
+ }
625
+ return mapExpression(value, index);
573
626
  }
574
627
 
575
628
  function rewriteStatements(
576
629
  items: readonly CoreStatement[],
577
630
  rewrite: PlaceRewrite,
578
631
  ): CoreStatement[] {
579
- const expression = (value: CoreExpression) =>
580
- rewriteExpression(value, rewrite);
581
- const statements = (body: readonly CoreStatement[]) =>
582
- rewriteStatements(body, rewrite);
583
- return items.map((item) =>
584
- rewriteStatement(item, rewrite, expression, statements),
585
- );
632
+ return items.map((item) => rewriteStatement(item, rewrite));
586
633
  }
587
634
 
588
635
  function rewriteStatement(
589
636
  item: CoreStatement,
590
637
  rewrite: PlaceRewrite,
591
- expression: (value: CoreExpression) => CoreExpression,
592
- statements: (body: readonly CoreStatement[]) => CoreStatement[],
593
638
  ): CoreStatement {
639
+ const expression = (value: CoreExpression) =>
640
+ rewriteExpression(value, rewrite);
641
+ const statements = (body: readonly CoreStatement[]) =>
642
+ rewriteStatements(body, rewrite);
594
643
  switch (item.kind) {
595
644
  case "assign": {
596
- const place = rewrite.place(item.root, item.path ?? []);
645
+ const place = rewrite.place(item.root, item.path ?? [], expression);
597
646
  return {
598
647
  ...item,
599
648
  root: place.root,
@@ -601,86 +650,42 @@ function rewriteStatement(
601
650
  value: expression(item.value),
602
651
  };
603
652
  }
604
- case "if":
605
- return {
606
- ...item,
607
- condition: expression(item.condition),
608
- // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
609
- then: statements(item.then),
610
- else: statements(item.else),
611
- };
612
- case "switch":
613
- return {
614
- ...item,
615
- value: expression(item.value),
616
- cases: item.cases.map((branch) => ({
617
- ...branch,
618
- body: statements(branch.body),
619
- })),
620
- fallback: statements(item.fallback),
621
- };
622
653
  case "for":
623
- return {
624
- ...item,
625
- counter: rewrite.identity(item.counter),
626
- ...(item.dynamic && {
627
- dynamic: {
628
- ...item.dynamic,
629
- start: expression(item.dynamic.start),
630
- limit: expression(item.dynamic.limit),
631
- },
632
- }),
633
- body: statements(item.body),
634
- };
654
+ return mapBodies(
655
+ mapStatementExpressions(
656
+ { ...item, counter: rewrite.identity(item.counter) },
657
+ expression,
658
+ ),
659
+ statements,
660
+ );
635
661
  case "invoke":
636
- return {
637
- ...item,
638
- ...(item.instance !== undefined && {
639
- instance: rewrite.identity(item.instance),
640
- }),
641
- ...(item.index && { index: expression(item.index) }),
642
- arguments: item.arguments.map(expression),
643
- ...(item.destination !== undefined && {
644
- destination: rewrite.identity(item.destination),
645
- }),
646
- };
662
+ return mapStatementExpressions(
663
+ {
664
+ ...item,
665
+ ...(item.instance !== undefined && {
666
+ instance: rewrite.identity(item.instance),
667
+ }),
668
+ ...(item.destination !== undefined && {
669
+ destination: rewrite.identity(item.destination),
670
+ }),
671
+ },
672
+ expression,
673
+ );
647
674
  case "blockUpdate":
648
- return {
649
- ...item,
650
- instance: rewrite.identity(item.instance),
651
- ...(item.index && { index: expression(item.index) }),
652
- inputs: Object.fromEntries(
653
- Object.entries(item.inputs).map(([name, input]) => [
654
- name,
655
- expression(input),
656
- ]),
657
- ),
658
- };
675
+ return mapStatementExpressions(
676
+ { ...item, instance: rewrite.identity(item.instance) },
677
+ expression,
678
+ );
679
+ case "if":
680
+ case "switch":
659
681
  case "return":
660
- return item.value ? { ...item, value: expression(item.value) } : item;
661
682
  case "telemetry":
662
- return {
663
- ...item,
664
- properties: item.properties.map((property) => ({
665
- ...property,
666
- value: expression(property.value),
667
- ...(property.length && { length: expression(property.length) }),
668
- })),
669
- ...(item.record.kind === "exception" && {
670
- record: { ...item.record, code: expression(item.record.code) },
671
- }),
672
- };
673
683
  case "break":
674
684
  case "continue":
675
- return item;
685
+ return mapBodies(mapStatementExpressions(item, expression), statements);
676
686
  }
677
687
  }
678
688
 
679
- const returns = (items: readonly CoreStatement[]): boolean =>
680
- items.some(
681
- (item) => item.kind === "return" || nestedBodies(item).some(returns),
682
- );
683
-
684
689
  /** A routine that only returns a constant, or does nothing: what each of its calls amounts to. */
685
690
  function constantResult(
686
691
  fn: CoreFunction,
@@ -744,50 +749,25 @@ export function foldConstantRoutines(core: VerifiedCoreModule): {
744
749
  const called = new Set<string>();
745
750
  const fold = (items: readonly CoreStatement[]): CoreStatement[] =>
746
751
  items.flatMap((item): CoreStatement[] => {
747
- if (item.kind === "invoke") {
748
- const result = constants.get(item.function);
749
- if (!result || !item.arguments.every(plainArgument)) {
750
- called.add(item.function);
751
- return [item];
752
- }
753
- if (item.destination === undefined || !result.value) {
754
- return [];
755
- }
756
- return [
757
- {
758
- kind: "assign",
759
- span: item.span,
760
- root: item.destination,
761
- value: { ...result.value, span: item.span },
762
- },
763
- ];
752
+ if (item.kind !== "invoke") {
753
+ return [mapBodies(item, fold)];
754
+ }
755
+ const result = constants.get(item.function);
756
+ if (!result || !item.arguments.every(plainArgument)) {
757
+ called.add(item.function);
758
+ return [item];
764
759
  }
765
- switch (item.kind) {
766
- case "if":
767
- return [
768
- {
769
- ...item,
770
- // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
771
- then: fold(item.then),
772
- else: fold(item.else),
773
- },
774
- ];
775
- case "switch":
776
- return [
777
- {
778
- ...item,
779
- cases: item.cases.map((branch) => ({
780
- ...branch,
781
- body: fold(branch.body),
782
- })),
783
- fallback: fold(item.fallback),
784
- },
785
- ];
786
- case "for":
787
- return [{ ...item, body: fold(item.body) }];
788
- default:
789
- return [item];
760
+ if (item.destination === undefined || !result.value) {
761
+ return [];
790
762
  }
763
+ return [
764
+ {
765
+ kind: "assign",
766
+ span: item.span,
767
+ root: item.destination,
768
+ value: { ...result.value, span: item.span },
769
+ },
770
+ ];
791
771
  });
792
772
  const functions = core.functions.map((fn) => ({
793
773
  ...fn,