@tsplc/compiler 0.2.17 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -0,0 +1,30 @@
1
+ export { type CodesysOptions, codesys, direct } from "./config.ts";
2
+ export { emitCodesys, type SourceMapping } from "./emit.ts";
3
+ export {
4
+ buildCodesys,
5
+ codesysBuildConfig,
6
+ type CodesysEngineeringBuild,
7
+ engineeringBuildSchema,
8
+ } from "./engineering.ts";
9
+ export { type CodesysPlan, type CodesysProject, planCodesys } from "./plan.ts";
10
+ export type { ProjectHardware } from "./manifest.ts";
11
+ export { diagnoseCodesys } from "./vendor.ts";
12
+ export {
13
+ iecSpelling,
14
+ ioTargets,
15
+ isStoragePath,
16
+ resolveStoragePath,
17
+ type StorageBinding,
18
+ } from "./io-paths.ts";
19
+ export { planGlobalNames } from "./global-names.ts";
20
+ export { publicationSelectors, resolvePublication } from "./publication.ts";
21
+ export { jsonScalar, validateHttpLayout } from "./http.ts";
22
+ export { Sources } from "./sources.ts";
23
+ export { storageLayout } from "./storage.ts";
24
+ export {
25
+ accessedStorage,
26
+ routineTasks,
27
+ schedulePrograms,
28
+ taskStorageOwnership,
29
+ } from "./task-access.ts";
30
+ export { planJobFailures, telemetryCalls, telemetryPath } from "./telemetry.ts";
@@ -0,0 +1,430 @@
1
+ import { createHash } from "node:crypto";
2
+ import type {
3
+ CoreExpression,
4
+ CoreFunctionBlock,
5
+ CoreStatement,
6
+ GeneratedObject,
7
+ SourceSpan,
8
+ } from "@tsplc/compiler/ir";
9
+ import type { DebugManifest } from "@tsplc/debug/manifest";
10
+ import { elementaryType, integerRange } from "@tsplc/iec";
11
+ import { DebugAnalysis, type InstancePath, type Operand } from "./debug.ts";
12
+ import {
13
+ expressionText,
14
+ placeText,
15
+ type StorageScope,
16
+ storageName,
17
+ } from "./expressions.ts";
18
+ import { isStoragePath, resolveStoragePath } from "./io-paths.ts";
19
+ import { ioAddress } from "./manifest.ts";
20
+ import { Names } from "./names.ts";
21
+ import type { CodesysPlan } from "./plan.ts";
22
+ import {
23
+ type CodesysSymbols,
24
+ type EmissionContext,
25
+ required,
26
+ } from "./symbols.ts";
27
+ import { telemetryClient, telemetryObjects } from "./telemetry.ts";
28
+
29
+ /**
30
+ * The debugger's and telemetry's names in the program: `GVL_TsplcDebug` and its fields, each
31
+ * task's ring, and the instrumentation fields of each block.
32
+ */
33
+ export type Instrumentation = ReturnType<typeof planInstrumentation>;
34
+
35
+ export function planInstrumentation(
36
+ plan: CodesysPlan,
37
+ symbols: CodesysSymbols,
38
+ ) {
39
+ const { core, options } = plan;
40
+ const settings = plan.project.debug;
41
+ // A simulation build binds no fieldbus I/O, but its outputs are still the configured ones.
42
+ const hardware = plan.project.hardware;
43
+ const outputs = [
44
+ ...core.variables
45
+ .filter((variable) => variable.storage === "output")
46
+ .map((root) => ({ key: root.name, root, segments: [] })),
47
+ ...(hardware
48
+ ? Object.entries(hardware.config.io).flatMap(([key, binding]) => {
49
+ if (
50
+ !isStoragePath(key) ||
51
+ !ioAddress(hardware, binding)?.startsWith("%Q")
52
+ ) {
53
+ return [];
54
+ }
55
+ const resolved = resolveStoragePath(core, key);
56
+ return "error" in resolved ? [] : [resolved];
57
+ })
58
+ : plan.storageBindings.filter(({ key }) =>
59
+ required(options.io[key]).address.startsWith("%Q"),
60
+ )
61
+ ).map(({ key, root, segments }) => ({ key, root, segments })),
62
+ ];
63
+ const analysis = new DebugAnalysis(core, plan.deployment, settings, outputs);
64
+ /** `GVL_TsplcDebug`, and the names of its fields. */
65
+ const global = symbols.names.allocateObject("GVL", "TsplcDebug");
66
+ const names = new Names();
67
+ names.allocate("buildId");
68
+ const slots = {
69
+ decisions: names.allocate("decisions"),
70
+ writers: names.allocate("writers"),
71
+ };
72
+ /** Each task's ring and sender in `GVL_TsplcDebug`. */
73
+ const rings = new Map<string, string>();
74
+ const telemetry = plan.telemetry;
75
+ if (telemetry) {
76
+ const tasks = new Set([
77
+ ...[...telemetry.calls.values(), ...telemetry.failures.values()].map(
78
+ (site) => site.task,
79
+ ),
80
+ ...analysis.events.map((site) => site.task),
81
+ ]);
82
+ for (const task of plan.deployment.tasks) {
83
+ if (tasks.has(task.name)) {
84
+ rings.set(task.name, names.allocate(task.name));
85
+ }
86
+ }
87
+ }
88
+ const telemetryNames = rings.size
89
+ ? {
90
+ writer: symbols.names.allocateObject("FB", "TsplcTelemetry"),
91
+ record: symbols.names.allocateObject("ST", "TsplcRecord"),
92
+ client: symbols.names.allocateObject("FB", "TsplcTelemetryHttp"),
93
+ }
94
+ : undefined;
95
+ /** Job instances in manifest order, and the job id each single-instance declaration passes to its service calls. */
96
+ const jobs: { block: CoreFunctionBlock; path: InstancePath }[] = core.blocks
97
+ .filter((block) => block.job)
98
+ .flatMap((block) =>
99
+ analysis.instances.get(block.id)!.map((path) => ({ block, path })),
100
+ );
101
+ const jobIds = new Map<string, number>();
102
+ jobs.forEach(({ path }, index) => {
103
+ const declared = path.at(-1)!.variable;
104
+ if (analysis.owningPath(declared) === path) {
105
+ jobIds.set(declared.id, index + 1);
106
+ }
107
+ });
108
+ /** Raw bytes over each assembly, in `GVL_TsplcDebug`, by device. */
109
+ const devices = new Map<
110
+ string,
111
+ Partial<
112
+ Record<
113
+ "input" | "output",
114
+ { field: string; address: string; bytes: number }
115
+ >
116
+ >
117
+ >();
118
+ if (settings && hardware?.tree) {
119
+ for (const device of hardware.catalog.devices) {
120
+ devices.set(
121
+ device.id,
122
+ Object.fromEntries(
123
+ device.assemblies.map((assembly) => [
124
+ assembly.direction,
125
+ {
126
+ field: names.allocate(`${device.id}_${assembly.direction}s`),
127
+ address: assembly.address,
128
+ bytes: assembly.size,
129
+ },
130
+ ]),
131
+ ),
132
+ );
133
+ }
134
+ }
135
+ return {
136
+ analysis,
137
+ global,
138
+ slots,
139
+ rings,
140
+ telemetryNames,
141
+ jobs,
142
+ jobIds,
143
+ devices,
144
+ fields: new Map<string, BlockInstrumentation>(),
145
+ };
146
+ }
147
+
148
+ /** Instrumentation fields of a block: its job state and the requesting job's id. */
149
+ interface BlockInstrumentation {
150
+ busy?: string;
151
+ /** The method that records the job starting and finishing, allocated with `busy`. */
152
+ track?: string;
153
+ step?: string;
154
+ startedAt?: string;
155
+ job?: string;
156
+ sequence?: string;
157
+ }
158
+
159
+ /** Stands for the build id in the sender until the id, a hash over everything else, is known. */
160
+ const buildPlaceholder = "<build>";
161
+
162
+ export function emitTelemetry(
163
+ plan: CodesysPlan,
164
+ symbols: CodesysSymbols,
165
+ instrumentation: Instrumentation,
166
+ networkName: string | undefined,
167
+ ): GeneratedObject[] {
168
+ const { telemetry } = plan;
169
+ const names = instrumentation.telemetryNames;
170
+ if (!telemetry || !names) {
171
+ return [];
172
+ }
173
+ return telemetryObjects({
174
+ plan: telemetry,
175
+ names,
176
+ target: symbols.targetTypes,
177
+ endpoint: required(plan.http[telemetryClient]),
178
+ network: `${required(networkName)}.network`,
179
+ build: buildPlaceholder,
180
+ types: symbols.typeMap,
181
+ });
182
+ }
183
+
184
+ /**
185
+ * `GVL_TsplcDebug` holds the build id, which identifies this ST and its manifest, so the id is
186
+ * computed over everything else first.
187
+ */
188
+ export function emitDebugGlobal(
189
+ plan: CodesysPlan,
190
+ instrumentation: Instrumentation,
191
+ objects: GeneratedObject[],
192
+ manifest: DebugManifest,
193
+ ): DebugManifest {
194
+ const hash = createHash("sha256");
195
+ for (const object of objects) {
196
+ hash.update(
197
+ `${object.name}\n${object.declaration}\n${object.implementation ?? ""}\n`,
198
+ );
199
+ }
200
+ hash.update(JSON.stringify(manifest));
201
+ const id = hash.digest("hex").slice(0, 16);
202
+
203
+ // A batch names its build; the id is known only now, so the sender's literal is filled in last.
204
+ const send = objects.find(
205
+ (object) => object.id === "tsplc:telemetryWriter:Send",
206
+ );
207
+ if (send?.implementation !== undefined) {
208
+ send.implementation = send.implementation.replace(buildPlaceholder, id);
209
+ }
210
+
211
+ const fields = [`buildId : STRING(16) := '${id}'`];
212
+ for (const [task, field] of instrumentation.rings) {
213
+ fields.push(
214
+ `${field} : ${required(instrumentation.telemetryNames).writer} := (task := '${task}')`,
215
+ );
216
+ }
217
+ const settings = plan.project.debug;
218
+ if (settings) {
219
+ if (instrumentation.analysis.decisions.size) {
220
+ fields.push(
221
+ `${instrumentation.slots.decisions} : ARRAY[0..${instrumentation.analysis.decisions.size - 1}] OF DINT`,
222
+ );
223
+ }
224
+ if (settings.writers && instrumentation.analysis.outputs.length) {
225
+ fields.push(
226
+ `${instrumentation.slots.writers} : ARRAY[0..${instrumentation.analysis.outputs.length - 1}] OF UINT`,
227
+ );
228
+ }
229
+ for (const raw of [...instrumentation.devices.values()].flatMap((device) =>
230
+ Object.values(device),
231
+ )) {
232
+ fields.push(
233
+ `${raw.field} AT ${raw.address} : ARRAY[0..${raw.bytes - 1}] OF BYTE`,
234
+ );
235
+ }
236
+ }
237
+ objects.push({
238
+ id: "debug",
239
+ kind: "globalList",
240
+ name: instrumentation.global,
241
+ // Nothing in the program reads the build id; linkalways keeps it in the application.
242
+ declaration: `{attribute 'linkalways'}
243
+ {attribute 'qualified_only'}
244
+ VAR_GLOBAL
245
+ ${fields.map((field) => ` ${field};\n`).join("")}END_VAR
246
+ `,
247
+ });
248
+ return { ...manifest, build: { ...manifest.build, id } };
249
+ }
250
+
251
+ /** What a routine's probes read, and the task whose ring they record into unless told otherwise. */
252
+ export interface RoutineProbes {
253
+ context: EmissionContext;
254
+ storage: StorageScope;
255
+ task: string | undefined;
256
+ }
257
+
258
+ /** Appends a line of a routine's implementation, mapped to `source` when given. */
259
+ type WriteLine = (line: string, depth: number, source?: SourceSpan) => void;
260
+
261
+ export const ringTarget = (
262
+ { global, rings }: Instrumentation,
263
+ task: string | undefined,
264
+ ) => `${global}.${required(rings.get(required(task)))}`;
265
+
266
+ const [dintMinimum, dintMaximum] = integerRange(elementaryType("DINT"));
267
+
268
+ // Trace operands are DINTs: BOOL as 0/1, enums by value, integers clamped to the DINT range.
269
+ const traceOperand = (storage: StorageScope, value: CoreExpression): string => {
270
+ const type = required(storage.symbols.typeMap.get(value.type));
271
+ const text = expressionText(storage, value);
272
+ if (type.kind === "bool") {
273
+ return `BOOL_TO_DINT(${text})`;
274
+ }
275
+ if (type.kind !== "integer" && type.kind !== "bits") {
276
+ return `TO_DINT(${text})`;
277
+ }
278
+ const signed = type.kind === "integer" && type.signed;
279
+ const [minimum, maximum] = integerRange({ bits: type.bits, signed });
280
+ if (minimum >= dintMinimum && maximum <= dintMaximum) {
281
+ return `TO_DINT(${text})`;
282
+ }
283
+ if (signed) {
284
+ return `TO_DINT(LIMIT(LINT#${dintMinimum}, ${text}, LINT#${dintMaximum}))`;
285
+ }
286
+ const wide = type.bits === 32 ? "UDINT" : "ULINT";
287
+ return `TO_DINT(MIN(TO_${wide}(${text}), ${wide}#${dintMaximum}))`;
288
+ };
289
+
290
+ // CODESYS requires every input, so operands a site lacks are passed as 0.
291
+ const traceCall = (
292
+ { context, storage, task }: RoutineProbes,
293
+ site: number,
294
+ value: string,
295
+ operands: readonly Operand[] = [],
296
+ ): string => {
297
+ const captured = Array.from(
298
+ { length: required(context.plan.telemetry?.traceOperands) },
299
+ (_, index) => {
300
+ const operand = operands[index];
301
+ return `, operand${index} := ${operand ? traceOperand(storage, operand.capture) : "DINT#0"}`;
302
+ },
303
+ );
304
+ return `${ringTarget(context.instrumentation, task)}.Trace(site := UINT#${site}, value := ${value}, operands := USINT#${operands.length}${captured.join("")});`;
305
+ };
306
+
307
+ /** The writer and trace probes the debug analysis placed on a statement, written before it. */
308
+ export function writeProbes(
309
+ probes: RoutineProbes,
310
+ write: WriteLine,
311
+ item: CoreStatement,
312
+ depth: number,
313
+ ): void {
314
+ const { instrumentation } = probes.context;
315
+ const { storage } = probes;
316
+ for (const probe of instrumentation.analysis.probes.get(item) ?? []) {
317
+ if (probe.kind === "writer") {
318
+ const writer = `${instrumentation.global}.${instrumentation.slots.writers}[${probe.output}] := UINT#${probe.site};`;
319
+ if (!probe.when.length) {
320
+ write(writer, depth, item.span);
321
+ continue;
322
+ }
323
+ const reached = probe.when.map(
324
+ ({ index, value }) =>
325
+ `TO_DINT(${expressionText(storage, index)}) = DINT#${value}`,
326
+ );
327
+ write(`IF ${reached.join(" AND ")} THEN`, depth, item.span);
328
+ write(writer, depth + 1, item.span);
329
+ write("END_IF;", depth, item.span);
330
+ continue;
331
+ }
332
+ const value = `TO_DINT(${expressionText(storage, probe.value)})`;
333
+ if (item.kind === "assign") {
334
+ write(
335
+ `IF ${placeText(storage, item.root, item.path)} <> ${expressionText(storage, probe.value)} THEN`,
336
+ depth,
337
+ item.span,
338
+ );
339
+ } else {
340
+ const last = `${instrumentation.global}.${instrumentation.slots.decisions}[${required(probe.slot)}]`;
341
+ write(`IF ${value} <> ${last} THEN`, depth, item.span);
342
+ write(`${last} := ${value};`, depth + 1, item.span);
343
+ }
344
+ write(
345
+ traceCall(probes, probe.site, value, probe.operands),
346
+ depth + 1,
347
+ item.span,
348
+ );
349
+ write("END_IF;", depth, item.span);
350
+ }
351
+ }
352
+
353
+ export const jobField = (
354
+ storage: StorageScope,
355
+ job: CoreFunctionBlock,
356
+ name: string,
357
+ ) =>
358
+ storageName(
359
+ storage,
360
+ required(job.state.find((item) => item.name === name)).id,
361
+ );
362
+
363
+ /**
364
+ * The job's tracking method, which records it starting or finishing. The job calls it on
365
+ * entry and on every exit: its caller stops calling it once it is done, so only the call that
366
+ * finishes it sees the finish.
367
+ */
368
+ export function jobTracking(
369
+ probes: RoutineProbes,
370
+ job: CoreFunctionBlock,
371
+ fields: BlockInstrumentation,
372
+ ): string {
373
+ const { plan, instrumentation } = probes.context;
374
+ const busy = jobField(probes.storage, job, "busy");
375
+ const sites = instrumentation.analysis.jobSites.get(job.id);
376
+ const failure = plan.telemetry?.failures.get(job.id);
377
+ const lines: string[] = [];
378
+ const line = (text: string, depth: number) =>
379
+ lines.push(" ".repeat(depth) + text);
380
+ line(`IF ${busy} = ${required(fields.busy)} THEN`, 0);
381
+ line("RETURN;", 1);
382
+ line("END_IF;", 0);
383
+ if (fields.startedAt || sites) {
384
+ line(`IF ${busy} THEN`, 0);
385
+ if (fields.startedAt) {
386
+ line(`${fields.startedAt} := TIME_TO_UDINT(TIME());`, 1);
387
+ }
388
+ if (sites) {
389
+ line(
390
+ traceCall(
391
+ probes,
392
+ sites.start,
393
+ `TO_DINT(${jobField(probes.storage, job, "step")})`,
394
+ ),
395
+ 1,
396
+ );
397
+ }
398
+ line("END_IF;", 0);
399
+ }
400
+ if (sites || failure) {
401
+ const error = jobField(probes.storage, job, "error");
402
+ line(`IF NOT ${busy} THEN`, 0);
403
+ if (sites) {
404
+ line(`IF ${error} <> 0 THEN`, 1);
405
+ line(traceCall(probes, sites.completion, `-TO_DINT(${error})`), 2);
406
+ line("ELSE", 1);
407
+ line(
408
+ traceCall(
409
+ probes,
410
+ sites.completion,
411
+ `TO_DINT(${required(fields.step)})`,
412
+ ),
413
+ 2,
414
+ );
415
+ line("END_IF;", 1);
416
+ }
417
+ // Cancellation is asked for, so it isn't a failure.
418
+ if (failure) {
419
+ line(`IF ${error} <> 0 AND ${error} <> 1 THEN`, 1);
420
+ line(
421
+ `${ringTarget(instrumentation, failure.task)}.Failure${failure.id}(code := ${error}, step := ${required(fields.step)});`,
422
+ 2,
423
+ );
424
+ line("END_IF;", 1);
425
+ }
426
+ line("END_IF;", 0);
427
+ }
428
+ line(`${fields.busy} := ${busy};`, 0);
429
+ return `${lines.join("\n")}\n`;
430
+ }
@@ -0,0 +1,140 @@
1
+ import type { PlcType, Variable, VerifiedCoreModule } from "@tsplc/compiler/ir";
2
+ import { type IoTarget, ioLayout } from "@tsplc/typegen/hardware";
3
+ import { moduleName } from "./storage.ts";
4
+
5
+ type StorageSegment =
6
+ | { kind: "field"; record: string; name: string }
7
+ | { kind: "index"; value: number };
8
+
9
+ /** An `io` key that names a field of authored module storage, e.g. `PlantIO.Motor.Output.Run`. */
10
+ export interface StorageBinding {
11
+ key: string;
12
+ root: Variable;
13
+ segments: readonly StorageSegment[];
14
+ type: PlcType;
15
+ }
16
+
17
+ const pathPattern =
18
+ /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
19
+
20
+ export const isStoragePath = (key: string): boolean =>
21
+ key.includes(".") || key.includes("[");
22
+
23
+ /** Resolve a storage path against verified types; the error explains the first unresolvable segment. */
24
+ export function resolveStoragePath(
25
+ core: VerifiedCoreModule,
26
+ key: string,
27
+ ): StorageBinding | { error: string } {
28
+ const match = pathPattern.exec(key);
29
+ if (!match) {
30
+ return {
31
+ error: `${key}: expected Module.variable followed by .field or [index].`,
32
+ };
33
+ }
34
+ const [, module, name, rest] = match;
35
+ const roots = core.variables.filter(
36
+ (item) =>
37
+ item.storage === "module" &&
38
+ item.name === name &&
39
+ moduleName(item) === module,
40
+ );
41
+ const [root] = roots;
42
+ if (!root || roots.length !== 1) {
43
+ return {
44
+ error: root
45
+ ? `${key}: ${module}.${name} is declared by more than one module named ${module}.`
46
+ : `${key}: no mutable module variable ${module}.${name}.`,
47
+ };
48
+ }
49
+ const types = new Map(core.types.map((type) => [type.id, type]));
50
+ let type = types.get(root.type)!;
51
+ const segments: StorageSegment[] = [];
52
+ for (const [, field, index] of rest!.matchAll(
53
+ /\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g,
54
+ )) {
55
+ if (field !== undefined) {
56
+ const member =
57
+ type.kind === "record"
58
+ ? type.fields.find((f) => f.name === field)
59
+ : undefined;
60
+ if (!member) {
61
+ return { error: `${key}: no field ${field}.` };
62
+ }
63
+ segments.push({ kind: "field", record: type.id, name: field });
64
+ type = types.get(member.type)!;
65
+ } else {
66
+ const value = Number(index);
67
+ if (type.kind !== "array") {
68
+ return { error: `${key}: ${index} indexes a non-array value.` };
69
+ }
70
+ if (value < type.lowerBound || value >= type.lowerBound + type.length) {
71
+ return {
72
+ error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`,
73
+ };
74
+ }
75
+ segments.push({ kind: "index", value });
76
+ type = types.get(type.element)!;
77
+ }
78
+ }
79
+ return { key, root, segments, type };
80
+ }
81
+
82
+ /** IEC spelling of a bindable type, as typegen spells channels; undefined for records, enums, strings. */
83
+ export function iecSpelling(
84
+ type: PlcType,
85
+ types: ReadonlyMap<string, PlcType>,
86
+ ): string | undefined {
87
+ if (
88
+ type.kind === "bool" ||
89
+ type.kind === "integer" ||
90
+ type.kind === "bits" ||
91
+ type.kind === "float" ||
92
+ type.kind === "duration" ||
93
+ type.kind === "calendar"
94
+ ) {
95
+ return type.id;
96
+ }
97
+ if (type.kind !== "array") {
98
+ return undefined;
99
+ }
100
+ const element = iecSpelling(types.get(type.element)!, types);
101
+ const upper = type.lowerBound + type.length - 1;
102
+ return element && !element.startsWith("ARRAY")
103
+ ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}`
104
+ : undefined;
105
+ }
106
+
107
+ /** Every key an `io` mapping may use: logical IO names and paths into mutable module storage. */
108
+ export function ioTargets(core: VerifiedCoreModule): IoTarget[] {
109
+ const types = new Map(core.types.map((type) => [type.id, type]));
110
+ const targets: IoTarget[] = [];
111
+ const add = (key: string, type: PlcType) => {
112
+ const layout = ioLayout(iecSpelling(type, types) ?? "");
113
+ if (layout) {
114
+ targets.push({ key, layout });
115
+ }
116
+ };
117
+ const visit = (key: string, type: PlcType): void => {
118
+ add(key, type);
119
+ if (type.kind === "record") {
120
+ for (const field of type.fields) {
121
+ visit(`${key}.${field.name}`, types.get(field.type)!);
122
+ }
123
+ }
124
+ // Typegen writes keys as template literal types, so any index matches here.
125
+ if (type.kind === "array") {
126
+ visit(`${key}[` + "${number}" + "]", types.get(type.element)!);
127
+ }
128
+ };
129
+ for (const variable of core.variables) {
130
+ if (variable.storage === "input" || variable.storage === "output") {
131
+ add(variable.name, types.get(variable.type)!);
132
+ } else if (variable.storage === "module") {
133
+ visit(
134
+ `${moduleName(variable)}.${variable.name}`,
135
+ types.get(variable.type)!,
136
+ );
137
+ }
138
+ }
139
+ return targets;
140
+ }