@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6558 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16076 -0
  12. package/dist/index.js.map +61 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1078 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,790 @@
1
+ import { parse } from "node:path";
2
+ import {
3
+ admitCore,
4
+ type CoreExpression,
5
+ type CoreFunction,
6
+ type CoreFunctionBlock,
7
+ type CorePath,
8
+ type CoreStatement,
9
+ constantIndex,
10
+ mapBodies,
11
+ nestedBodies,
12
+ type VerifiedCoreModule,
13
+ } from "./core-model";
14
+ import type { Variable } from "./model";
15
+ import { mapExpression, mapPath, mapStatementExpressions } from "./operands";
16
+ import { type CoreTables, coreTables, lookup } from "./tables";
17
+ import { isValueType, type PlcType } from "./types";
18
+
19
+ /**
20
+ * Routines that are the same code over different storage, such as one method elaborated once per
21
+ * instance, merged into one routine that borrows that storage. `routines` maps every routine that
22
+ * was merged away to the one that runs in its place.
23
+ */
24
+ export interface SharedRoutines {
25
+ core: VerifiedCoreModule;
26
+ routines: ReadonlyMap<string, string>;
27
+ }
28
+
29
+ /**
30
+ * Merges free routines whose bodies differ only in the persistent storage they reach. Each place a
31
+ * routine reaches through a fixed path into module storage starts at an anchor: the place without
32
+ * its last field, or the whole place when it ends in a constant index or reaches the first index
33
+ * that is computed at run time. Routines with the same anchored body, declaration and partition
34
+ * share one routine that takes each anchor that differs between them as an `InOut` parameter;
35
+ * each call site borrows its routine's anchors. A borrowed place is the caller's storage, read and
36
+ * written where the original routine read and wrote it, so evaluation order and aliasing are
37
+ * unchanged. Callees merge before their callers, whose calls then differ only in what they borrow.
38
+ *
39
+ * `partition` keeps routines apart that must stay apart, such as those of different tasks; a
40
+ * routine it gives no partition is left as it is.
41
+ */
42
+ export function shareRoutines(
43
+ core: VerifiedCoreModule,
44
+ partition: (routine: CoreFunction) => string | undefined,
45
+ ): SharedRoutines {
46
+ const tables = coreTables(core);
47
+ const globals = new Map(core.variables.map((item) => [item.id, item]));
48
+ const entries = new Set(core.programs.map((program) => program.entry));
49
+ const bodies = new Map<string, readonly CoreStatement[]>(
50
+ [...core.functions, ...core.blocks].map((routine) => [
51
+ routine.id,
52
+ routine.body,
53
+ ]),
54
+ );
55
+ const merged = new Map<string, string>();
56
+ const shared = new Map<string, CoreFunction>();
57
+ const body = (id: string) => lookup(bodies, id, "routine");
58
+
59
+ const roots: Roots = {
60
+ anchorable: (root) => {
61
+ const variable = globals.get(root);
62
+ return variable !== undefined && variable.storage !== "constant";
63
+ },
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),
67
+ };
68
+
69
+ const candidates = core.functions.filter(
70
+ (fn) => !fn.owner && !entries.has(fn.id),
71
+ );
72
+ for (const level of callLevels(candidates, body)) {
73
+ const groups = new Map<string, Anchored[]>();
74
+ for (const fn of level) {
75
+ const group = partition(fn);
76
+ if (group === undefined) {
77
+ continue;
78
+ }
79
+ const anchored = anchor({ ...fn, body: body(fn.id) }, tables, roots);
80
+ if (!anchored) {
81
+ continue;
82
+ }
83
+ const key = `${group}\n${anchored.key}`;
84
+ groups.set(key, [...(groups.get(key) ?? []), anchored]);
85
+ }
86
+ const calls = new Map<string, MergedCall>();
87
+ for (const members of groups.values()) {
88
+ const [first] = members;
89
+ if (!first || members.length < 2) {
90
+ continue;
91
+ }
92
+ const varying: Varying = {
93
+ anchors: first.anchors.map((slot, index) =>
94
+ members.some((member) => member.anchors[index]?.key !== slot.key),
95
+ ),
96
+ constants: constantParameters(members),
97
+ };
98
+ shared.set(
99
+ first.fn.id,
100
+ mergedRoutine(members, varying, roots, core.folded ?? []),
101
+ );
102
+ for (const [index, member] of members.entries()) {
103
+ if (index) {
104
+ merged.set(member.fn.id, first.fn.id);
105
+ }
106
+ calls.set(member.fn.id, {
107
+ target: first.fn.id,
108
+ borrows: member.anchors.filter((_, slot) => varying.anchors[slot]),
109
+ values: member.constants.filter(
110
+ (_, slot) => varying.constants[slot] === slot,
111
+ ),
112
+ });
113
+ }
114
+ }
115
+ if (!calls.size) {
116
+ continue;
117
+ }
118
+ for (const [id, items] of bodies) {
119
+ bodies.set(id, rewriteCalls(items, calls));
120
+ }
121
+ }
122
+ if (!merged.size) {
123
+ return { core, routines: merged };
124
+ }
125
+
126
+ const functions = core.functions.flatMap((fn): CoreFunction[] => {
127
+ if (merged.has(fn.id)) {
128
+ return [];
129
+ }
130
+ return [shared.get(fn.id) ?? { ...fn, body: body(fn.id) }];
131
+ });
132
+ const blocks = core.blocks.map(
133
+ (block): CoreFunctionBlock => ({ ...block, body: body(block.id) }),
134
+ );
135
+ return {
136
+ core: admitCore({ ...core, functions, blocks }),
137
+ routines: merged,
138
+ };
139
+ }
140
+
141
+ interface Roots {
142
+ /** Whether a root is module storage, whose places a routine can borrow. */
143
+ anchorable: (root: string) => boolean;
144
+ variable: (root: string) => Variable;
145
+ /** Whether a type holds only data, which a reference can bind to. */
146
+ plainData: (type: string) => boolean;
147
+ }
148
+
149
+ /** A place a routine reaches in module storage, from the routine's own anchor. */
150
+ interface Borrow {
151
+ root: string;
152
+ path: CorePath;
153
+ type: string;
154
+ }
155
+
156
+ type ConstantExpression = Extract<CoreExpression, { kind: "constant" }>;
157
+
158
+ /** A routine's body with its anchors numbered in the order it first reaches them. */
159
+ interface Anchored {
160
+ fn: CoreFunction;
161
+ key: string;
162
+ anchors: readonly (Borrow & { key: string })[];
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>;
167
+ }
168
+
169
+ /** Candidate routines, callees before their callers. A routine's level is one more than its deepest callee's. */
170
+ function callLevels(
171
+ candidates: readonly CoreFunction[],
172
+ body: (id: string) => readonly CoreStatement[],
173
+ ): CoreFunction[][] {
174
+ const levels = new Map<string, number>();
175
+ const callees = (items: readonly CoreStatement[], found: Set<string>) => {
176
+ for (const item of items) {
177
+ if (item.kind === "invoke") {
178
+ found.add(item.function);
179
+ }
180
+ for (const nested of nestedBodies(item)) {
181
+ callees(nested, found);
182
+ }
183
+ }
184
+ return found;
185
+ };
186
+ const level = (id: string): number => {
187
+ const known = levels.get(id);
188
+ if (known !== undefined) {
189
+ return known;
190
+ }
191
+ const deepest = [...callees(body(id), new Set())].reduce(
192
+ (depth, callee) => Math.max(depth, level(callee) + 1),
193
+ 0,
194
+ );
195
+ levels.set(id, deepest);
196
+ return deepest;
197
+ };
198
+ const ordered: CoreFunction[][] = [];
199
+ for (const fn of candidates) {
200
+ const depth = level(fn.id);
201
+ ordered[depth] = [...(ordered[depth] ?? []), fn];
202
+ }
203
+ return ordered.filter((items) => items !== undefined);
204
+ }
205
+
206
+ /** The fixed part of a place that an anchor holds, by the rule `shareRoutines` describes. */
207
+ function anchorLength(path: CorePath): number {
208
+ const dynamic = path.findIndex(
209
+ (segment) =>
210
+ segment.kind === "index" && constantIndex(segment.value) === undefined,
211
+ );
212
+ if (dynamic >= 0) {
213
+ return dynamic;
214
+ }
215
+ return path.at(-1)?.kind === "field" ? path.length - 1 : path.length;
216
+ }
217
+
218
+ const constantText = (segment: CorePath[number]) =>
219
+ segment.kind === "field"
220
+ ? `.${segment.name}`
221
+ : `[${segment.value.kind === "constant" ? JSON.stringify(segment.value.value) : "?"}]`;
222
+
223
+ /**
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.
229
+ */
230
+ function anchor(
231
+ fn: CoreFunction,
232
+ tables: CoreTables,
233
+ roots: Roots,
234
+ ): Anchored | undefined {
235
+ const own = new Map(
236
+ [...fn.parameters, ...fn.locals].map((variable, index) => [
237
+ variable.id,
238
+ `#${index}`,
239
+ ]),
240
+ );
241
+ const anchors: (Borrow & { key: string })[] = [];
242
+ const slots = new Map<ConstantExpression, number>();
243
+ const numbers = new Map<string, number>();
244
+ const rewrite: PlaceRewrite = {
245
+ constant: (value) => {
246
+ if (!scalarConstant(value, tables.types)) {
247
+ return value;
248
+ }
249
+ const slot = slots.get(value) ?? slots.size;
250
+ slots.set(value, slot);
251
+ return {
252
+ kind: "load",
253
+ type: value.type,
254
+ span: value.span,
255
+ root: `$${slot}`,
256
+ };
257
+ },
258
+ place: (root, path, index) => {
259
+ if (!roots.anchorable(root)) {
260
+ return { root: own.get(root) ?? root, path: mapPath(path, index) };
261
+ }
262
+ const { fixed, key } = anchorOf(root, path);
263
+ const rest = mapPath(path.slice(fixed.length), index);
264
+ const known = numbers.get(key);
265
+ if (known !== undefined) {
266
+ return { root: `@${known}`, path: rest };
267
+ }
268
+ const type = tables.placeType(roots.variable(root).type, fixed)?.id;
269
+ if (type === undefined) {
270
+ throw new Unanchored();
271
+ }
272
+ // A block instance is not borrowed: its place stays as written, the same in every routine or none.
273
+ if (!roots.plainData(type)) {
274
+ return { root, path: [...fixed, ...rest] };
275
+ }
276
+ numbers.set(key, anchors.length);
277
+ anchors.push({ root, path: fixed, type, key });
278
+ return { root: `@${anchors.length - 1}`, path: rest };
279
+ },
280
+ identity: (root) => {
281
+ if (roots.anchorable(root)) {
282
+ throw new Unanchored();
283
+ }
284
+ return own.get(root) ?? root;
285
+ },
286
+ };
287
+ try {
288
+ const body = rewriteStatements(fn.body, rewrite);
289
+ // Not the name: the elaborator numbers each instance's copy of a routine. The declaration
290
+ // and the body say what it does.
291
+ const signature = {
292
+ span: fn.span,
293
+ result: fn.result,
294
+ parameters: fn.parameters.map(({ id, ...rest }) => rest),
295
+ locals: fn.locals.map(({ id, ...rest }) => rest),
296
+ anchors: anchors.map((item) => item.type),
297
+ };
298
+ return {
299
+ fn,
300
+ key: JSON.stringify([signature, body]),
301
+ anchors,
302
+ constants: [...slots.keys()],
303
+ slots,
304
+ };
305
+ } catch (cause) {
306
+ if (cause instanceof Unanchored) {
307
+ return undefined;
308
+ }
309
+ throw cause;
310
+ }
311
+ }
312
+
313
+ /** A place's anchor, and the key that identifies it. */
314
+ const anchorOf = (root: string, path: CorePath) => {
315
+ const fixed = path.slice(0, anchorLength(path));
316
+ return { fixed, key: `${root}${fixed.map(constantText).join("")}` };
317
+ };
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
+
345
+ /**
346
+ * The first routine of a group, taking each anchor that differs between the routines as an
347
+ * `InOut` parameter after its own parameters, then each constant that differs as a value
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.
350
+ */
351
+ function mergedRoutine(
352
+ members: readonly Anchored[],
353
+ varying: Varying,
354
+ roots: Roots,
355
+ folded: Folded,
356
+ ): CoreFunction {
357
+ const [{ fn, anchors, constants, slots }] = required(members);
358
+ const anchorNames = borrowNames(members, varying, roots);
359
+ const borrowed = new Map<number, Variable>();
360
+ for (const [index, slot] of anchors.entries()) {
361
+ const name = anchorNames.get(index);
362
+ if (name === undefined) {
363
+ continue;
364
+ }
365
+ borrowed.set(index, {
366
+ id: `${fn.id}:anchor${index}`,
367
+ name,
368
+ type: slot.type,
369
+ storage: "parameter",
370
+ mutable: true,
371
+ retention: "none",
372
+ mode: "inOut",
373
+ span: fn.span,
374
+ });
375
+ }
376
+ const values = new Map<number, Variable>();
377
+ for (const [index, constant] of constants.entries()) {
378
+ if (varying.constants[index] === index) {
379
+ values.set(index, {
380
+ id: `${fn.id}:value${index}`,
381
+ name: foldedName(members, index, folded) ?? "value",
382
+ type: constant.type,
383
+ storage: "parameter",
384
+ mutable: false,
385
+ retention: "none",
386
+ span: fn.span,
387
+ });
388
+ }
389
+ }
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));
395
+ const rewrite: PlaceRewrite = {
396
+ constant: (value) => {
397
+ const slot = slots.get(value);
398
+ const replacement = parameter(
399
+ values,
400
+ slot === undefined ? undefined : varying.constants[slot],
401
+ );
402
+ return replacement
403
+ ? {
404
+ kind: "load",
405
+ type: value.type,
406
+ span: value.span,
407
+ root: replacement.id,
408
+ }
409
+ : value;
410
+ },
411
+ place: (root, path, index) => {
412
+ if (!roots.anchorable(root)) {
413
+ return { root, path: mapPath(path, index) };
414
+ }
415
+ const { fixed, key } = anchorOf(root, path);
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 }
420
+ : { root, path: [...fixed, ...rest] };
421
+ },
422
+ identity: (root) => root,
423
+ };
424
+ return {
425
+ ...fn,
426
+ parameters: [...fn.parameters, ...borrowed.values(), ...values.values()],
427
+ body: rewriteStatements(fn.body, rewrite),
428
+ };
429
+ }
430
+
431
+ /** Which anchors differ between the routines of a group, and each constant's parameter, by number. */
432
+ interface Varying {
433
+ anchors: 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
+ );
535
+ }
536
+
537
+ /** What a call to a merged routine adds after its own arguments. */
538
+ interface MergedCall {
539
+ target: string;
540
+ borrows: readonly Borrow[];
541
+ values: readonly CoreExpression[];
542
+ }
543
+
544
+ /** Calls to merged routines go to the routine that runs in their place, borrowing their anchors. */
545
+ function rewriteCalls(
546
+ items: readonly CoreStatement[],
547
+ calls: ReadonlyMap<string, MergedCall>,
548
+ ): CoreStatement[] {
549
+ return items.map((item): CoreStatement => {
550
+ if (item.kind !== "invoke") {
551
+ return mapBodies(item, (body) => rewriteCalls(body, calls));
552
+ }
553
+ const call = calls.get(item.function);
554
+ if (!call) {
555
+ return item;
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
+ };
575
+ });
576
+ }
577
+
578
+ class Unanchored extends Error {}
579
+
580
+ interface PlaceRewrite {
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 };
587
+ /** A root a statement names without a path: a loop counter, call destination or block instance. */
588
+ identity: (root: string) => string;
589
+ /** A constant the body evaluates; case labels and loop bounds are not expressions. */
590
+ constant: (value: ConstantExpression) => CoreExpression;
591
+ }
592
+
593
+ /** Constants a routine can take as a value parameter instead: scalars of an elementary or enum type. */
594
+ const scalarConstant = (
595
+ value: ConstantExpression,
596
+ types: ReadonlyMap<string, PlcType>,
597
+ ) =>
598
+ ["bool", "integer", "float", "duration", "calendar"].includes(
599
+ value.value.kind,
600
+ ) && types.get(value.type)?.kind !== "string";
601
+
602
+ function rewriteExpression(
603
+ value: CoreExpression,
604
+ rewrite: PlaceRewrite,
605
+ ): CoreExpression {
606
+ const index = (operand: CoreExpression) =>
607
+ rewriteExpression(operand, rewrite);
608
+ if (value.kind === "constant") {
609
+ return rewrite.constant(value);
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);
626
+ }
627
+
628
+ function rewriteStatements(
629
+ items: readonly CoreStatement[],
630
+ rewrite: PlaceRewrite,
631
+ ): CoreStatement[] {
632
+ return items.map((item) => rewriteStatement(item, rewrite));
633
+ }
634
+
635
+ function rewriteStatement(
636
+ item: CoreStatement,
637
+ rewrite: PlaceRewrite,
638
+ ): CoreStatement {
639
+ const expression = (value: CoreExpression) =>
640
+ rewriteExpression(value, rewrite);
641
+ const statements = (body: readonly CoreStatement[]) =>
642
+ rewriteStatements(body, rewrite);
643
+ switch (item.kind) {
644
+ case "assign": {
645
+ const place = rewrite.place(item.root, item.path ?? [], expression);
646
+ return {
647
+ ...item,
648
+ root: place.root,
649
+ ...(item.path || place.path.length ? { path: place.path } : {}),
650
+ value: expression(item.value),
651
+ };
652
+ }
653
+ case "for":
654
+ return mapBodies(
655
+ mapStatementExpressions(
656
+ { ...item, counter: rewrite.identity(item.counter) },
657
+ expression,
658
+ ),
659
+ statements,
660
+ );
661
+ case "invoke":
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
+ );
674
+ case "blockUpdate":
675
+ return mapStatementExpressions(
676
+ { ...item, instance: rewrite.identity(item.instance) },
677
+ expression,
678
+ );
679
+ case "if":
680
+ case "switch":
681
+ case "return":
682
+ case "telemetry":
683
+ case "break":
684
+ case "continue":
685
+ return mapBodies(mapStatementExpressions(item, expression), statements);
686
+ }
687
+ }
688
+
689
+ /** A routine that only returns a constant, or does nothing: what each of its calls amounts to. */
690
+ function constantResult(
691
+ fn: CoreFunction,
692
+ ): { value?: CoreExpression } | undefined {
693
+ const [only, ...rest] = fn.body;
694
+ if (rest.length || fn.owner) {
695
+ return undefined;
696
+ }
697
+ if (!only) {
698
+ return fn.result ? undefined : {};
699
+ }
700
+ if (only.kind !== "return") {
701
+ return undefined;
702
+ }
703
+ if (!only.value) {
704
+ return fn.result ? undefined : {};
705
+ }
706
+ return only.value.kind === "constant" ? { value: only.value } : undefined;
707
+ }
708
+
709
+ /** The path a load or borrow reads through. */
710
+ const placePath = (value: CoreExpression): CorePath | undefined => {
711
+ if (value.kind === "load") {
712
+ return value.path ?? [];
713
+ }
714
+ return value.kind === "borrow" ? value.place.path : undefined;
715
+ };
716
+
717
+ /** Arguments that reading cannot fault: loads, borrows and constants, without arithmetic in their indexes. */
718
+ const plainArgument = (value: CoreExpression): boolean => {
719
+ if (value.kind === "constant") {
720
+ return true;
721
+ }
722
+ return (
723
+ placePath(value)?.every(
724
+ (segment) => segment.kind === "field" || plainArgument(segment.value),
725
+ ) ?? false
726
+ );
727
+ };
728
+
729
+ /**
730
+ * Replaces each call of a routine that only returns a constant with an assignment of that
731
+ * constant, and drops each call of one that does nothing. A call whose arguments compute
732
+ * something stays, so evaluating them can still fault as it would have. Routines no call
733
+ * reaches any more, other than program entries, are dropped.
734
+ */
735
+ export function foldConstantRoutines(core: VerifiedCoreModule): {
736
+ core: VerifiedCoreModule;
737
+ routines: ReadonlySet<string>;
738
+ } {
739
+ const entries = new Set(core.programs.map((program) => program.entry));
740
+ const constants = new Map(
741
+ core.functions.flatMap((fn) => {
742
+ const result = entries.has(fn.id) ? undefined : constantResult(fn);
743
+ return result ? [[fn.id, result] as const] : [];
744
+ }),
745
+ );
746
+ if (!constants.size) {
747
+ return { core, routines: new Set() };
748
+ }
749
+ const called = new Set<string>();
750
+ const fold = (items: readonly CoreStatement[]): CoreStatement[] =>
751
+ items.flatMap((item): CoreStatement[] => {
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];
759
+ }
760
+ if (item.destination === undefined || !result.value) {
761
+ return [];
762
+ }
763
+ return [
764
+ {
765
+ kind: "assign",
766
+ span: item.span,
767
+ root: item.destination,
768
+ value: { ...result.value, span: item.span },
769
+ },
770
+ ];
771
+ });
772
+ const functions = core.functions.map((fn) => ({
773
+ ...fn,
774
+ body: fold(fn.body),
775
+ }));
776
+ const blocks = core.blocks.map(
777
+ (block): CoreFunctionBlock => ({ ...block, body: fold(block.body) }),
778
+ );
779
+ const routines = new Set(
780
+ [...constants.keys()].filter((id) => !called.has(id)),
781
+ );
782
+ return {
783
+ core: admitCore({
784
+ ...core,
785
+ functions: functions.filter((fn) => !routines.has(fn.id)),
786
+ blocks,
787
+ }),
788
+ routines,
789
+ };
790
+ }