@tsplc/compiler 0.2.17 → 0.2.18

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,142 @@
1
+ import type {
2
+ EmitResult,
3
+ GeneratedObject,
4
+ SourceSpan,
5
+ } from "@tsplc/compiler/ir";
6
+ import type { Publication } from "@tsplc/config";
7
+ import type { DebugManifest } from "@tsplc/debug/manifest";
8
+ import {
9
+ emitGlobalLists,
10
+ emitIoList,
11
+ type IoMapping,
12
+ ioTarget,
13
+ } from "./global-lists.ts";
14
+ import { emitServiceBlock, httpNetwork, type RpcChannel } from "./http.ts";
15
+ import {
16
+ emitDebugGlobal,
17
+ emitTelemetry,
18
+ planInstrumentation,
19
+ } from "./instrumentation.ts";
20
+ import { debugManifest } from "./manifest.ts";
21
+ import { type CodesysPlan, diagnostic, isCodesysPlan } from "./plan.ts";
22
+ import { emitScanProgram } from "./programs.ts";
23
+ import { machineInterfaces, publishedSymbols } from "./publication.ts";
24
+ import { emitRoutine } from "./routines.ts";
25
+ import { stFiles } from "./st-files.ts";
26
+ import {
27
+ allocateBlockFields,
28
+ allocateFunctionNames,
29
+ allocateRoutineScope,
30
+ createSymbols,
31
+ } from "./symbols.ts";
32
+
33
+ export interface SourceMapping {
34
+ path: string;
35
+ line: number;
36
+ span: SourceSpan;
37
+ }
38
+
39
+ type CodesysBundle = EmitResult & {
40
+ /** Variables a generated device tree maps to their bit or byte channels. */
41
+ ioMappings: readonly IoMapping[];
42
+ mappings: readonly SourceMapping[];
43
+ ioSymbols: Readonly<Record<string, string>>;
44
+ publication: Publication;
45
+ /** The debugger's view of this build; its id is also published as `build.target`. */
46
+ debug?: DebugManifest;
47
+ };
48
+
49
+ // A bundle owns target names and source mappings. Per-routine declarations and
50
+ // implementation lines stay local to emitRoutine, so they cannot leak between POUs.
51
+ export function emitCodesys(plan: CodesysPlan): CodesysBundle {
52
+ if (!isCodesysPlan(plan)) {
53
+ return {
54
+ artifacts: [],
55
+ objects: [],
56
+ mappings: [],
57
+ ioSymbols: {},
58
+ publication: { production: [], development: [] },
59
+ ioMappings: [],
60
+ diagnostics: [diagnostic("Emission requires a validated CODESYS plan.")],
61
+ };
62
+ }
63
+ const { core } = plan;
64
+ const symbols = createSymbols(plan);
65
+ const instrumentation = planInstrumentation(plan, symbols);
66
+ const context = { plan, symbols, instrumentation };
67
+ const globalLists = emitGlobalLists(plan, symbols);
68
+ const ioList = emitIoList(plan, symbols);
69
+ const network = httpNetwork(plan, symbols);
70
+ const objects: GeneratedObject[] = [
71
+ ...symbols.targetTypes.objects,
72
+ ...globalLists.objects,
73
+ ...ioList.objects,
74
+ ...(network ? [network] : []),
75
+ ];
76
+ const mappings: SourceMapping[] = [
77
+ ...globalLists.mappings,
78
+ ...ioList.mappings,
79
+ ];
80
+
81
+ // Helpers must be discovered before allocating local names: an ST local must
82
+ // never shadow a helper, function, FB, or DUT that the implementation calls.
83
+ allocateFunctionNames(symbols, plan);
84
+ for (const fn of core.functions) {
85
+ symbols.numeric.prepareStatements(fn.body);
86
+ }
87
+ for (const block of core.blocks) {
88
+ symbols.numeric.prepareStatements(block.body);
89
+ }
90
+ objects.push(...symbols.numeric.objects);
91
+ allocateBlockFields(symbols, instrumentation, plan, objects);
92
+
93
+ objects.push(...emitTelemetry(plan, symbols, instrumentation, network?.name));
94
+ const routines = [
95
+ ...core.functions,
96
+ ...core.blocks.filter((block) => !block.standard),
97
+ ];
98
+ for (const fn of routines) {
99
+ allocateRoutineScope(symbols, instrumentation, objects, fn);
100
+ }
101
+ const rpcChannels: RpcChannel[] = [];
102
+ for (const fn of routines) {
103
+ if (
104
+ "inputs" in fn &&
105
+ (fn.runtime?.kind === "http" || fn.runtime?.kind === "rpc")
106
+ ) {
107
+ const service = emitServiceBlock(context, network?.name, fn);
108
+ objects.push(...service.objects);
109
+ rpcChannels.push(...service.rpcChannels);
110
+ continue;
111
+ }
112
+ const routine = emitRoutine(context, fn);
113
+ objects.push(...routine.objects);
114
+ mappings.push(...routine.mappings);
115
+ }
116
+ for (const program of core.programs) {
117
+ objects.push(emitScanProgram(context, ioList.channels, program));
118
+ }
119
+ const debug = emitDebugGlobal(
120
+ plan,
121
+ instrumentation,
122
+ objects,
123
+ debugManifest(context, (key) => ioTarget(plan, symbols, key)),
124
+ );
125
+
126
+ return {
127
+ artifacts: [
128
+ ...stFiles(plan, symbols, objects, mappings),
129
+ ...machineInterfaces(plan, symbols, rpcChannels),
130
+ ],
131
+ objects,
132
+ mappings,
133
+ ioSymbols: Object.fromEntries([
134
+ ...ioList.channels.map((channel) => [channel.key, channel.target]),
135
+ ...ioList.ioMappings.map((mapping) => [mapping.key, mapping.variable]),
136
+ ]),
137
+ ioMappings: ioList.ioMappings,
138
+ publication: publishedSymbols(plan, symbols, rpcChannels),
139
+ debug,
140
+ diagnostics: [],
141
+ };
142
+ }
@@ -0,0 +1,109 @@
1
+ import { resolve } from "node:path";
2
+ import type { EmitResult } from "@tsplc/compiler/ir";
3
+ import {
4
+ buildProject,
5
+ configSchema,
6
+ type InstalledLibrary,
7
+ resolveConfig,
8
+ } from "@tsplc/build";
9
+ import type { Controller, DeviceTree } from "@tsplc/config";
10
+ import { z } from "zod";
11
+ import type { CodesysPlan } from "./plan.ts";
12
+
13
+ export const engineeringBuildSchema = configSchema.omit({
14
+ sourceDir: true,
15
+ entry: true,
16
+ outDir: true,
17
+ task: true,
18
+ tasks: true,
19
+ });
20
+ export const engineeringSchema = z.strictObject({
21
+ kind: z.literal("v3.5"),
22
+ build: engineeringBuildSchema.optional(),
23
+ });
24
+ export type CodesysEngineeringBuild = z.input<typeof engineeringBuildSchema>;
25
+
26
+ export function codesysBuildConfig(
27
+ plan: CodesysPlan,
28
+ bundle: Pick<EmitResult, "objects">,
29
+ paths: {
30
+ configFile: string;
31
+ sourceDir: string;
32
+ outDir: string;
33
+ libraries?: InstalledLibrary[];
34
+ deviceTree?: DeviceTree;
35
+ controller?: Controller;
36
+ },
37
+ ) {
38
+ const settings = plan.options.engineering.build;
39
+ if (!settings) {
40
+ throw new Error(
41
+ "CODESYS build requires engineering.build settings (codesys installation and template). Configure them or use --emit-only.",
42
+ );
43
+ }
44
+ const programs = new Map(
45
+ plan.core.programs.map((program) => {
46
+ const matches = bundle.objects.filter(
47
+ (object) => object.id === program.id && object.kind === "program",
48
+ );
49
+ const generated = matches[0];
50
+ if (matches.length !== 1 || !generated) {
51
+ throw new Error(
52
+ `Generated bundle must contain one PROGRAM object for ${program.name}.`,
53
+ );
54
+ }
55
+ return [program.name, generated] as const;
56
+ }),
57
+ );
58
+ const tasks = plan.deployment.tasks.map((task) => ({
59
+ ...task,
60
+ programs: task.programs.map((name) => {
61
+ const program = programs.get(name);
62
+ if (!program) {
63
+ throw new Error(
64
+ `Task ${task.name} references a missing generated PROGRAM ${name}.`,
65
+ );
66
+ }
67
+ return program.name;
68
+ }),
69
+ }));
70
+ const first = plan.core.programs[0];
71
+ const entry = first && programs.get(first.name);
72
+ if (!entry) {
73
+ throw new Error("CODESYS build requires a generated PROGRAM entry.");
74
+ }
75
+ const sourceDir = resolve(paths.sourceDir);
76
+ return resolveConfig(
77
+ {
78
+ ...settings,
79
+ libraryReferences: [
80
+ ...(settings.libraryReferences ?? []),
81
+ ...(Object.values(plan.http).some(
82
+ (endpoint) => endpoint.transport !== "opcua",
83
+ )
84
+ ? ["Net Base Services, 4.0.0.0 (CODESYS)"]
85
+ : []),
86
+ ...(Object.values(plan.http).some((endpoint) => endpoint.tls)
87
+ ? ["CmpX509Cert Implementation, 3.5.22.0 (System)"]
88
+ : []),
89
+ ],
90
+ ...(paths.libraries ? { libraries: paths.libraries } : {}),
91
+ ...(paths.deviceTree ? { deviceTree: paths.deviceTree } : {}),
92
+ ...(paths.controller ? { controller: paths.controller } : {}),
93
+ sourceDir,
94
+ entry: resolve(
95
+ sourceDir,
96
+ entry.sourcePath ?? `${entry.name}/declaration.st`,
97
+ ),
98
+ outDir: resolve(paths.outDir),
99
+ tasks,
100
+ },
101
+ paths.configFile,
102
+ );
103
+ }
104
+
105
+ export async function buildCodesys(
106
+ ...arguments_: Parameters<typeof codesysBuildConfig>
107
+ ) {
108
+ return buildProject(codesysBuildConfig(...arguments_));
109
+ }
@@ -0,0 +1,92 @@
1
+ import type { CoreExpression, CorePath } from "@tsplc/compiler/ir";
2
+ import { type CodesysSymbols, required } from "./symbols.ts";
3
+
4
+ /** The storage a routine's ST can name: module storage, IO and its own variables, with their types. */
5
+ export interface StorageScope {
6
+ symbols: CodesysSymbols;
7
+ names: ReadonlyMap<string, string>;
8
+ types: ReadonlyMap<string, string>;
9
+ }
10
+
11
+ export const storageName = ({ names }: StorageScope, id: string): string => {
12
+ const value = names.get(id);
13
+ if (!value) {
14
+ throw new Error(`Missing verified storage ${id}.`);
15
+ }
16
+ return value;
17
+ };
18
+
19
+ // Block output records are a source abstraction; target FB fields are direct.
20
+ export const placeText = (
21
+ scope: StorageScope,
22
+ id: string,
23
+ path: CorePath = [],
24
+ ): string => {
25
+ const { typeMap, blocks, blockFields, targetTypes } = scope.symbols;
26
+ let text = storageName(scope, id);
27
+ let typeId = required(scope.types.get(id));
28
+ let outputBlock: string | undefined;
29
+ for (const segment of path) {
30
+ const type = required(typeMap.get(typeId));
31
+ if (
32
+ segment.kind === "field" &&
33
+ type.kind === "block" &&
34
+ segment.name === "out"
35
+ ) {
36
+ outputBlock = type.block;
37
+ typeId = required(type.output);
38
+ continue;
39
+ }
40
+ if (segment.kind === "field" && outputBlock) {
41
+ const output = required(
42
+ required(blocks.get(outputBlock)).outputs.find(
43
+ (field) => field.name === segment.name,
44
+ ),
45
+ );
46
+ text += `.${required(required(blockFields.get(outputBlock)).get(output.id))}`;
47
+ typeId = output.type;
48
+ outputBlock = undefined;
49
+ } else if (segment.kind === "field" && type.kind === "record") {
50
+ text += `.${targetTypes.field(typeId, segment.name)}`;
51
+ typeId = required(
52
+ type.fields.find((field) => field.name === segment.name),
53
+ ).type;
54
+ } else if (segment.kind === "index" && type.kind === "array") {
55
+ // A strict enum converts explicitly to its DINT base, as HTTP JSON encoding does.
56
+ text +=
57
+ typeMap.get(segment.value.type)?.kind === "enum"
58
+ ? `[TO_DINT(${expressionText(scope, segment.value)})]`
59
+ : `[${expressionText(scope, segment.value)}]`;
60
+ typeId = type.element;
61
+ } else {
62
+ throw new Error("Invalid verified place");
63
+ }
64
+ }
65
+ return text;
66
+ };
67
+
68
+ export const expressionText = (
69
+ scope: StorageScope,
70
+ value: CoreExpression,
71
+ ): string => {
72
+ const { typeMap, targetTypes, numeric } = scope.symbols;
73
+ if (value.kind === "constant") {
74
+ return targetTypes.literal(value.value, value.type);
75
+ }
76
+ if (value.kind === "load") {
77
+ return placeText(scope, value.root, value.path);
78
+ }
79
+ if (value.kind === "borrow") {
80
+ return placeText(scope, value.place.root, value.place.path);
81
+ }
82
+ if (value.kind === "convert" && typeMap.get(value.type)?.kind === "string") {
83
+ return expressionText(scope, value.operand);
84
+ }
85
+ if (value.kind === "unary" || value.kind === "convert") {
86
+ return numeric.render(value, [expressionText(scope, value.operand)]);
87
+ }
88
+ return numeric.render(value, [
89
+ expressionText(scope, value.left),
90
+ expressionText(scope, value.right),
91
+ ]);
92
+ };
@@ -0,0 +1,250 @@
1
+ import {
2
+ defaultValue,
3
+ type GeneratedObject,
4
+ instancedBlock,
5
+ type Variable,
6
+ } from "@tsplc/compiler/ir";
7
+ import type { SourceMapping } from "./emit.ts";
8
+ import {
9
+ isStoragePath,
10
+ resolveStoragePath,
11
+ type StorageBinding,
12
+ } from "./io-paths.ts";
13
+ import { Names } from "./names.ts";
14
+ import type { GlobalStorage } from "./storage.ts";
15
+ import type { CodesysPlan } from "./plan.ts";
16
+ import { type CodesysSymbols, required } from "./symbols.ts";
17
+
18
+ const globalSections = {
19
+ constants: "VAR_GLOBAL CONSTANT",
20
+ retained: "VAR_GLOBAL RETAIN",
21
+ state: "VAR_GLOBAL",
22
+ } as const satisfies Record<GlobalStorage, string>;
23
+
24
+ /** Each `io` binding: an AT wire copied to or from its logical target around the scan. */
25
+ export interface IoChannel {
26
+ key: string;
27
+ root: string;
28
+ input: boolean;
29
+ target: string;
30
+ wire: string;
31
+ inverted?: boolean;
32
+ }
33
+
34
+ /** A variable a generated device tree maps to its bit or byte channel. */
35
+ export interface IoMapping {
36
+ key: string;
37
+ address: string;
38
+ variable: string;
39
+ }
40
+
41
+ const globalInitializer = (
42
+ { typeMap, targetTypes }: CodesysSymbols,
43
+ storage: GlobalStorage,
44
+ item: Variable,
45
+ ): string => {
46
+ if (instancedBlock(item.type, typeMap)) {
47
+ return "";
48
+ }
49
+ const value = item.initial ?? defaultValue(item.type, typeMap);
50
+ // CONSTANT declarations always keep their initializer. Mutable zero
51
+ // aggregates use the same implicit initialization as the original ST.
52
+ return storage === "constants"
53
+ ? ` := ${targetTypes.literal(value, item.type)}`
54
+ : targetTypes.declarationInitializer(value, item.type);
55
+ };
56
+
57
+ /** The global lists of module storage; each variable's global symbol goes into `symbols.references`. */
58
+ export function emitGlobalLists(
59
+ plan: CodesysPlan,
60
+ symbols: CodesysSymbols,
61
+ ): { objects: GeneratedObject[]; mappings: SourceMapping[] } {
62
+ const { options } = plan;
63
+ const { globals, references, targetTypes } = symbols;
64
+ const objects: GeneratedObject[] = [];
65
+ const mappings: SourceMapping[] = [];
66
+ for (const group of globals) {
67
+ const { name, fields } = group;
68
+ const published = new Set(plan.publication[options.buildTarget]);
69
+ const publish = group.variables.some((variable) =>
70
+ published.has(variable.id),
71
+ );
72
+ const lines = [
73
+ ...(publish ? ["{attribute 'linkalways'}"] : []),
74
+ "{attribute 'qualified_only'}",
75
+ globalSections[group.storage],
76
+ ];
77
+ for (const item of group.variables) {
78
+ const field = required(fields.get(item.id));
79
+ references.set(item.id, `${name}.${field}`);
80
+ if (published.has(item.id)) {
81
+ lines.push(
82
+ ` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`,
83
+ );
84
+ }
85
+ mappings.push({
86
+ path: `${name}.st`,
87
+ line: lines.length + 1,
88
+ span: item.span,
89
+ });
90
+ const initial = globalInitializer(symbols, group.storage, item);
91
+ lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
92
+ }
93
+ lines.push("END_VAR");
94
+ objects.push({
95
+ id: group.id,
96
+ kind: "globalList",
97
+ name,
98
+ declaration: `${lines.join("\n")}\n`,
99
+ });
100
+ }
101
+ return { objects, mappings };
102
+ }
103
+
104
+ /**
105
+ * `GVL_IO`: logical IO and the AT wires of `io` bindings. Logical IO's global symbols go into
106
+ * `symbols.references`.
107
+ */
108
+ export function emitIoList(
109
+ plan: CodesysPlan,
110
+ symbols: CodesysSymbols,
111
+ ): {
112
+ objects: GeneratedObject[];
113
+ mappings: SourceMapping[];
114
+ channels: IoChannel[];
115
+ ioMappings: IoMapping[];
116
+ } {
117
+ const { core, options } = plan;
118
+ const { names, references, targetTypes, typeMap } = symbols;
119
+ const objects: GeneratedObject[] = [];
120
+ const mappings: SourceMapping[] = [];
121
+ const channels: IoChannel[] = [];
122
+ const ioMappings: IoMapping[] = [];
123
+ const ioName = names.allocate("GVL_IO");
124
+ const ioFields = new Names();
125
+ for (const name of symbols.blockNames.values()) {
126
+ ioFields.reserve(name);
127
+ }
128
+ const ioLines = [
129
+ "{attribute 'linkalways'}",
130
+ "{attribute 'qualified_only'}",
131
+ "VAR_GLOBAL",
132
+ ];
133
+ for (const item of core.variables.filter(
134
+ (item) => item.storage === "input" || item.storage === "output",
135
+ )) {
136
+ const field = ioFields.allocate(item.name);
137
+ const initial = item.initial ?? defaultValue(item.type, typeMap);
138
+ const binding = required(options.io[item.name]);
139
+ references.set(item.id, `${ioName}.${field}`);
140
+ if (binding.mapped) {
141
+ ioMappings.push({
142
+ key: item.name,
143
+ address: binding.address,
144
+ variable: `${ioName}.${field}`,
145
+ });
146
+ mappings.push({
147
+ path: `${ioName}.st`,
148
+ line: ioLines.length + 2,
149
+ span: item.span,
150
+ });
151
+ ioLines.push(
152
+ " {attribute 'symbol' := 'read'}",
153
+ ` ${field} : ${targetTypes.name(item.type)} := ${targetTypes.literal(initial, item.type)};`,
154
+ );
155
+ continue;
156
+ }
157
+ const wire = ioFields.allocate(`${item.name}_physical`);
158
+ channels.push({
159
+ key: item.name,
160
+ root: item.id,
161
+ input: item.storage === "input",
162
+ target: `${ioName}.${field}`,
163
+ wire: `${ioName}.${wire}`,
164
+ inverted: binding.inverted,
165
+ });
166
+ mappings.push(
167
+ { path: `${ioName}.st`, line: ioLines.length + 1, span: item.span },
168
+ { path: `${ioName}.st`, line: ioLines.length + 3, span: item.span },
169
+ );
170
+ ioLines.push(
171
+ ` ${wire} AT ${binding.address} : ${targetTypes.name(item.type)};`,
172
+ // Publish the scan's logical value for monitoring. Physical wires stay
173
+ // private; external writes cannot alter the controller's IO snapshot.
174
+ " {attribute 'symbol' := 'read'}",
175
+ ` ${field} : ${targetTypes.name(item.type)} := ${targetTypes.literal(initial, item.type)};`,
176
+ );
177
+ }
178
+ for (const { key, root, segments, type } of plan.storageBindings) {
179
+ const { address, mapped, inverted } = required(options.io[key]);
180
+ const target = bindingTarget(symbols, { root, segments });
181
+ if (mapped) {
182
+ ioMappings.push({ key, address, variable: target });
183
+ continue;
184
+ }
185
+ const wire = ioFields.allocate(
186
+ `${key.replace(/\W+/g, "_").replace(/_+$/, "")}_physical`,
187
+ );
188
+ // The wire takes the target's own type, so equal-width EDS types need no conversion.
189
+ ioLines.push(` ${wire} AT ${address} : ${targetTypes.name(type.id)};`);
190
+ channels.push({
191
+ key,
192
+ root: root.id,
193
+ input: address[1] === "I",
194
+ target,
195
+ wire: `${ioName}.${wire}`,
196
+ inverted,
197
+ });
198
+ }
199
+ ioLines.push("END_VAR");
200
+ // Mapped storage bindings need no IO list; mapped logical IO is declared here.
201
+ if (ioLines.length > 4) {
202
+ objects.push({
203
+ id: "io",
204
+ kind: "globalList",
205
+ name: ioName,
206
+ declaration: `${ioLines.join("\n")}\n`,
207
+ });
208
+ }
209
+ return { objects, mappings, channels, ioMappings };
210
+ }
211
+
212
+ /** The target symbol of an `io` storage path. */
213
+ function bindingTarget(
214
+ symbols: CodesysSymbols,
215
+ { root, segments }: Pick<StorageBinding, "root" | "segments">,
216
+ ): string {
217
+ return segments.reduce(
218
+ (path, segment) =>
219
+ segment.kind === "field"
220
+ ? `${path}.${symbols.targetTypes.field(segment.record, segment.name)}`
221
+ : `${path}[${segment.value}]`,
222
+ required(symbols.references.get(root.id)),
223
+ );
224
+ }
225
+
226
+ /** The target symbol and type that hold an `io` key's value, when this program has it. */
227
+ export function ioTarget(
228
+ { core }: CodesysPlan,
229
+ symbols: CodesysSymbols,
230
+ key: string,
231
+ ): { target: string; type: string } | undefined {
232
+ const logical = core.variables.find(
233
+ (variable) =>
234
+ (variable.storage === "input" || variable.storage === "output") &&
235
+ variable.name === key,
236
+ );
237
+ if (logical) {
238
+ return {
239
+ target: required(symbols.references.get(logical.id)),
240
+ type: logical.type,
241
+ };
242
+ }
243
+ if (!isStoragePath(key)) {
244
+ return undefined;
245
+ }
246
+ const resolved = resolveStoragePath(core, key);
247
+ return "error" in resolved
248
+ ? undefined
249
+ : { target: bindingTarget(symbols, resolved), type: resolved.type.id };
250
+ }
@@ -0,0 +1,68 @@
1
+ import { standardBlocks, type VerifiedCoreModule } from "@tsplc/compiler/ir";
2
+ import { Names, pascalCase } from "./names.ts";
3
+ import { storageLayout } from "./storage.ts";
4
+ import { CodesysTypes } from "./types.ts";
5
+
6
+ export const planGlobalNames = (
7
+ core: VerifiedCoreModule,
8
+ programNames: Readonly<Record<string, string>> = {},
9
+ ) => {
10
+ const names = new Names();
11
+ for (const name of Object.values(programNames)) {
12
+ names.reserve(name);
13
+ }
14
+
15
+ const typeMap = new Map(core.types.map((type) => [type.id, type]));
16
+ const blockNames = new Map(
17
+ core.blocks.map((block) => [
18
+ block.id,
19
+ block.standard
20
+ ? standardBlocks[block.standard].native
21
+ : names.allocateObject("FB", block.name),
22
+ ]),
23
+ );
24
+ for (const name of blockNames.values()) {
25
+ names.reserve(name);
26
+ }
27
+ const targetTypes = new CodesysTypes(typeMap, names, blockNames);
28
+
29
+ const { globalLists, retainedVariables } = storageLayout(core);
30
+ const hasExports = (group: (typeof globalLists)[number]) =>
31
+ group.variables.some((variable) => variable.exported && !variable.exposure);
32
+ const globals = globalLists.map((group) => {
33
+ const splitByStorage = globalLists.some(
34
+ (other) =>
35
+ other.module === group.module &&
36
+ other.storage !== group.storage &&
37
+ hasExports(other),
38
+ );
39
+ // Exported lists are the program's public interface. Private storage stays generated.
40
+ const name = hasExports(group)
41
+ ? names.allocate(
42
+ pascalCase(
43
+ splitByStorage ? `${group.module}-${group.storage}` : group.module,
44
+ ),
45
+ )
46
+ : names.allocateObject("GVL", `${group.module}_${group.storage}`);
47
+ const fields = new Names();
48
+ for (const name of blockNames.values()) {
49
+ fields.reserve(name);
50
+ }
51
+ return {
52
+ ...group,
53
+ name,
54
+ fields: new Map(
55
+ group.variables.map((item) => [item.id, fields.allocate(item.name)]),
56
+ ),
57
+ };
58
+ });
59
+
60
+ return {
61
+ names,
62
+ typeMap,
63
+ blockNames,
64
+ targetTypes,
65
+ globals,
66
+ retainedVariables,
67
+ };
68
+ };