@tsplc/compiler 0.2.14 → 0.2.17

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 (54) hide show
  1. package/backends/codesys/debug.ts +509 -0
  2. package/backends/codesys/emit.ts +701 -9
  3. package/backends/codesys/http.ts +110 -34
  4. package/backends/codesys/index.ts +2 -1
  5. package/backends/codesys/io-paths.ts +3 -1
  6. package/backends/codesys/manifest.ts +312 -0
  7. package/backends/codesys/plan.ts +39 -9
  8. package/backends/codesys/publication.ts +2 -2
  9. package/backends/codesys/storage.ts +10 -3
  10. package/backends/codesys/task-access.ts +51 -1
  11. package/backends/codesys/telemetry.ts +593 -0
  12. package/backends/codesys/types.ts +2 -1
  13. package/dist/cli.js +190 -33
  14. package/dist/cli.js.map +6 -6
  15. package/dist/codesys.js +2148 -432
  16. package/dist/codesys.js.map +14 -11
  17. package/dist/elaborate-capture.js +7 -1
  18. package/dist/elaborate-capture.js.map +3 -3
  19. package/dist/index.js +877 -459
  20. package/dist/index.js.map +16 -15
  21. package/dist/ir.js +87 -23
  22. package/dist/ir.js.map +10 -9
  23. package/dist/project.js +42 -9
  24. package/dist/project.js.map +3 -3
  25. package/dist/telemetry.js +83 -0
  26. package/dist/telemetry.js.map +12 -0
  27. package/ir/core-model.ts +13 -0
  28. package/ir/core.ts +1 -0
  29. package/ir/errors.ts +20 -0
  30. package/ir/index.ts +1 -0
  31. package/ir/link.ts +17 -8
  32. package/ir/model.ts +39 -0
  33. package/ir/routine.ts +62 -29
  34. package/ir/types.ts +7 -1
  35. package/package.json +12 -6
  36. package/project/cli.ts +96 -6
  37. package/project/plant.ts +58 -9
  38. package/project/project.ts +56 -10
  39. package/src/frontend/async.ts +284 -195
  40. package/src/frontend/configuration.ts +7 -21
  41. package/src/frontend/const-functions.ts +44 -38
  42. package/src/frontend/elaborate/capture.ts +7 -0
  43. package/src/frontend/elaborate/index.ts +135 -61
  44. package/src/frontend/elaborate/layouts.ts +8 -0
  45. package/src/frontend/elaborate/model.ts +13 -0
  46. package/src/frontend/elaborate/specialize.ts +302 -111
  47. package/src/frontend/exposure.ts +28 -26
  48. package/src/frontend/positions.ts +272 -0
  49. package/src/frontend/promises.ts +52 -47
  50. package/src/frontend/services.ts +16 -26
  51. package/src/frontend/types.ts +14 -0
  52. package/src/frontend/typescript.ts +185 -65
  53. package/stdlib/telemetry.ts +72 -0
  54. package/types/telemetry.d.ts +44 -0
@@ -69,10 +69,39 @@ export const resolveHttpEndpoint = (value: string, input: HttpOptions): HttpEndp
69
69
  tls: url.protocol === "https:",
70
70
  };
71
71
  };
72
- const quote = (text: string) =>
73
- "'" +
74
- text.replaceAll("$", "$$").replaceAll("'", "$'").replaceAll("\r", "$R").replaceAll("\n", "$N") +
75
- "'";
72
+ const escapes: Record<string, string> = { $: "$$", "'": "$'", "\r": "$R", "\n": "$N" };
73
+ /** An ST string literal. */
74
+ export const quote = (text: string) =>
75
+ `'${text.replace(/[$'\r\n]/g, (character) => escapes[character]!)}'`;
76
+
77
+ /**
78
+ * The ST that appends a BOOL, integer, bit string or UTF-8 STRING `value` as JSON with the
79
+ * encoder methods of `httpMethods`, and the most bytes it can append.
80
+ */
81
+ export const jsonScalar = (
82
+ type: PlcType,
83
+ value: string,
84
+ ): { code: string; size: number } | undefined => {
85
+ if (type.kind === "string" && type.encoding === "utf8" && type.capacity <= 2048)
86
+ return { code: `WriteString(${value});`, size: type.capacity * 6 + 2 };
87
+ if (type.kind === "bool")
88
+ return { code: `IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`, size: 5 };
89
+ if (type.kind === "bits") {
90
+ const wide = type.bits <= 32 ? "UDINT" : "ULINT";
91
+ return {
92
+ code: `Append(${wide}_TO_STRING(TO_${wide}(${value})));`,
93
+ size: String(2n ** BigInt(type.bits) - 1n).length,
94
+ };
95
+ }
96
+ if (type.kind === "integer") {
97
+ const bits = BigInt(type.bits);
98
+ return {
99
+ code: `Append(${type.id}_TO_STRING(${value}));`,
100
+ size: String(type.signed ? -(2n ** (bits - 1n)) : 2n ** bits - 1n).length,
101
+ };
102
+ }
103
+ return undefined;
104
+ };
76
105
 
