@tsplc/tmp-compiler 0.0.0-stage → 0.6.3

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 (185) 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 +6563 -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 +16198 -0
  12. package/dist/index.js.map +62 -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 +1090 -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-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,688 @@
1
+ import {
2
+ type Constant,
3
+ type CoreExpression,
4
+ type CoreStatement,
5
+ type CoreTables,
6
+ coreTables,
7
+ type Deployment,
8
+ type Diagnostic,
9
+ foldConstantRoutines,
10
+ forwardTemporaries,
11
+ freeze,
12
+ instancedBlock,
13
+ isLogicalIo,
14
+ isVerifiedCore,
15
+ nestedBodies,
16
+ type PlcType,
17
+ type SourceSpan,
18
+ shareRoutines,
19
+ statementExpressions,
20
+ subexpressions,
21
+ type VerifiedCoreModule,
22
+ } from "@tsplc/compiler/ir";
23
+ import type {
24
+ Environment,
25
+ Publication,
26
+ ResolvedDebugConfig,
27
+ ResolvedHmiConfig,
28
+ ResolvedTelemetryConfig,
29
+ ServerConfig,
30
+ } from "@tsplc/config";
31
+ import {
32
+ cyclicTasksSchema,
33
+ scheduleRepeats,
34
+ taskPriority,
35
+ } from "@tsplc/config/build";
36
+ import { ioScalarBits } from "@tsplc/iec";
37
+ import { addressBits, ioLayout, regionOf } from "@tsplc/typegen/hardware";
38
+ import { type CodesysOptions, optionsSchema } from "./config";
39
+ import { type HttpEndpoint, resolveHttpEndpoint } from "./endpoints";
40
+ import { httpLayout, serviceBlock } from "./http";
41
+ import { writerPaths } from "./instrumentation";
42
+ import {
43
+ iecSpelling,
44
+ isStoragePath,
45
+ resolveStoragePath,
46
+ type StorageBinding,
47
+ } from "./io-paths";
48
+ import type { ProjectHardware } from "./manifest";
49
+ import { isIecIdentifier } from "./names";
50
+ import { resolvePublication } from "./publication";
51
+ import { required } from "./required";
52
+ import { schedulePrograms } from "./scheduling";
53
+ import { storageLayout } from "./storage";
54
+ import {
55
+ accessedStorage,
56
+ routineTasks,
57
+ taskStorageOwnership,
58
+ } from "./task-access";
59
+ import { planTelemetry, type TelemetryPlan } from "./telemetry";
60
+
61
+ // Only this planner can admit a target configuration for emission: other modules cannot write the
62
+ // brand, and a copy of a plan is not in `plans`.
63
+ const planned: unique symbol = Symbol("CODESYS plan");
64
+ export interface CodesysPlan {
65
+ readonly [planned]: true;
66
+ readonly core: VerifiedCoreModule;
67
+ /**
68
+ * The module as the frontend specialized it, one routine per instance, before programs are joined
69
+ * and routines folded, shared and forwarded, with each task's programs in that module. The debug
70
+ * manifest and explanations describe every instance, whatever the emitted routines look like.
71
+ */
72
+ readonly specialized: VerifiedCoreModule;
73
+ readonly specializedTasks: Deployment;
74
+ /** The routine each specialized function that `shareRoutines` merged away runs as. */
75
+ readonly sharedRoutines: ReadonlyMap<string, string>;
76
+ readonly deployment: Deployment;
77
+ readonly options: CodesysOptions;
78
+ /** The IEC name `programNames` gives a program, by program name. */
79
+ readonly programNames: ReadonlyMap<string, string>;
80
+ /** `io` keys that name authored storage, resolved against the verified types. */
81
+ readonly storageBindings: readonly StorageBinding[];
82
+ /** The storage paths `debug.writers.paths` matches, each recorded in a last-writer slot. */
83
+ readonly writerPaths: readonly StorageBinding[];
84
+ readonly publication: Publication;
85
+ /** The endpoint each service block calls, by block id. */
86
+ readonly http: Readonly<Record<string, HttpEndpoint>>;
87
+ readonly project: CodesysProject;
88
+ /** Each task's records and their sender, when the program has telemetry. */
89
+ readonly telemetry?: TelemetryPlan;
90
+ }
91
+
92
+ const plans = new WeakSet<CodesysPlan>();
93
+
94
+ /** Whether `plan` is one `planCodesys` returned rather than a copy or a lookalike. */
95
+ export const isPlanned = (plan: CodesysPlan): boolean => plans.has(plan);
96
+
97
+ /**
98
+ * What the debug manifest describes beyond the program, the instrumentation `debug` asks for,
99
+ * and the telemetry settings and server its records go to.
100
+ */
101
+ export interface CodesysProject {
102
+ /** Manifest sources and telemetry `source`s are relative to this directory. */
103
+ root: string;
104
+ debug?: ResolvedDebugConfig;
105
+ telemetry?: ResolvedTelemetryConfig;
106
+ server?: Pick<ServerConfig, "transport" | "baseUrlEnv">;
107
+ hardware?: ProjectHardware;
108
+ /** The HMI's controls, whose targets the debugger names as clients that write. */
109
+ hmi?: Pick<ResolvedHmiConfig, "controls">;
110
+ /** Where HTTP credentials and the telemetry base URL are read from; this process's environment by default. */
111
+ environment?: Environment;
112
+ }
113
+ /** Where a check of the plan sends what it refuses, each becoming a diagnostic. */
114
+ export type Report = (message: string, span?: SourceSpan) => void;
115
+ function diagnostic(message: string, span?: SourceSpan): Diagnostic {
116
+ return {
117
+ origin: "backend",
118
+ code: "PLC7001",
119
+ severity: "error",
120
+ message,
121
+ ...(span && { span }),
122
+ };
123
+ }
124
+
125
+ export function planCodesys(
126
+ specialized: VerifiedCoreModule,
127
+ deployment: Deployment,
128
+ value: unknown,
129
+ project: CodesysProject = { root: process.cwd() },
130
+ ): { plan?: CodesysPlan; diagnostics: readonly Diagnostic[] } {
131
+ if (!isVerifiedCore(specialized)) {
132
+ return {
133
+ diagnostics: [
134
+ diagnostic("CODESYS requires a verified, normalized core module."),
135
+ ],
136
+ };
137
+ }
138
+
139
+ const parsed = optionsSchema.safeParse(value);
140
+ if (!parsed.success) {
141
+ return {
142
+ diagnostics: parsed.error.issues.map((issue) =>
143
+ diagnostic(`${issue.path.join(".")}: ${issue.message}`),
144
+ ),
145
+ };
146
+ }
147
+
148
+ const options = parsed.data;
149
+ const environment = project.environment ?? { ...process.env };
150
+ const diagnostics: Diagnostic[] = [];
151
+ const report = (message: string, span?: SourceSpan): void => {
152
+ diagnostics.push(diagnostic(message, span));
153
+ };
154
+ const { core, routines, tasks, specializedTasks } = scheduledRoutines(
155
+ specialized,
156
+ deployment,
157
+ project.debug,
158
+ report,
159
+ );
160
+ const scheduled: Deployment = { tasks };
161
+ const { types } = coreTables(core);
162
+ const http = new Map<string, HttpEndpoint>();
163
+ for (const block of core.blocks.filter(serviceBlock)) {
164
+ const layout = httpLayout(block, types);
165
+ if ("error" in layout) {
166
+ report(layout.error, block.span);
167
+ continue;
168
+ }
169
+ const endpoint: HttpEndpoint | { error: string } =
170
+ block.runtime.kind === "rpc"
171
+ ? {
172
+ transport: "opcua",
173
+ path: block.runtime.path,
174
+ timeoutMs: options.http.timeoutMs,
175
+ }
176
+ : resolveHttpEndpoint(block.runtime.url, options.http, environment);
177
+ if ("error" in endpoint) {
178
+ report(endpoint.error, block.span);
179
+ continue;
180
+ }
181
+ http.set(block.id, endpoint);
182
+ }
183
+
184
+ const storageBindings = validateIo(core, options, report);
185
+ const writerBindings = writerPaths(core, project.debug, report);
186
+ validateTasks(core, scheduled, report);
187
+ validateProgramNames(core, options.programNames, report);
188
+ validateRetain(core, report);
189
+ validateConstants(core, report);
190
+ const telemetry = planTelemetry(
191
+ core,
192
+ scheduled,
193
+ options,
194
+ { ...project, environment, trace: project.debug?.trace },
195
+ report,
196
+ );
197
+ const { publication, errors } = resolvePublication(core, options.publish);
198
+ for (const error of errors) {
199
+ report(error);
200
+ }
201
+
202
+ if (diagnostics.length) {
203
+ return { diagnostics };
204
+ }
205
+
206
+ const plan: CodesysPlan = Object.freeze({
207
+ core,
208
+ specialized,
209
+ specializedTasks: { tasks: specializedTasks },
210
+ sharedRoutines: routines,
211
+ deployment: structuredClone(scheduled),
212
+ options,
213
+ programNames: new Map(Object.entries(options.programNames)),
214
+ storageBindings,
215
+ writerPaths: writerBindings,
216
+ publication,
217
+ http: Object.fromEntries(http),
218
+ project,
219
+ ...(telemetry && { telemetry }),
220
+ [planned]: true as const,
221
+ });
222
+ freeze(plan.deployment);
223
+ freeze(plan.specializedTasks);
224
+ freeze(plan.options);
225
+ freeze(plan.storageBindings);
226
+ freeze(plan.writerPaths);
227
+ freeze(plan.publication);
228
+ plans.add(plan);
229
+ return { plan, diagnostics: [] };
230
+ }
231
+
232
+ /**
233
+ * Routines specialized per instance, merged where they run the same code in the same task, calls
234
+ * of routines that only return a constant replaced by it, and temporaries read right after they
235
+ * are written folded into their reader, with each task's programs in the module that results.
236
+ * Continuation programs stay apart: each task's wrapper calls them, and joining them named the
237
+ * joined program after whichever came first.
238
+ * The debugger's instrumentation is written per statement of each routine, so a program built
239
+ * with `debug` keeps every instance's own routine, as does one whose scheduling is invalid or
240
+ * names a program the module lacks: its diagnostics name the routines as written.
241
+ */
242
+ function scheduledRoutines(
243
+ specialized: VerifiedCoreModule,
244
+ deployment: Deployment,
245
+ debug: ResolvedDebugConfig | undefined,
246
+ report: Report,
247
+ ) {
248
+ const issues: string[] = [];
249
+ const specializedTasks = schedulePrograms(
250
+ specialized,
251
+ deployment.tasks,
252
+ (message) => {
253
+ issues.push(message);
254
+ },
255
+ );
256
+ const programs = new Set(specialized.programs.map((program) => program.name));
257
+ const unknown = deployment.tasks.some((task) =>
258
+ task.programs.some((name) => !programs.has(name)),
259
+ );
260
+ if (debug || issues.length || unknown) {
261
+ for (const message of issues) {
262
+ report(message);
263
+ }
264
+ return {
265
+ core: specialized,
266
+ routines: new Map<string, string>(),
267
+ tasks: specializedTasks,
268
+ specializedTasks,
269
+ };
270
+ }
271
+ const folded = foldConstantRoutines(specialized);
272
+ const foldedTasks = routineTasks(folded.core, {
273
+ tasks: schedulePrograms(folded.core, deployment.tasks, () => {}),
274
+ });
275
+ const shared = shareRoutines(folded.core, (routine) =>
276
+ foldedTasks.get(routine.id),
277
+ );
278
+ const core = forwardTemporaries(shared.core);
279
+ return {
280
+ core,
281
+ routines: shared.routines,
282
+ tasks: schedulePrograms(core, deployment.tasks, report),
283
+ specializedTasks,
284
+ };
285
+ }
286
+
287
+ /** Validate every `io` binding and return the ones that name authored storage. */
288
+ function validateIo(
289
+ core: VerifiedCoreModule,
290
+ options: CodesysOptions,
291
+ report: Report,
292
+ ): StorageBinding[] {
293
+ const tables = coreTables(core);
294
+ const targets: {
295
+ name: string;
296
+ binding: CodesysOptions["io"][string];
297
+ type: PlcType;
298
+ region: "I" | "Q";
299
+ span?: SourceSpan;
300
+ }[] = [];
301
+ const names = new Set<string>();
302
+ for (const item of core.variables.filter(isLogicalIo)) {
303
+ if (names.has(item.name)) {
304
+ report(
305
+ `Ambiguous I/O name ${item.name}; logical I/O names must be unique.`,
306
+ item.span,
307
+ );
308
+ }
309
+ names.add(item.name);
310
+ const binding = Object.hasOwn(options.io, item.name)
311
+ ? options.io[item.name]
312
+ : undefined;
313
+ if (!binding) {
314
+ report(`Missing I/O binding for ${item.name}.`, item.span);
315
+ continue;
316
+ }
317
+ targets.push({
318
+ name: item.name,
319
+ binding,
320
+ type: tables.typeOf(item.type),
321
+ region: regionOf(item.storage),
322
+ span: item.span,
323
+ });
324
+ }
325
+
326
+ const scheduled = new Set<string>();
327
+ for (const program of core.programs) {
328
+ for (const id of accessedStorage(tables.functionOf(program.entry), core)) {
329
+ scheduled.add(id);
330
+ }
331
+ }
332
+ const storageBindings: StorageBinding[] = [];
333
+ for (const [name, binding] of Object.entries(options.io)) {
334
+ if (names.has(name)) {
335
+ continue;
336
+ }
337
+ if (!isStoragePath(name)) {
338
+ report(`Unknown I/O binding ${name}.`);
339
+ continue;
340
+ }
341
+ const resolved = resolveStoragePath(core, name);
342
+ if ("error" in resolved) {
343
+ report(resolved.error);
344
+ continue;
345
+ }
346
+ const overlapping = storageBindings.find((other) =>
347
+ nested(other, resolved),
348
+ );
349
+ if (overlapping) {
350
+ report(`${name} overlaps the binding ${overlapping.key}.`);
351
+ }
352
+ if (!scheduled.has(resolved.root.id)) {
353
+ report(
354
+ `${name}: no scheduled program uses ${resolved.root.name}, so it would never be copied.`,
355
+ );
356
+ }
357
+ storageBindings.push(resolved);
358
+ targets.push({
359
+ name,
360
+ binding,
361
+ type: resolved.type,
362
+ region: required(addressBits(binding.address)).region,
363
+ });
364
+ }
365
+
366
+ const placed: {
367
+ region: "I" | "Q";
368
+ start: number;
369
+ end: number;
370
+ name: string;
371
+ shared?: boolean;
372
+ }[] = [];
373
+ for (const { name, binding, type, region, span } of targets) {
374
+ // An array binds at its first element; the remaining elements follow at
375
+ // consecutive addresses of the same width, like an EDS byte/word span.
376
+ const array = type.kind === "array" ? type : undefined;
377
+ const element = array ? tables.typeOf(array.element) : type;
378
+ // Typegen spells channels as IEC types; equal layouts bind (an EDS UINT flag word into a WORD).
379
+ const layout = ioSpelling(type, tables, ioLayout);
380
+ if (binding.type && (!layout || ioLayout(binding.type) !== layout)) {
381
+ report(
382
+ `I/O type mismatch for ${name}: ${type.id} cannot bind to ${binding.type}.`,
383
+ span,
384
+ );
385
+ }
386
+ const address = required(addressBits(binding.address));
387
+ if (address.region !== region) {
388
+ report(
389
+ `Wrong address region for ${name}: expected %${region}${binding.address.charAt(2)}.`,
390
+ span,
391
+ );
392
+ }
393
+ if (region === "I" && element.kind === "float") {
394
+ report(
395
+ "Floating logical inputs require an explicit runtime nonfinite policy, which is not supported yet.",
396
+ span,
397
+ );
398
+ }
399
+ if (array && element.kind === "bool") {
400
+ report(
401
+ `BOOL arrays are not bit-packed in CODESYS I/O; bind each element of ${name} separately.`,
402
+ span,
403
+ );
404
+ }
405
+ if (ioSpelling(element, tables, ioScalarBits) !== address.bits) {
406
+ report(`Address size does not match ${name}:${type.id}.`, span);
407
+ }
408
+ const start = address.offsetBits;
409
+ const end = start + address.bits * (array?.length ?? 1);
410
+ if (
411
+ binding.inverted &&
412
+ (region !== "I" || element.kind !== "bool" || array)
413
+ ) {
414
+ report(`Only a BOOL input can be inverted: ${name}.`, span);
415
+ }
416
+ if (binding.shared && region !== "I") {
417
+ report(`Only an input can be shared: ${name}.`, span);
418
+ }
419
+ const collision = placed.find(
420
+ (other) =>
421
+ other.region === address.region &&
422
+ other.start < end &&
423
+ start < other.end &&
424
+ !(
425
+ binding.shared &&
426
+ other.shared &&
427
+ other.start === start &&
428
+ other.end === end
429
+ ),
430
+ );
431
+ if (collision) {
432
+ report(
433
+ `Overlapping I/O address ${binding.address} with ${collision.name}.`,
434
+ span,
435
+ );
436
+ }
437
+ placed.push({
438
+ region: address.region,
439
+ start,
440
+ end,
441
+ name,
442
+ shared: binding.shared,
443
+ });
444
+ // The address's number, which CODESYS counts in elements of its size: %IW12 is bytes 24-25.
445
+ const unit = address.bits === 1 ? 8 : address.bits;
446
+ if (Math.floor(address.offsetBits / unit) > 0x7fff_ffff) {
447
+ report(`I/O offset is too large: ${binding.address}.`, span);
448
+ }
449
+ }
450
+ return storageBindings;
451
+ }
452
+
453
+ /** What `read` makes of a type's IEC spelling, or undefined for a type typegen does not spell. */
454
+ const ioSpelling = <T>(
455
+ type: PlcType,
456
+ tables: CoreTables,
457
+ read: (spelling: string) => T,
458
+ ): T | undefined => {
459
+ const spelling = iecSpelling(type, tables.types);
460
+ return spelling === undefined ? undefined : read(spelling);
461
+ };
462
+
463
+ /** Two storage bindings conflict when one target contains the other. */
464
+ function nested(left: StorageBinding, right: StorageBinding): boolean {
465
+ return (
466
+ left.root.id === right.root.id &&
467
+ left.segments.every((a, index) => {
468
+ const b = right.segments[index];
469
+ if (!b) {
470
+ return true;
471
+ }
472
+ return a.kind === "field"
473
+ ? b.kind === "field" && a.name === b.name
474
+ : b.kind === "index" && a.value === b.value;
475
+ })
476
+ );
477
+ }
478
+
479
+ // `planCodesys` callers pass deployments that no config schema has seen, so the planner checks
480
+ // each task against the raw ST schedule's rules, and the rules that need the program: CODESYS
481
+ // task names are identifiers, and each program runs in exactly one task.
482
+ function validateTasks(
483
+ core: VerifiedCoreModule,
484
+ deployment: Deployment,
485
+ report: Report,
486
+ ): void {
487
+ const issues =
488
+ cyclicTasksSchema.safeParse(deployment.tasks).error?.issues ?? [];
489
+ const refused = (index: number, field: string) =>
490
+ issues.filter(({ path }) => path[0] === index && path[1] === field);
491
+ // zod skips the schema's own repeat check once any task has a type issue.
492
+ const repeats = scheduleRepeats(deployment.tasks);
493
+ const repeated = (task: number, position: number | null) =>
494
+ repeats.some((item) => item.task === task && item.position === position);
495
+ const programs = new Map(
496
+ core.programs.map((program) => [program.name, program]),
497
+ );
498
+ const checkOwnership = taskStorageOwnership(core, report);
499
+ deployment.tasks.forEach((task, index) => {
500
+ if (!isIecIdentifier(task.name)) {
501
+ report(`Invalid task name ${task.name}.`);
502
+ }
503
+ if (repeated(index, null)) {
504
+ report(`Duplicate task name ${task.name}.`);
505
+ }
506
+ if (refused(index, "priority").length) {
507
+ report(
508
+ `Task ${task.name} priority must be ${taskPriority.minValue}..${taskPriority.maxValue}.`,
509
+ );
510
+ }
511
+ const interval = refused(index, "intervalNanoseconds");
512
+ if (interval.some(({ code }) => code === "invalid_format")) {
513
+ report(`Invalid task interval for ${task.name}.`);
514
+ } else if (interval.length) {
515
+ report(
516
+ `Task ${task.name} requires an exact positive TIME interval in milliseconds.`,
517
+ );
518
+ }
519
+ if (refused(index, "programs").some(({ path }) => path.length === 2)) {
520
+ report(`Task ${task.name} has no programs.`);
521
+ }
522
+ task.programs.forEach((name, position) => {
523
+ const program = programs.get(name);
524
+ if (!program) {
525
+ report(`Unknown task program ${name}.`);
526
+ return;
527
+ }
528
+ if (repeated(index, position)) {
529
+ report(`Program ${name} must belong to exactly one task.`);
530
+ }
531
+ checkOwnership(task.name, program);
532
+ });
533
+ });
534
+ const scheduled = new Set(deployment.tasks.flatMap((task) => task.programs));
535
+ for (const name of programs.keys()) {
536
+ if (!scheduled.has(name)) {
537
+ report(`Program ${name} has no cyclic task.`);
538
+ }
539
+ }
540
+ }
541
+
542
+ function validateProgramNames(
543
+ core: VerifiedCoreModule,
544
+ programNames: Readonly<Record<string, string>>,
545
+ report: Report,
546
+ ): void {
547
+ if (core.blocks.some((block) => block.standard === "Blinker")) {
548
+ for (const target of Object.values(programNames)) {
549
+ if (target.toUpperCase() === "UTIL") {
550
+ report(
551
+ `IEC object name ${target} shadows the Util library namespace required by Blinker.`,
552
+ );
553
+ }
554
+ }
555
+ }
556
+ const programs = new Set(core.programs.map((program) => program.name));
557
+ const explicitNames = new Set<string>();
558
+ for (const [name, target] of Object.entries(programNames)) {
559
+ if (!programs.has(name)) {
560
+ report(`Unknown program name override ${name}.`);
561
+ }
562
+ if (explicitNames.has(target.toUpperCase())) {
563
+ report(`Duplicate IEC program name ${target}.`);
564
+ }
565
+ explicitNames.add(target.toUpperCase());
566
+ }
567
+ }
568
+
569
+ /**
570
+ * InOut addresses must not survive a retained restart, including nested children. CODESYS accepts
571
+ * one persistent variable list in an application, so only one module's storage may persist.
572
+ */
573
+ function validateRetain(core: VerifiedCoreModule, report: Report): void {
574
+ const { types, blockOf } = coreTables(core);
575
+ const blockHasInOut = (id: string): boolean => {
576
+ const block = blockOf(id);
577
+ return (
578
+ block.inputs.some((input) => input.mode === "inOut") ||
579
+ block.state.some((field) => {
580
+ const type = instancedBlock(field.type, types);
581
+ return type !== undefined && blockHasInOut(type.block);
582
+ })
583
+ );
584
+ };
585
+
586
+ const layout = storageLayout(core);
587
+ for (const block of core.blocks) {
588
+ if (layout.retainedBlocks.has(block.id) && blockHasInOut(block.id)) {
589
+ report(
590
+ "Retained function blocks cannot contain direct or nested InOut references.",
591
+ block.span,
592
+ );
593
+ }
594
+ }
595
+ for (const variable of core.variables) {
596
+ const type = instancedBlock(variable.type, types);
597
+ if (variable.retention !== "none" && type && blockHasInOut(type.block)) {
598
+ report(
599
+ "Retained function blocks cannot contain direct or nested InOut references.",
600
+ variable.span,
601
+ );
602
+ }
603
+ }
604
+ const [, ...others] = layout.globalLists.filter(
605
+ (list) => list.kind === "persistent",
606
+ );
607
+ for (const list of others) {
608
+ report(
609
+ "CODESYS keeps one persistent variable list per application: persist the storage of one module only.",
610
+ list.variables[0]?.span,
611
+ );
612
+ }
613
+ }
614
+
615
+ function validateConstants(core: VerifiedCoreModule, report: Report): void {
616
+ const { typeOf } = coreTables(core);
617
+ const constant = (value: Constant, id: string, span?: SourceSpan): void => {
618
+ const type = typeOf(id);
619
+ if (type.kind === "string" && value.kind === "string") {
620
+ if (
621
+ type.encoding === "utf8" &&
622
+ [...value.value].some(
623
+ (character) =>
624
+ character.charCodeAt(0) === 0 || character.charCodeAt(0) > 127,
625
+ )
626
+ ) {
627
+ report(
628
+ "Non-ASCII STRING literals require a verified project-wide UTF8 setting; this profile supports ASCII literals.",
629
+ span,
630
+ );
631
+ }
632
+ if (type.encoding === "utf16" && /[\uD800-\uDFFF]/.test(value.value)) {
633
+ report(
634
+ "CODESYS WSTRING uses UCS-2 and cannot represent surrogate code units.",
635
+ span,
636
+ );
637
+ }
638
+ }
639
+ if (type.kind === "array" && value.kind === "array") {
640
+ for (const item of value.items) {
641
+ constant(item, type.element, span);
642
+ }
643
+ }
644
+ if (type.kind === "record" && value.kind === "record") {
645
+ for (const field of type.fields) {
646
+ constant(required(value.fields[field.name]), field.type, span);
647
+ }
648
+ }
649
+ };
650
+ const constantsInExpression = (value: CoreExpression): void => {
651
+ if (value.kind === "constant") {
652
+ constant(value.value, value.type, value.span);
653
+ }
654
+ subexpressions(value).forEach(constantsInExpression);
655
+ };
656
+ const constantsInBody = (items: readonly CoreStatement[]): void => {
657
+ for (const item of items) {
658
+ statementExpressions(item).forEach(constantsInExpression);
659
+ if (item.kind !== "switch") {
660
+ nestedBodies(item).forEach(constantsInBody);
661
+ continue;
662
+ }
663
+ for (const branch of item.cases) {
664
+ for (const value of branch.values) {
665
+ constant(value, item.value.type, item.span);
666
+ }
667
+ constantsInBody(branch.body);
668
+ }
669
+ constantsInBody(item.fallback);
670
+ }
671
+ };
672
+ core.variables.forEach((variable) => {
673
+ if (variable.initial) {
674
+ constant(variable.initial, variable.type, variable.span);
675
+ }
676
+ });
677
+ for (const fn of core.functions) {
678
+ constantsInBody(fn.body);
679
+ }
680
+ core.blocks.forEach((block) => {
681
+ [...block.outputs, ...block.state, ...block.locals].forEach((variable) => {
682
+ if (variable.initial) {
683
+ constant(variable.initial, variable.type, variable.span);
684
+ }
685
+ });
686
+ constantsInBody(block.body);
687
+ });
688
+ }