@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
@@ -1,457 +0,0 @@
1
- import {
2
- instancedBlock,
3
- type Constant,
4
- type CoreExpression,
5
- type CorePath,
6
- type CoreStatement,
7
- type Deployment,
8
- type Diagnostic,
9
- isVerifiedCore,
10
- type PlcType,
11
- telemetryOperands,
12
- type SourceSpan,
13
- type VerifiedCoreModule,
14
- } from "@tsplc/compiler/ir";
15
- import { type CodesysOptions, optionsSchema } from "./config.ts";
16
- import { ioLayout, ioScalarBits } from "@tsplc/typegen/hardware";
17
- import { iecSpelling, isStoragePath, resolveStoragePath, type StorageBinding } from "./io-paths.ts";
18
- import { isIecIdentifier } from "./names.ts";
19
- import { storageLayout } from "./storage.ts";
20
- import { validateHttpLayout, resolveHttpEndpoint, type HttpEndpoint } from "./http.ts";
21
- import { accessedStorage, schedulePrograms, taskStorageOwnership } from "./task-access.ts";
22
- import { resolvePublication } from "./publication.ts";
23
- import type {
24
- Publication,
25
- ResolvedDebugConfig,
26
- ResolvedTelemetryConfig,
27
- ResolvedTsplcConfig,
28
- } from "@tsplc/config";
29
- import type { ProjectHardware } from "./manifest.ts";
30
- import { planTelemetry, telemetryClient, type TelemetryPlan } from "./telemetry.ts";
31
-
32
- // Only this planner can admit a target configuration for emission. Cloning a
33
- // branded-looking object does not give it membership in this private identity set.
34
- const planned: unique symbol = Symbol("CODESYS plan");
35
- export interface CodesysPlan {
36
- readonly [planned]: true;
37
- readonly core: VerifiedCoreModule;
38
- readonly deployment: Deployment;
39
- readonly options: CodesysOptions;
40
- /** `io` keys that name authored storage, resolved against the verified types. */
41
- readonly storageBindings: readonly StorageBinding[];
42
- readonly publication: Publication;
43
- readonly http: Readonly<Record<string, HttpEndpoint>>;
44
- readonly project: CodesysProject;
45
- /** Each task's records and their sender, when the program has telemetry. */
46
- readonly telemetry?: TelemetryPlan;
47
- }
48
- /**
49
- * What the debug manifest describes beyond the program, the instrumentation `debug` asks for,
50
- * and the telemetry settings and server its records go to.
51
- */
52
- export interface CodesysProject {
53
- /** Manifest sources and telemetry `source`s are relative to this directory. */
54
- root: string;
55
- debug?: ResolvedDebugConfig;
56
- telemetry?: ResolvedTelemetryConfig;
57
- server?: Pick<NonNullable<ResolvedTsplcConfig["server"]>, "transport" | "baseUrlEnv">;
58
- hardware?: ProjectHardware;
59
- }
60
- const plans = new WeakSet<object>();
61
- export function diagnostic(message: string, span?: SourceSpan): Diagnostic {
62
- return { origin: "backend", code: "PLC7001", severity: "error", message, ...(span && { span }) };
63
- }
64
- export function isCodesysPlan(plan: CodesysPlan): boolean {
65
- return plans.has(plan);
66
- }
67
-
68
- export function planCodesys(
69
- core: VerifiedCoreModule,
70
- deployment: Deployment,
71
- value: unknown,
72
- project: CodesysProject = { root: process.cwd() },
73
- ): { plan?: CodesysPlan; diagnostics: readonly Diagnostic[] } {
74
- if (!isVerifiedCore(core))
75
- return { diagnostics: [diagnostic("CODESYS requires a verified, normalized core module.")] };
76
-
77
- const parsed = optionsSchema.safeParse(value);
78
- if (!parsed.success)
79
- return {
80
- diagnostics: parsed.error.issues.map((issue) =>
81
- diagnostic(`${issue.path.join(".")}: ${issue.message}`),
82
- ),
83
- };
84
-
85
- const options = parsed.data;
86
- const diagnostics: Diagnostic[] = [];
87
- const report = (message: string, span?: SourceSpan): void => {
88
- diagnostics.push(diagnostic(message, span));
89
- };
90
- deployment = { tasks: schedulePrograms(core, deployment.tasks, report) };
91
- const http = new Map<string, HttpEndpoint>();
92
- for (const block of core.blocks)
93
- if (block.runtime?.kind === "http" || block.runtime?.kind === "rpc") {
94
- try {
95
- validateHttpLayout(block, new Map(core.types.map((type) => [type.id, type])));
96
- http.set(
97
- block.id,
98
- block.runtime.kind === "rpc"
99
- ? {
100
- transport: "opcua",
101
- host: "",
102
- port: 0,
103
- authority: "",
104
- path: block.runtime.path,
105
- token: "",
106
- timeoutMs: options.http.timeoutMs,
107
- tls: false,
108
- }
109
- : resolveHttpEndpoint(block.runtime.url, options.http),
110
- );
111
- } catch (cause) {
112
- report(cause instanceof Error ? cause.message : String(cause), block.span);
113
- }
114
- }
115
-
116
- const storageBindings = validateIo(core, options, report);
117
- validateTasks(core, deployment, report);
118
- validateStorage(core, options, report);
119
- validateConstants(core, report);
120
- const { telemetry, endpoint } = planTelemetry(
121
- core,
122
- deployment,
123
- options,
124
- { ...project, trace: project.debug?.trace },
125
- report,
126
- );
127
- if (endpoint) http.set(telemetryClient, endpoint);
128
- const { publication, errors } = resolvePublication(core, options.publish);
129
- for (const error of errors) report(error);
130
-
131
- if (diagnostics.length) return { diagnostics };
132
-
133
- const plan: CodesysPlan = Object.freeze({
134
- core,
135
- deployment: structuredClone(deployment),
136
- options: structuredClone(options),
137
- storageBindings,
138
- publication,
139
- http: Object.fromEntries(http),
140
- project,
141
- ...(telemetry && { telemetry }),
142
- [planned]: true as const,
143
- });
144
- // Parsed options can contain nested engineering settings; detach and freeze the complete plan.
145
- const freeze = (value: unknown): void => {
146
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) return;
147
- for (const child of Object.values(value)) freeze(child);
148
- Object.freeze(value);
149
- };
150
- freeze(plan.deployment);
151
- freeze(plan.options);
152
- freeze(plan.storageBindings);
153
- freeze(plan.publication);
154
- plans.add(plan);
155
- return { plan, diagnostics: [] };
156
- }
157
-
158
- type Report = (message: string, span?: SourceSpan) => void;
159
-
160
- /** Validate every `io` binding and return the ones that name authored storage. */
161
- function validateIo(
162
- core: VerifiedCoreModule,
163
- options: CodesysOptions,
164
- report: Report,
165
- ): StorageBinding[] {
166
- // Compare physical bindings as bit intervals, regardless of their spelling.
167
- // Different widths can still overlap.
168
- const types = new Map(core.types.map((type) => [type.id, type]));
169
- const targets: {
170
- name: string;
171
- binding: CodesysOptions["io"][string];
172
- type: PlcType;
173
- region: "I" | "Q";
174
- span?: SourceSpan;
175
- }[] = [];
176
- const names = new Set<string>();
177
- for (const item of core.variables.filter(
178
- (item) => item.storage === "input" || item.storage === "output",
179
- )) {
180
- if (names.has(item.name))
181
- report(`Ambiguous I/O name ${item.name}; logical I/O names must be unique.`, item.span);
182
- names.add(item.name);
183
- const binding = Object.hasOwn(options.io, item.name) ? options.io[item.name] : undefined;
184
- if (!binding) {
185
- report(`Missing I/O binding for ${item.name}.`, item.span);
186
- continue;
187
- }
188
- targets.push({
189
- name: item.name,
190
- binding,
191
- type: types.get(item.type)!,
192
- region: item.storage === "input" ? "I" : "Q",
193
- span: item.span,
194
- });
195
- }
196
-
197
- const scheduled = new Set<string>();
198
- for (const program of core.programs) {
199
- const fn = core.functions.find((item) => item.id === program.entry)!;
200
- for (const id of accessedStorage(fn, core)) scheduled.add(id);
201
- }
202
- const storageBindings: StorageBinding[] = [];
203
- for (const [name, binding] of Object.entries(options.io)) {
204
- if (names.has(name)) continue;
205
- if (!isStoragePath(name)) {
206
- report(`Unknown I/O binding ${name}.`);
207
- continue;
208
- }
209
- const resolved = resolveStoragePath(core, name);
210
- if ("error" in resolved) {
211
- report(resolved.error);
212
- continue;
213
- }
214
- const overlapping = storageBindings.find((other) => nested(other, resolved));
215
- if (overlapping) report(`${name} overlaps the binding ${overlapping.key}.`);
216
- if (!scheduled.has(resolved.root.id))
217
- report(
218
- `${name}: no scheduled program uses ${resolved.root.name}, so it would never be copied.`,
219
- );
220
- storageBindings.push(resolved);
221
- targets.push({
222
- name,
223
- binding,
224
- type: resolved.type,
225
- region: binding.address[1] === "I" ? "I" : "Q",
226
- });
227
- }
228
-
229
- const addresses: {
230
- region: string;
231
- start: bigint;
232
- end: bigint;
233
- name: string;
234
- shared?: boolean;
235
- }[] = [];
236
- for (const { name, binding, type, region, span } of targets) {
237
- // An array binds at its first element; the remaining elements follow at
238
- // consecutive addresses of the same width, like an EDS byte/word span.
239
- const array = type.kind === "array" ? type : undefined;
240
- const element = array ? types.get(array.element) : type;
241
- // Typegen spells channels as IEC types; equal layouts bind (an EDS UINT flag word into a WORD).
242
- const layout = ioLayout(iecSpelling(type, types) ?? "");
243
- if (binding.type && (!layout || ioLayout(binding.type) !== layout))
244
- report(`I/O type mismatch for ${name}: ${type.id} cannot bind to ${binding.type}.`, span);
245
- if (!binding.address.startsWith(`%${region}`))
246
- report(`Wrong address region for ${name}: expected %${region}X.`, span);
247
- const match = /^%([IQ])([XBWD])([0-9]+)(?:\.([0-7]))?$/.exec(binding.address);
248
- if (!match) continue;
249
- if (region === "I" && element?.kind === "float")
250
- report(
251
- "Floating logical inputs require an explicit runtime nonfinite policy, which is not supported yet.",
252
- span,
253
- );
254
- if (array && element?.kind === "bool")
255
- report(
256
- `BOOL arrays are not bit-packed in CODESYS I/O; bind each element of ${name} separately.`,
257
- span,
258
- );
259
- const size = match[2] === "X" ? 1 : match[2] === "B" ? 8 : match[2] === "W" ? 16 : 32;
260
- const elementBits = element && ioScalarBits(iecSpelling(element, types) ?? "");
261
- if (elementBits !== size) report(`Address size does not match ${name}:${type.id}.`, span);
262
- // CODESYS numbers %IW/%ID by element: %IW12 is bytes 24-25. See verify.py.
263
- const unit = size === 1 ? 8n : BigInt(size);
264
- const offset = BigInt(match[3]!);
265
- const start = offset * unit + BigInt(match[4] ?? 0),
266
- end = start + BigInt(size) * BigInt(array?.length ?? 1);
267
- if (binding.inverted && (region !== "I" || element?.kind !== "bool" || array))
268
- report(`Only a BOOL input can be inverted: ${name}.`, span);
269
- if (binding.shared && region !== "I") report(`Only an input can be shared: ${name}.`, span);
270
- const collision = addresses.find(
271
- (address) =>
272
- address.region === match[1] &&
273
- address.start < end &&
274
- start < address.end &&
275
- !(binding.shared && address.shared && address.start === start && address.end === end),
276
- );
277
- if (collision)
278
- report(`Overlapping I/O address ${binding.address} with ${collision.name}.`, span);
279
- addresses.push({ region: match[1]!, start, end, name, shared: binding.shared });
280
- if (offset > 0x7fff_ffffn) report(`I/O offset is too large: ${binding.address}.`, span);
281
- }
282
- return storageBindings;
283
- }
284
-
285
- /** Two storage bindings conflict when one target contains the other. */
286
- function nested(left: StorageBinding, right: StorageBinding): boolean {
287
- return (
288
- left.root.id === right.root.id &&
289
- left.segments.every((a, index) => {
290
- const b = right.segments[index];
291
- if (!b) return true;
292
- return a.kind === "field"
293
- ? b.kind === "field" && a.name === b.name
294
- : b.kind === "index" && a.value === b.value;
295
- })
296
- );
297
- }
298
-
299
- function validateTasks(core: VerifiedCoreModule, deployment: Deployment, report: Report): void {
300
- const programs = new Map(core.programs.map((program) => [program.name, program]));
301
- const assignment = new Map<string, string>();
302
- const taskNames = new Set<string>();
303
- const checkOwnership = taskStorageOwnership(core, report);
304
- for (const task of deployment.tasks) {
305
- if (!isIecIdentifier(task.name)) report(`Invalid task name ${task.name}.`);
306
- if (taskNames.has(task.name.toUpperCase())) report(`Duplicate task name ${task.name}.`);
307
- taskNames.add(task.name.toUpperCase());
308
- if (!Number.isInteger(task.priority) || task.priority < 0 || task.priority > 31)
309
- report(`Task ${task.name} priority must be 0..31.`);
310
- if (!/^[1-9][0-9]*$/.test(task.intervalNanoseconds))
311
- report(`Invalid task interval for ${task.name}.`);
312
- else {
313
- const ns = BigInt(task.intervalNanoseconds);
314
- if (ns % 1_000_000n || ns > 4_294_967_295_000_000n)
315
- report(`Task ${task.name} requires an exact positive TIME interval in milliseconds.`);
316
- }
317
- if (!task.programs.length) report(`Task ${task.name} has no programs.`);
318
- for (const name of task.programs) {
319
- const program = programs.get(name);
320
- if (!program) {
321
- report(`Unknown task program ${name}.`);
322
- continue;
323
- }
324
- if (assignment.has(name)) report(`Program ${name} must belong to exactly one task.`);
325
- assignment.set(name, task.name);
326
- checkOwnership(task.name, program);
327
- }
328
- }
329
- for (const name of programs.keys())
330
- if (!assignment.has(name)) report(`Program ${name} has no cyclic task.`);
331
- }
332
-
333
- function validateStorage(core: VerifiedCoreModule, options: CodesysOptions, report: Report): void {
334
- const programs = new Map(core.programs.map((program) => [program.name, program]));
335
- if (core.blocks.some((block) => block.standard === "Blinker")) {
336
- for (const target of Object.values(options.programNames ?? {})) {
337
- if (target.toUpperCase() === "UTIL")
338
- report(`IEC object name ${target} shadows the Util library namespace required by Blinker.`);
339
- }
340
- }
341
- const explicitNames = new Set<string>();
342
- for (const [name, target] of Object.entries(options.programNames ?? {})) {
343
- if (!programs.has(name)) report(`Unknown program name override ${name}.`);
344
- if (explicitNames.has(target.toUpperCase())) report(`Duplicate IEC program name ${target}.`);
345
- explicitNames.add(target.toUpperCase());
346
- }
347
- const types = new Map(core.types.map((type) => [type.id, type]));
348
- const blocks = new Map(core.blocks.map((block) => [block.id, block]));
349
-
350
- // InOut addresses must not survive a retained restart, including nested children.
351
- const blockHasInOut = (id: string): boolean => {
352
- const block = blocks.get(id)!;
353
- return (
354
- block.inputs.some((input) => input.mode === "inOut") ||
355
- block.state.some((field) => {
356
- const type = instancedBlock(field.type, types);
357
- return type !== undefined && blockHasInOut(type.block);
358
- })
359
- );
360
- };
361
-
362
- const layout = storageLayout(core);
363
- for (const block of core.blocks)
364
- if (layout.retainedBlocks.has(block.id) && blockHasInOut(block.id))
365
- report(
366
- "Retained function blocks cannot contain direct or nested InOut references.",
367
- block.span,
368
- );
369
- for (const variable of core.variables) {
370
- const type = instancedBlock(variable.type, types);
371
- if (variable.retain && type && blockHasInOut(type.block))
372
- report(
373
- "Retained function blocks cannot contain direct or nested InOut references.",
374
- variable.span,
375
- );
376
- }
377
- }
378
-
379
- function validateConstants(core: VerifiedCoreModule, report: Report): void {
380
- const types = new Map(core.types.map((type) => [type.id, type]));
381
- const constant = (value: Constant, id: string, span?: SourceSpan): void => {
382
- const type = types.get(id)!;
383
- if (type.kind === "string" && value.kind === "string") {
384
- if (
385
- type.encoding === "utf8" &&
386
- [...value.value].some(
387
- (character) => character.charCodeAt(0) === 0 || character.charCodeAt(0) > 127,
388
- )
389
- )
390
- report(
391
- "Non-ASCII STRING literals require a verified project-wide UTF8 setting; this profile supports ASCII literals.",
392
- span,
393
- );
394
- if (type.encoding === "utf16" && /[\uD800-\uDFFF]/.test(value.value))
395
- report("CODESYS WSTRING uses UCS-2 and cannot represent surrogate code units.", span);
396
- }
397
- if (type.kind === "array" && value.kind === "array")
398
- for (const item of value.items) constant(item, type.element, span);
399
- if (type.kind === "record" && value.kind === "record")
400
- for (const field of type.fields) constant(value.fields[field.name]!, field.type, span);
401
- };
402
- const constantsInPath = (path: CorePath = []): void => {
403
- for (const segment of path) if (segment.kind === "index") constantsInExpression(segment.value);
404
- };
405
- const constantsInExpression = (value: CoreExpression): void => {
406
- if (value.kind === "constant") constant(value.value, value.type, value.span);
407
- if (value.kind === "load") constantsInPath(value.path);
408
- if (value.kind === "borrow") constantsInPath(value.place.path);
409
- if (value.kind === "unary" || value.kind === "convert") constantsInExpression(value.operand);
410
- if (value.kind === "binary") {
411
- constantsInExpression(value.left);
412
- constantsInExpression(value.right);
413
- }
414
- };
415
- const constantsInBody = (items: readonly CoreStatement[]): void => {
416
- for (const item of items) {
417
- if (item.kind === "assign") {
418
- constantsInExpression(item.value);
419
- constantsInPath(item.path);
420
- }
421
- if (item.kind === "if") {
422
- constantsInExpression(item.condition);
423
- constantsInBody(item.then);
424
- constantsInBody(item.else);
425
- }
426
- if (item.kind === "switch") {
427
- constantsInExpression(item.value);
428
- item.cases.forEach((branch) => {
429
- for (const value of branch.values) constant(value, item.value.type, item.span);
430
- constantsInBody(branch.body);
431
- });
432
- constantsInBody(item.fallback);
433
- }
434
- if (item.kind === "for") constantsInBody(item.body);
435
- if (item.kind === "invoke") {
436
- if (item.index) constantsInExpression(item.index);
437
- item.arguments.forEach(constantsInExpression);
438
- }
439
- if (item.kind === "blockUpdate") {
440
- if (item.index) constantsInExpression(item.index);
441
- Object.values(item.inputs).forEach(constantsInExpression);
442
- }
443
- if (item.kind === "return" && item.value) constantsInExpression(item.value);
444
- if (item.kind === "telemetry") telemetryOperands(item).forEach(constantsInExpression);
445
- }
446
- };
447
- core.variables.forEach((variable) => {
448
- if (variable.initial) constant(variable.initial, variable.type, variable.span);
449
- });
450
- for (const fn of core.functions) constantsInBody(fn.body);
451
- core.blocks.forEach((block) => {
452
- [...block.outputs, ...block.state, ...block.locals].forEach((variable) => {
453
- if (variable.initial) constant(variable.initial, variable.type, variable.span);
454
- });
455
- constantsInBody(block.body);
456
- });
457
- }
@@ -1,59 +0,0 @@
1
- import type { Publication } from "@tsplc/config";
2
- import type { VerifiedCoreModule } from "@tsplc/compiler/ir";
3
- import { moduleFile, moduleName } from "./storage.ts";
4
-
5
- const globals = (core: VerifiedCoreModule) =>
6
- core.variables.filter((variable) => variable.storage === "module" && variable.exported);
7
-
8
- /** Source names are independent of CODESYS name allocation and the active build target. */
9
- export const publicationSelectors = (core: VerifiedCoreModule): string[] => {
10
- const variables = globals(core);
11
- return [
12
- ...new Set(
13
- variables.flatMap((variable) => [
14
- moduleName(variable),
15
- `${moduleName(variable)}.${variable.name}`,
16
- ]),
17
- ),
18
- ].sort();
19
- };
20
-
21
- export const resolvePublication = (
22
- core: VerifiedCoreModule,
23
- policy: Publication,
24
- ): { publication: Publication; errors: string[] } => {
25
- const variables = globals(core);
26
- const errors: string[] = [];
27
- const select = (selectors: readonly string[]) => {
28
- const selected = new Set(
29
- variables.filter((variable) => variable.exposure).map((variable) => variable.id),
30
- );
31
- const seen = new Set<string>();
32
- for (const selector of selectors) {
33
- if (seen.has(selector)) errors.push(`Duplicate publication selector ${selector}.`);
34
- seen.add(selector);
35
- const candidates = variables.filter(
36
- (variable) =>
37
- selector === moduleName(variable) ||
38
- selector === `${moduleName(variable)}.${variable.name}`,
39
- );
40
- if (!candidates.length) {
41
- errors.push(
42
- `Unknown publication selector ${selector}; select an exported mutable global or its module.`,
43
- );
44
- continue;
45
- }
46
- if (new Set(candidates.map(moduleFile)).size !== 1) {
47
- errors.push(`Ambiguous publication selector ${selector}.`);
48
- continue;
49
- }
50
- for (const variable of candidates) selected.add(variable.id);
51
- }
52
- return variables.filter((variable) => selected.has(variable.id)).map((variable) => variable.id);
53
- };
54
- const publication = {
55
- production: select(policy.production),
56
- development: select(policy.development),
57
- };
58
- return { publication, errors };
59
- };
@@ -1,70 +0,0 @@
1
- import { basename } from "node:path";
2
- import { instancedBlock, type Variable, type VerifiedCoreModule } from "@tsplc/compiler/ir";
3
-
4
- interface GlobalList {
5
- id: string;
6
- module: string;
7
- storage: "constants" | "retained" | "state";
8
- variables: Variable[];
9
- }
10
-
11
- /**
12
- * The module that declares a module-level variable, from its id. Spans point at what the user
13
- * wrote, which for elaborated storage is not the module the elaborator made for it.
14
- */
15
- export const moduleFile = (variable: Variable): string =>
16
- variable.id.slice(0, variable.id.indexOf(":"));
17
-
18
- /** The module's name: its file name without extension. */
19
- export const moduleName = (variable: Variable): string =>
20
- basename(moduleFile(variable)).replace(/\.[^.]+$/, "");
21
-
22
- /** CODESYS promotes an enclosing instance when private child state is retained. */
23
- export function storageLayout(core: VerifiedCoreModule) {
24
- const types = new Map(core.types.map((type) => [type.id, type]));
25
- const blocks = new Map(core.blocks.map((block) => [block.id, block]));
26
- const retention = new Map<string, boolean>();
27
- const blockRetained = (id: string): boolean => {
28
- const cached = retention.get(id);
29
- if (cached !== undefined) return cached;
30
- const block = blocks.get(id);
31
- if (!block) throw new Error("Missing verified block during retention planning.");
32
- const retained = block.state.some((field) => {
33
- const type = instancedBlock(field.type, types);
34
- return field.retain || (type !== undefined && blockRetained(type.block));
35
- });
36
- retention.set(id, retained);
37
- return retained;
38
- };
39
-
40
- const retainedBlocks = new Set(
41
- core.blocks.filter((block) => blockRetained(block.id)).map((block) => block.id),
42
- );
43
- const retainedVariables = new Set(
44
- [...core.variables, ...core.blocks.flatMap((block) => block.state)]
45
- .filter((variable) => {
46
- const type = instancedBlock(variable.type, types);
47
- return variable.retain || (type !== undefined && retainedBlocks.has(type.block));
48
- })
49
- .map((variable) => variable.id),
50
- );
51
-
52
- const groups = new Map<string, GlobalList>();
53
- for (const variable of core.variables) {
54
- if (variable.storage === "input" || variable.storage === "output") continue;
55
- const storage =
56
- variable.storage === "constant"
57
- ? "constants"
58
- : retainedVariables.has(variable.id)
59
- ? "retained"
60
- : "state";
61
- const id = `${moduleFile(variable)}:${storage}`;
62
- let group = groups.get(id);
63
- if (!group) {
64
- group = { id, module: moduleName(variable), storage, variables: [] };
65
- groups.set(id, group);
66
- }
67
- group.variables.push(variable);
68
- }
69
- return { retainedBlocks, retainedVariables, globalLists: [...groups.values()] };
70
- }