77
106
  const httpLayouts = (block: CoreFunctionBlock, types: ReadonlyMap<string, PlcType>) => {
78
107
  const request = block.inputs.find((v) => v.name === "request"),
@@ -89,18 +118,17 @@ const httpLayouts = (block: CoreFunctionBlock, types: ReadonlyMap<string, PlcTyp
89
118
  throw new Error("HTTP requires closed request/response records with 1..31 response fields.");
90
119
  const scalarSize = (id: string): number => {
91
120
  const type = types.get(id);
92
- if (type?.kind === "string" && type.encoding === "utf8" && type.capacity <= 2048)
93
- return type.capacity * 6 + 2;
94
- if (type?.kind === "bool") return 5;
95
121
  if (type?.kind === "enum")
96
122
  return Math.max(...type.members.map((member) => member.value.length));
97
- if ((type?.kind === "integer" || type?.kind === "bits") && type.bits <= 32) {
98
- const signed = type.kind === "integer" && type.signed;
99
- return String(signed ? -(2 ** (type.bits - 1)) : 2 ** type.bits - 1).length;
100
- }
101
- throw new Error(
102
- "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.",
103
- );
123
+ const scalar =
124
+ type && !((type.kind === "integer" || type.kind === "bits") && type.bits > 32)
125
+ ? jsonScalar(type, "")
126
+ : undefined;
127
+ if (!scalar)
128
+ throw new Error(
129
+ "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.",
130
+ );
131
+ return scalar.size;
104
132
  };
105
133
  const recordSize = (record: typeof requestLayout, response: boolean) =>
106
134
  2 +
@@ -135,6 +163,8 @@ export const emitHttp = (
135
163
  endpoint: HttpEndpoint,
136
164
  network: string,
137
165
  rpcGlobal?: string,
166
+ /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
167
+ trace?: { job: string; sequence: string },
138
168
  ): GeneratedObject => {
139
169
  const port = (label: string) => {
140
170
  const variable = [...block.inputs, ...block.outputs].find((v) => v.name === label);
@@ -150,15 +180,9 @@ export const emitHttp = (
150
180
  (_, i) =>
151
181
  `${i ? "Append(',');" : ""}${encode(type.element, `${value}[${i + type.lowerBound}]`)}`,
152
182
  ).join("\n");
153
- if (type.kind === "string" && type.encoding === "utf8" && type.capacity <= 2048)
154
- return `WriteString(${value});`;
155
- if (type.kind === "bool")
156
- return `IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`;
157
183
  if (type.kind === "enum") return `Append(DINT_TO_STRING(TO_DINT(${value})));`;
158
- if (type.kind === "bits" && type.bits <= 32)
159
- return `Append(UDINT_TO_STRING(TO_UDINT(${value})));`;
160
- if (type.kind === "integer" && type.bits <= 32)
161
- return `Append(${target.name(typeId)}_TO_STRING(${value}));`;
184
+ const scalar = jsonScalar(type, value);
185
+ if (scalar) return scalar.code;
162
186
  throw new Error(
163
187
  "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, integers up to 32 bits and fixed arrays.",
164
188
  );
@@ -283,18 +307,70 @@ IF stage=90 THEN
283
307
  END_IF;`,
284
308
  };
285
309
  }
286
- // Helpers are emitted as native methods under the HTTP block by the emitter.
287
- return {
310
+ return nativeHttp({
288
311
  id: block.id,
289
- kind: "functionBlock",
290
312
  name,
291
- declaration: `FUNCTION_BLOCK ${name}
292
- VAR_INPUT
293
- ${inputs}
313
+ ports: `VAR_INPUT
314
+ ${inputs}${trace ? `\n${trace.job} : UDINT;` : ""}
294
315
  END_VAR
295
316
  VAR_OUTPUT
296
317
  ${outputs}
297
- END_VAR
318
+ END_VAR`,
319
+ port,
320
+ endpoint,
321
+ network,
322
+ method: block.runtime?.kind === "http" ? block.runtime.method : "GET",
323
+ json: block.runtime?.kind === "http" && block.runtime.json,
324
+ body:
325
+ block.runtime?.kind === "http" && block.runtime.json
326
+ ? `Append('{'); ${requestCode} Append('}');`
327
+ : "",
328
+ decode: decodeResponse,
329
+ ...(trace && { trace }),
330
+ });
331
+ };
332
+
333
+ /**
334
+ * A native HTTP/1.1 client block over Net Base Services: it sends what `body` appends to
335
+ * `payload` and, on a 2xx response, runs `decode` over the response body in `payload`.
336
+ */
337
+ export const nativeHttp = ({
338
+ id,
339
+ name,
340
+ ports,
341
+ port,
342
+ endpoint,
343
+ network,
344
+ method,
345
+ json,
346
+ body,
347
+ decode,
348
+ trace,
349
+ }: {
350
+ id: string;
351
+ name: string;
352
+ /** Its input and output declarations, with `start`, `cancel`, `busy`, `done` and `error`. */
353
+ ports: string;
354
+ port: (label: string) => string;
355
+ endpoint: HttpEndpoint;
356
+ network: string;
357
+ method: string;
358
+ json: boolean;
359
+ body: string;
360
+ decode: string;
361
+ /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
362
+ trace?: { job: string; sequence: string };
363
+ }): GeneratedObject => {
364
+ const requestHeader = trace
365
+ ? `AppendWire(UDINT_TO_STRING(${trace.job}));AppendWire(':');AppendWire(UDINT_TO_STRING(${trace.sequence}));AppendWire('$R$NContent-Length: ');`
366
+ : "";
367
+ // Helpers are emitted as native methods under the HTTP block by the emitter.
368
+ return {
369
+ id,
370
+ kind: "functionBlock",
371
+ name,
372
+ declaration: `FUNCTION_BLOCK ${name}
373
+ ${ports}
298
374
  VAR
299
375
  remoteAddress : NBS.IPv4Address;
300
376
  remoteIP : NBS.IIPAddress := remoteAddress;
@@ -321,7 +397,7 @@ VAR
321
397
  numberValue : LINT;
322
398
  wireUsed : UINT;
323
399
  tokenUsed : UINT;
324
- index : UINT;
400
+ index : UINT;${trace ? `\n ${trace.sequence} : UDINT;` : ""}
325
401
  END_VAR
326
402
  `,
327
403
  // The host goes in the resolver call, not an initial value: an online change keeps the values
@@ -332,12 +408,12 @@ END_VAR
332
408
  RETURN;
333
409
  END_IF;
334
410
  IF stage=0 THEN
335
- payload:=''; malformed:=FALSE; used:=0; received:='';
336
- ${block.runtime?.kind === "http" && block.runtime.json ? `Append('{'); ${requestCode} Append('}');` : ""}
411
+ payload:=''; malformed:=FALSE; used:=0; received:='';${trace ? `\n ${trace.sequence}:=${trace.sequence}+1;` : ""}
412
+ ${body}
337
413
  IF malformed THEN ${port("error")}:=3; stage:=90;
338
414
  ELSE
339
415
  wire:='';wireUsed:=0;
340
- AppendWire(${quote((block.runtime?.kind === "http" ? block.runtime.method : "GET") + " " + endpoint.path + " HTTP/1.1\r\nHost: " + endpoint.authority + "\r\n" + (endpoint.token ? "Authorization: Bearer " + endpoint.token + "\r\n" : "") + (block.runtime?.kind === "http" && block.runtime.json ? "Content-Type: application/json\r\n" : "") + "Accept: application/json\r\nConnection: close\r\nContent-Length: ")});
416
+ AppendWire(${quote(method + " " + endpoint.path + " HTTP/1.1\r\nHost: " + endpoint.authority + "\r\n" + (endpoint.token ? "Authorization: Bearer " + endpoint.token + "\r\n" : "") + (json ? "Content-Type: application/json\r\n" : "") + "Accept: application/json\r\nConnection: close\r\n" + (trace ? "x-tsplc-request: " : "Content-Length: "))});${requestHeader}
341
417
  AppendWire(UINT_TO_STRING(ByteLength(payload)));AppendWire('$R$N$R$N');AppendWire(payload); stage:=10;
342
418
  END_IF;
343
419
  END_IF;
@@ -376,7 +452,7 @@ IF stage=3 THEN
376
452
  ELSIF TO_DINT(used)>=TO_DINT(headerEnd)+3+contentLength THEN
377
453
  IF status<200 OR status>=300 THEN ${port("error")}:=10000+status;stage:=90;
378
454
  ELSE
379
- payload:='';IF contentLength>0 THEN FOR index:=0 TO TO_UINT(contentLength)-1 DO payload[index]:=received[headerEnd+3+index]; END_FOR;END_IF;payload[TO_UINT(contentLength)]:=0; ${decodeResponse}
455
+ payload:='';IF contentLength>0 THEN FOR index:=0 TO TO_UINT(contentLength)-1 DO payload[index]:=received[headerEnd+3+index]; END_FOR;END_IF;payload[TO_UINT(contentLength)]:=0; ${decode}
380
456
  stage:=90;
381
457
  END_IF;
382
458
  END_IF;
@@ -6,7 +6,8 @@ export {
6
6
  type CodesysEngineeringBuild,
7
7
  engineeringBuildSchema,
8
8
  } from "./engineering.ts";
9
- export { type CodesysPlan, planCodesys } from "./plan.ts";
9
+ export { type CodesysPlan, type CodesysProject, planCodesys } from "./plan.ts";
10
+ export type { ProjectHardware } from "./manifest.ts";
10
11
  export { diagnoseCodesys } from "./vendor.ts";
11
12
  export { ioTargets } from "./io-paths.ts";
12
13
  export { publicationSelectors } from "./publication.ts";
@@ -67,7 +67,9 @@ export function iecSpelling(
67
67
  type.kind === "bool" ||
68
68
  type.kind === "integer" ||
69
69
  type.kind === "bits" ||
70
- type.kind === "float"
70
+ type.kind === "float" ||
71
+ type.kind === "duration" ||
72
+ type.kind === "calendar"
71
73
  )
72
74
  return type.id;
73
75
  if (type.kind !== "array") return undefined;
@@ -0,0 +1,312 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, relative } from "node:path";
3
+ import { standardBlocks } from "@tsplc/compiler/ir";
4
+ import type {
5
+ Constant,
6
+ CoreFunctionBlock,
7
+ PlcModule,
8
+ PlcType,
9
+ SourceSpan,
10
+ } from "@tsplc/compiler/ir";
11
+ import type { ResolvedTsplcConfig } from "@tsplc/config";
12
+ import type {
13
+ DebugConstant,
14
+ DebugDevice,
15
+ DebugIo,
16
+ DebugType,
17
+ SourceRange,
18
+ } from "@tsplc/debug/manifest";
19
+ import type { HardwareCatalog } from "@tsplc/typegen/hardware";
20
+ import type { CodesysTypes } from "./types.ts";
21
+
22
+ /** The configured hardware a manifest describes; `tree` when this build generates the device tree. */
23
+ export interface ProjectHardware {
24
+ catalog: HardwareCatalog;
25
+ config: Pick<ResolvedTsplcConfig, "devices" | "io">;
26
+ tree: boolean;
27
+ }
28
+
29
+ /** Project files by index. Spans outside the project, such as virtual modules and packages, have no range. */
30
+ export class Sources {
31
+ readonly files: string[] = [];
32
+ private readonly loaded = new Map<string, { text: string; lines: number[] } | undefined>();
33
+
34
+ constructor(private readonly root: string) {}
35
+
36
+ private load(file: string) {
37
+ if (this.loaded.has(file)) return this.loaded.get(file);
38
+ const path = relative(this.root, file);
39
+ const inside =
40
+ !path.startsWith("..") && !isAbsolute(path) && !path.split(/[\\/]/).includes("node_modules");
41
+ let source: { text: string; lines: number[] } | undefined;
42
+ if (inside && existsSync(file)) {
43
+ const text = readFileSync(file, "utf8");
44
+ const lines = [0];
45
+ for (let index = 0; index < text.length; index++)
46
+ if (text[index] === "\n") lines.push(index + 1);
47
+ source = { text, lines };
48
+ }
49
+ this.loaded.set(file, source);
50
+ return source;
51
+ }
52
+
53
+ range(span: SourceSpan): SourceRange | undefined {
54
+ const source = this.load(span.file);
55
+ if (!source || span.end > source.text.length) return undefined;
56
+ const position = (offset: number) => {
57
+ let low = 0,
58
+ high = source.lines.length - 1;
59
+ while (low < high) {
60
+ const middle = (low + high + 1) >> 1;
61
+ if (source.lines[middle]! <= offset) low = middle;
62
+ else high = middle - 1;
63
+ }
64
+ return { line: low + 1, column: offset - source.lines[low]! + 1 };
65
+ };
66
+ const path = relative(this.root, span.file).replaceAll("\\", "/");
67
+ let file = this.files.indexOf(path);
68
+ if (file < 0) file = this.files.push(path) - 1;
69
+ const start = position(span.start),
70
+ end = position(span.end);
71
+ return { file, ...start, endLine: end.line, endColumn: end.column };
72
+ }
73
+
74
+ text(span: SourceSpan): string | undefined {
75
+ return this.load(span.file)?.text.slice(span.start, span.end);
76
+ }
77
+ }
78
+
79
+ const scalarTypes: Partial<Record<PlcType["kind"], true>> = {
80
+ bool: true,
81
+ integer: true,
82
+ bits: true,
83
+ float: true,
84
+ duration: true,
85
+ calendar: true,
86
+ };
87
+
88
+ /** Every verified type by id, with TypeScript names and the target's field names. */
89
+ export function debugTypes(
90
+ types: readonly PlcType[],
91
+ target: CodesysTypes,
92
+ blocks: ReadonlyMap<string, CoreFunctionBlock>,
93
+ fields: (block: string, variable: string) => string,
94
+ extras: (block: string) => readonly { name: string; target: string; type: string }[],
95
+ sources: Sources,
96
+ ): Record<string, DebugType> {
97
+ const name = (id: string) => id.split(":").at(-1)!;
98
+ return Object.fromEntries(
99
+ types.map((type): [string, DebugType] => {
100
+ if (scalarTypes[type.kind]) return [type.id, { kind: "scalar", iec: type.id }];
101
+ switch (type.kind) {
102
+ case "string":
103
+ return [
104
+ type.id,
105
+ { kind: "scalar", iec: type.encoding === "utf8" ? "STRING" : "WSTRING" },
106
+ ];
107
+ case "enum":
108
+ return [
109
+ type.id,
110
+ {
111
+ kind: "enum",
112
+ name: name(type.id),
113
+ members: Object.fromEntries(
114
+ type.members.map((member) => [member.name, Number(member.value)]),
115
+ ),
116
+ },
117
+ ];
118
+ case "array":
119
+ return [
120
+ type.id,
121
+ { kind: "array", element: type.element, length: type.length, lower: type.lowerBound },
122
+ ];
123
+ case "record":
124
+ return [
125
+ type.id,
126
+ {
127
+ kind: "record",
128
+ name: name(type.id),
129
+ fields: type.fields.map((field) => ({
130
+ name: field.name,
131
+ target: target.field(type.id, field.name),
132
+ type: field.type,
133
+ })),
134
+ },
135
+ ];
136
+ case "block": {
137
+ const block = blocks.get(type.block)!;
138
+ const native = block.standard && standardBlocks[block.standard];
139
+ const generated = Boolean(block.job || block.runtime);
140
+ const declaration = sources.range(block.span);
141
+ return [
142
+ type.id,
143
+ {
144
+ kind: "record",
145
+ name: block.job?.name ?? block.name,
146
+ ...(declaration && { declaration }),
147
+ fields: [
148
+ ...[...block.inputs, ...block.outputs, ...block.state].map((variable) => {
149
+ const declaration = !native && sources.range(variable.span);
150
+ return {
151
+ name: variable.name,
152
+ target: fields(block.id, variable.id),
153
+ type: variable.type,
154
+ ...(declaration && { declaration }),
155
+ ...(generated && { generated: true as const }),
156
+ };
157
+ }),
158
+ ...extras(block.id).map((field) => ({ ...field, generated: true as const })),
159
+ ],
160
+ },
161
+ ];
162
+ }
163
+ }
164
+ throw new Error(`Unsupported verified type ${type.id}`);
165
+ }),
166
+ );
167
+ }
168
+
169
+ /** A folded constant's JSON value; integers beyond doubles' exact range stay strings. */
170
+ const constantValue = (value: Constant): unknown => {
171
+ switch (value.kind) {
172
+ case "integer":
173
+ return Number.isSafeInteger(Number(value.value)) ? Number(value.value) : value.value;
174
+ case "duration":
175
+ return `${BigInt(value.nanoseconds) / 1_000_000n}ms`;
176
+ case "array":
177
+ return value.items.map(constantValue);
178
+ case "record":
179
+ return Object.fromEntries(
180
+ Object.entries(value.fields).map(([field, item]) => [field, constantValue(item)]),
181
+ );
182
+ default:
183
+ return value.value;
184
+ }
185
+ };
186
+
187
+ /** For folded values without a declared type, such as strings: named by the IEC type that holds them. */
188
+ const constantTypes: Record<Constant["kind"], string> = {
189
+ bool: "BOOL",
190
+ integer: "LINT",
191
+ float: "LREAL",
192
+ duration: "TIME",
193
+ calendar: "DATE_AND_TIME",
194
+ string: "STRING",
195
+ array: "ARRAY",
196
+ record: "STRUCT",
197
+ };
198
+
199
+ export const debugConstants = (
200
+ folded: NonNullable<PlcModule["folded"]>,
201
+ sources: Sources,
202
+ ): DebugConstant[] =>
203
+ folded.map((item) => {
204
+ const declaration = sources.range(item.span);
205
+ return {
206
+ path: item.path,
207
+ type: item.type ?? constantTypes[item.value.kind],
208
+ value: constantValue(item.value),
209
+ ...(declaration && { declaration }),
210
+ };
211
+ });
212
+
213
+ /** The `%I`/`%Q` address a configured binding uses: its own, or its device channel's. */
214
+ export const ioAddress = (
215
+ { catalog }: ProjectHardware,
216
+ binding: ProjectHardware["config"]["io"][string],
217
+ ) =>
218
+ "address" in binding
219
+ ? binding.address
220
+ : catalog.devices
221
+ .find((device) => device.id === binding.device)
222
+ ?.channels.find((item) => item.id === binding.channel)?.address;
223
+
224
+ /**
225
+ * Each configured `io` binding joined with its device channel and the target that holds its
226
+ * value, and each device with its assemblies, named channels and driver state. A generated
227
+ * device tree names each adapter after its device, with a `<device>_Modbus` server for its
228
+ * registers, so the debugger reads their state there.
229
+ */
230
+ export function debugHardware(
231
+ hardware: ProjectHardware,
232
+ io: (key: string) => { target: string; type: string } | undefined,
233
+ /** The byte array over each of a device's assemblies. */
234
+ raw: (id: string) => Partial<Record<"input" | "output", string>>,
235
+ ): { io: DebugIo[]; devices: DebugDevice[] } {
236
+ const { catalog, config } = hardware;
237
+ const rows = Object.entries(config.io).flatMap(([key, binding]): DebugIo[] => {
238
+ const held = io(key);
239
+ if (!held) return [];
240
+ const address = ioAddress(hardware, binding);
241
+ return [
242
+ {
243
+ path: key,
244
+ ...held,
245
+ direction: address?.startsWith("%Q") ? "output" : "input",
246
+ ...("device" in binding && { device: binding.device, channel: binding.channel }),
247
+ ...(address && { address }),
248
+ ...(binding.inverted && { inverted: true as const }),
249
+ ...(binding.shared && { shared: true as const }),
250
+ },
251
+ ];
252
+ });
253
+ return {
254
+ io: rows,
255
+ devices: catalog.devices.map((device) => {
256
+ const descriptor = catalog.descriptors.find((item) => item.file === device.descriptor);
257
+ const network = config.devices[device.id]?.network;
258
+ const bytes = raw(device.id);
259
+ const status = {
260
+ ...device.statusSymbols,
261
+ ...(hardware.tree &&
262
+ device.modbus && {
263
+ "Modbus error": `${device.id}_Modbus.xError`,
264
+ "Modbus error code": `${device.id}_Modbus.byModbusError`,
265
+ }),
266
+ };
267
+ return {
268
+ id: device.id,
269
+ ...(descriptor && {
270
+ product: descriptor.name,
271
+ vendor: descriptor.vendor,
272
+ productCode: descriptor.productCode,
273
+ }),
274
+ ...(network?.address && {
275
+ network: {
276
+ address: network.address,
277
+ ...(network.rpi && { rpiMs: Number(BigInt(network.rpi.nanoseconds)) / 1e6 }),
278
+ },
279
+ }),
280
+ ...(device.connection && { connection: device.connection.name }),
281
+ assemblies: device.assemblies.map((assembly) => ({
282
+ direction: assembly.direction,
283
+ bytes: assembly.size,
284
+ address: assembly.address,
285
+ ...(bytes[assembly.direction] && { raw: bytes[assembly.direction] }),
286
+ })),
287
+ ...(hardware.tree && {
288
+ health: {
289
+ state: `${device.id}.eState`,
290
+ diagnostic: `${device.id}.xDiagnosticAvailable`,
291
+ message: `${device.id}.sDiagString`,
292
+ },
293
+ }),
294
+ ...(Object.keys(status).length && { status }),
295
+ // Byte and bit expansions of an assembly are covered by its raw bytes.
296
+ channels: device.channels
297
+ .filter((channel) => !channel.parent && !/^(inputs|outputs)\.Byte\d+$/.test(channel.id))
298
+ .map((channel) => ({
299
+ id: channel.id,
300
+ name: channel.name,
301
+ direction: channel.direction,
302
+ type: channel.type,
303
+ offsetBits: channel.offsetBits,
304
+ bits: channel.bits,
305
+ ...(channel.address && { address: channel.address }),
306
+ ...(channel.unit && { unit: channel.unit }),
307
+ ...(channel.description && { description: channel.description }),
308
+ })),
309
+ };
310
+ }),
311
+ };
312
+ }
@@ -8,18 +8,26 @@ import {
8
8
  type Diagnostic,
9
9
  isVerifiedCore,
10
10
  type PlcType,
11
+ telemetryOperands,
11
12
  type SourceSpan,
12
13
  type VerifiedCoreModule,
13
14
  } from "@tsplc/compiler/ir";
14
15
  import { type CodesysOptions, optionsSchema } from "./config.ts";
15
- import { ioLayout } from "@tsplc/typegen/hardware";
16
+ import { ioLayout, ioScalarBits } from "@tsplc/typegen/hardware";
16
17
  import { iecSpelling, isStoragePath, resolveStoragePath, type StorageBinding } from "./io-paths.ts";
17
18
  import { isIecIdentifier } from "./names.ts";
18
19
  import { storageLayout } from "./storage.ts";
19
20
  import { validateHttpLayout, resolveHttpEndpoint, type HttpEndpoint } from "./http.ts";
20
21
  import { accessedStorage, schedulePrograms, taskStorageOwnership } from "./task-access.ts";
21
22
  import { resolvePublication } from "./publication.ts";
22
- import type { Publication } from "@tsplc/config";
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";
23
31
 
24
32
  // Only this planner can admit a target configuration for emission. Cloning a
25
33
  // branded-looking object does not give it membership in this private identity set.
@@ -33,6 +41,21 @@ export interface CodesysPlan {
33
41
  readonly storageBindings: readonly StorageBinding[];
34
42
  readonly publication: Publication;
35
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;
36
59
  }
37
60
  const plans = new WeakSet<object>();
38
61
  export function diagnostic(message: string, span?: SourceSpan): Diagnostic {
@@ -46,6 +69,7 @@ export function planCodesys(
46
69
  core: VerifiedCoreModule,
47
70
  deployment: Deployment,
48
71
  value: unknown,
72
+ project: CodesysProject = { root: process.cwd() },
49
73
  ): { plan?: CodesysPlan; diagnostics: readonly Diagnostic[] } {
50
74
  if (!isVerifiedCore(core))
51
75
  return { diagnostics: [diagnostic("CODESYS requires a verified, normalized core module.")] };
@@ -93,6 +117,14 @@ export function planCodesys(
93
117
  validateTasks(core, deployment, report);
94
118
  validateStorage(core, options, report);
95
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);
96
128
  const { publication, errors } = resolvePublication(core, options.publish);
97
129
  for (const error of errors) report(error);
98
130
 
@@ -105,6 +137,8 @@ export function planCodesys(
105
137
  storageBindings,
106
138
  publication,
107
139
  http: Object.fromEntries(http),
140
+ project,
141
+ ...(telemetry && { telemetry }),
108
142
  [planned]: true as const,
109
143
  });
110
144
  // Parsed options can contain nested engineering settings; detach and freeze the complete plan.
@@ -223,7 +257,8 @@ function validateIo(
223
257
  span,
224
258
  );
225
259
  const size = match[2] === "X" ? 1 : match[2] === "B" ? 8 : match[2] === "W" ? 16 : 32;
226
- if (ioBits(element) !== size) report(`Address size does not match ${name}:${type.id}.`, span);
260
+ const elementBits = element && ioScalarBits(iecSpelling(element, types) ?? "");
261
+ if (elementBits !== size) report(`Address size does not match ${name}:${type.id}.`, span);
227
262
  // CODESYS numbers %IW/%ID by element: %IW12 is bytes 24-25. See verify.py.
228
263
  const unit = size === 1 ? 8n : BigInt(size);
229
264
  const offset = BigInt(match[3]!);
@@ -261,12 +296,6 @@ function nested(left: StorageBinding, right: StorageBinding): boolean {
261
296
  );
262
297
  }
263
298
 
264
- /** Width of one bound element; BOOL is a single bit, numeric scalars their storage width. */
265
- function ioBits(type: PlcType | undefined): number {
266
- if (type?.kind === "bool") return 1;
267
- return type && "bits" in type ? type.bits : 0;
268
- }
269
-
270
299
  function validateTasks(core: VerifiedCoreModule, deployment: Deployment, report: Report): void {
271
300
  const programs = new Map(core.programs.map((program) => [program.name, program]));
272
301
  const assignment = new Map<string, string>();
@@ -412,6 +441,7 @@ function validateConstants(core: VerifiedCoreModule, report: Report): void {
412
441
  Object.values(item.inputs).forEach(constantsInExpression);
413
442
  }
414
443
  if (item.kind === "return" && item.value) constantsInExpression(item.value);
444
+ if (item.kind === "telemetry") telemetryOperands(item).forEach(constantsInExpression);
415
445
  }
416
446
  };
417
447
  core.variables.forEach((variable) => {
@@ -1,6 +1,6 @@
1
1
  import type { Publication } from "@tsplc/config";
2
2
  import type { VerifiedCoreModule } from "@tsplc/compiler/ir";
3
- import { moduleName } from "./storage.ts";
3
+ import { moduleFile, moduleName } from "./storage.ts";
4
4
 
5
5
  const globals = (core: VerifiedCoreModule) =>
6
6
  core.variables.filter((variable) => variable.storage === "module" && variable.exported);
@@ -43,7 +43,7 @@ export const resolvePublication = (
43
43
  );
44
44
  continue;
45
45
  }
46
- if (new Set(candidates.map((variable) => variable.span.file)).size !== 1) {
46
+ if (new Set(candidates.map(moduleFile)).size !== 1) {
47
47
  errors.push(`Ambiguous publication selector ${selector}.`);
48
48
  continue;
49
49
  }