@tsplc/compiler 0.5.6 → 0.5.8

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 (49) hide show
  1. package/dist/bun-runtime.js +139 -30
  2. package/dist/bun-runtime.js.map +8 -7
  3. package/dist/cli.js +24 -9
  4. package/dist/cli.js.map +6 -6
  5. package/dist/codesys.js +3237 -1957
  6. package/dist/codesys.js.map +19 -18
  7. package/dist/index.js +54 -6
  8. package/dist/index.js.map +8 -8
  9. package/dist/ir.js +1645 -1326
  10. package/dist/ir.js.map +13 -12
  11. package/dist/project.js +12 -6
  12. package/dist/project.js.map +4 -4
  13. package/package.json +9 -9
  14. package/src/codesys/debug.ts +17 -2
  15. package/src/codesys/emit.ts +40 -12
  16. package/src/codesys/explain.ts +1465 -0
  17. package/src/codesys/global-lists.ts +21 -9
  18. package/src/codesys/http.ts +125 -71
  19. package/src/codesys/instrumentation.ts +161 -9
  20. package/src/codesys/manifest.ts +29 -12
  21. package/src/codesys/numeric.ts +5 -3
  22. package/src/codesys/plan.ts +22 -6
  23. package/src/codesys/programs.ts +2 -0
  24. package/src/codesys/routines.ts +39 -9
  25. package/src/codesys/st-files.ts +73 -6
  26. package/src/codesys/telemetry.ts +70 -35
  27. package/src/frontend/elaborate/index.ts +16 -1
  28. package/src/frontend/elaborate/storage.ts +56 -1
  29. package/src/frontend/expressions.ts +2 -2
  30. package/src/frontend/intrinsics.ts +1 -2
  31. package/src/frontend/statements.ts +3 -2
  32. package/src/frontend/typescript.ts +3 -0
  33. package/src/ir/conditions.ts +895 -0
  34. package/src/ir/core-model.ts +2 -2
  35. package/src/ir/fold.ts +15 -107
  36. package/src/ir/index.ts +10 -11
  37. package/src/ir/link.ts +1 -0
  38. package/src/ir/model.ts +16 -79
  39. package/src/ir/numeric.ts +5 -41
  40. package/src/ir/ranges.ts +8 -14
  41. package/src/ir/scalars.ts +6 -4
  42. package/src/project/debugger.ts +9 -0
  43. package/src/project/project.ts +6 -0
  44. package/src/project/release.ts +7 -4
  45. package/src/runtime/async.ts +15 -12
  46. package/src/runtime/launch.ts +11 -4
  47. package/src/runtime/runtime.ts +26 -23
  48. package/src/runtime/telemetry.ts +14 -6
  49. package/src/runtime/transport.ts +172 -0
@@ -54,21 +54,34 @@ const globalInitializer = (
54
54
  : targetTypes.declarationInitializer(value, item.type);
55
55
  };
56
56
 
57
+ /**
58
+ * How a variable is published for the build target: an exposure is read-only, and any other
59
+ * published variable is writable by clients. Unpublished variables have no access.
60
+ */
61
+ export const publishedAccess = (
62
+ plan: CodesysPlan,
63
+ ): ((variable: Variable) => "read" | "readwrite" | undefined) => {
64
+ const published = new Set(plan.publication[plan.options.buildTarget]);
65
+ return (variable) => {
66
+ if (!published.has(variable.id)) {
67
+ return undefined;
68
+ }
69
+ return variable.exposure ? "read" : "readwrite";
70
+ };
71
+ };
72
+
57
73
  /** The global lists of module storage; each variable's global symbol goes into `symbols.references`. */
58
74
  export function emitGlobalLists(
59
75
  plan: CodesysPlan,
60
76
  symbols: CodesysSymbols,
61
77
  ): { objects: GeneratedObject[]; mappings: SourceMapping[] } {
62
- const { options } = plan;
63
78
  const { globals, references, targetTypes } = symbols;
64
79
  const objects: GeneratedObject[] = [];
65
80
  const mappings: SourceMapping[] = [];
81
+ const access = publishedAccess(plan);
66
82
  for (const group of globals) {
67
83
  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
- );
84
+ const publish = group.variables.some((variable) => access(variable));
72
85
  const lines = [
73
86
  ...(publish ? ["{attribute 'linkalways'}"] : []),
74
87
  "{attribute 'qualified_only'}",
@@ -78,10 +91,9 @@ export function emitGlobalLists(
78
91
  for (const item of section.variables) {
79
92
  const field = required(fields.get(item.id));
80
93
  references.set(item.id, `${name}.${field}`);
81
- if (published.has(item.id)) {
82
- lines.push(
83
- ` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`,
84
- );
94
+ const symbol = access(item);
95
+ if (symbol) {
96
+ lines.push(` {attribute 'symbol' := '${symbol}'}`);
85
97
  }
86
98
  mappings.push({
87
99
  path: `${name}.st`,
@@ -1,6 +1,7 @@
1
1
  // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
2
  import {
3
3
  type CoreFunctionBlock,
4
+ type FunctionBlock,
4
5
  type GeneratedObject,
5
6
  httpErrors,
6
7
  jobError,
@@ -338,23 +339,88 @@ IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** res
338
339
  return { port, requestCode, decodeResponse, inputs, outputs };
339
340
  };
340
341
 
341
- /** An OPC UA service block: it exchanges its request and reply through a slot of `rpcGlobal`. */
342
- const opcuaServiceBlock = (
343
- block: CoreFunctionBlock,
344
- name: string,
345
- { port, requestCode, decodeResponse, inputs, outputs }: ServiceCodecs,
346
- endpoint: HttpEndpoint,
347
- rpcGlobal: string,
348
- ): GeneratedObject => {
342
+ /** A slot of an OPC UA client: the request and reply strings the server exchanges through it. */
343
+ export interface RpcChannel {
344
+ path: string;
345
+ request: string;
346
+ requestId: string;
347
+ reply: string;
348
+ replyId: string;
349
+ epoch: string;
350
+ }
351
+
352
+ /**
353
+ * The global list an OPC UA client's calls to `path` go through, and its slots as channels for the
354
+ * server's gateway. Requests are read-only to the gateway; replies and connection epochs it writes.
355
+ */
356
+ export const rpcSlots = (
357
+ symbols: CodesysSymbols,
358
+ id: string,
359
+ owner: string,
360
+ path: string,
361
+ ): { list: GeneratedObject; channels: RpcChannel[] } => {
362
+ const name = symbols.names.allocateObject("GVL", `TsplcRpc_${owner}`);
363
+ return {
364
+ list: {
365
+ id: `${id}:rpc`,
366
+ kind: "globalList",
367
+ name,
368
+ declaration: `{attribute 'qualified_only'}
369
+ VAR_GLOBAL
370
+ {attribute 'symbol' := 'read'} requests:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
371
+ {attribute 'symbol' := 'read'} requestIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
372
+ {attribute 'symbol' := 'readwrite'} replyIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
373
+ {attribute 'symbol' := 'readwrite'} replies:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
374
+ {attribute 'symbol' := 'readwrite'} epochs:ARRAY[1..${opcuaServiceCapacity}] OF STRING(32);
375
+ inUse:ARRAY[1..${opcuaServiceCapacity}] OF __XWORD;
376
+ sequence:ARRAY[1..${opcuaServiceCapacity}] OF UDINT;
377
+ END_VAR`,
378
+ },
379
+ channels: Array.from({ length: opcuaServiceCapacity }, (_, index) => ({
380
+ path,
381
+ request: `${name}.requests[${index + 1}]`,
382
+ reply: `${name}.replies[${index + 1}]`,
383
+ requestId: `${name}.requestIds[${index + 1}]`,
384
+ replyId: `${name}.replyIds[${index + 1}]`,
385
+ epoch: `${name}.epochs[${index + 1}]`,
386
+ })),
387
+ };
388
+ };
389
+
390
+ /**
391
+ * A client block that exchanges what `body` appends to `payload` and its reply through a slot of
392
+ * `rpcGlobal`, as `nativeHttp` does over HTTP. A reply's status is 0 when the server's handler
393
+ * succeeded, 4 when it refused the request as an HTTP 4xx would, reported as HTTP 400, and
394
+ * anything else a network error. On success `decode` runs over the reply's body in `payload`.
395
+ */
396
+ export const opcuaClient = ({
397
+ id,
398
+ name,
399
+ ports,
400
+ port,
401
+ timeoutMs,
402
+ rpcGlobal,
403
+ body,
404
+ decode,
405
+ }: {
406
+ id: string;
407
+ name: string;
408
+ /** Its input and output declarations, with `start`, `cancel`, `busy`, `done` and `error`. */
409
+ ports: string;
410
+ port: (label: string) => string;
411
+ timeoutMs: number;
412
+ rpcGlobal: string;
413
+ body: string;
414
+ decode: string;
415
+ }): GeneratedObject => {
349
416
  const channel = (field: string, index = "slotIndex") =>
350
417
  `${rpcGlobal}.${field}[${index}]`;
351
418
  return {
352
- id: block.id,
419
+ id,
353
420
  kind: "functionBlock",
354
421
  name,
355
422
  declaration: `FUNCTION_BLOCK ${name}
356
- VAR_INPUT ${inputs} END_VAR
357
- VAR_OUTPUT ${outputs} END_VAR
423
+ ${ports}
358
424
  VAR
359
425
  timeout:TON;stage:UINT;slotIndex:UINT;candidate:UINT;
360
426
  identity:STRING(64);epoch:STRING(32);prefix:STRING(80);
@@ -380,7 +446,7 @@ IF stage=0 THEN
380
446
  ELSE
381
447
  epoch:=${channel("epochs")};identity:=CONCAT(CONCAT(epoch,':'),UDINT_TO_STRING(${channel("sequence")}));
382
448
  prefix:=CONCAT(identity,'|');payload:='';malformed:=FALSE;
383
- Append('{');${requestCode}Append('}');
449
+ ${body}
384
450
  IF malformed THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
385
451
  ELSIF ByteLength(payload)+LEN(prefix)>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
386
452
  ELSE
@@ -391,18 +457,20 @@ IF stage=0 THEN
391
457
  END_IF;
392
458
  END_IF;
393
459
  END_IF;
394
- timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
460
+ timeout(IN:=stage<90,PT:=T#${timeoutMs}ms);
395
461
  IF timeout.Q THEN ${port("error")}:=${jobError.timeout};stage:=90;END_IF;
396
462
  IF stage=1 THEN
397
463
  IF ${channel("epochs")}<>epoch THEN ${port("error")}:=${jobError.network};stage:=90;
398
464
  ELSIF ${channel("replyIds")}=identity AND_THEN LEFT(${channel("replies")},LEN(prefix))=prefix THEN
399
465
  payload:='';cursor:=LEN(prefix);
400
466
  IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=${jobError.malformedResponse};
401
- ELSIF ${channel("replies")}[cursor]<>48 OR ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=${jobError.network};
467
+ ELSIF ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=${jobError.network};
468
+ ELSIF ${channel("replies")}[cursor]=52 THEN ${port("error")}:=${httpErrors.base + 400};
469
+ ELSIF ${channel("replies")}[cursor]<>48 THEN ${port("error")}:=${jobError.network};
402
470
  ELSE
403
471
  FOR candidate:=cursor+2 TO ByteLength(${channel("replies")})-1 DO payload[candidate-cursor-2]:=${channel("replies")}[candidate];END_FOR;
404
472
  payload[ByteLength(${channel("replies")})-cursor-2]:=0;
405
- ${decodeResponse}
473
+ ${decode}
406
474
  END_IF;
407
475
  stage:=90;
408
476
  END_IF;
@@ -877,15 +945,16 @@ IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberVal
877
945
  );
878
946
  };
879
947
 
880
- /** A slot of an OPC UA service: the request and reply strings the server exchanges through it. */
881
- export interface RpcChannel {
882
- path: string;
883
- request: string;
884
- requestId: string;
885
- reply: string;
886
- replyId: string;
887
- epoch: string;
888
- }
948
+ type ServiceRuntime = Extract<
949
+ NonNullable<FunctionBlock["runtime"]>,
950
+ { kind: "http" | "rpc" }
951
+ >;
952
+
953
+ /** A block that calls a service: its body is the request state machine `emitServiceBlock` writes. */
954
+ export const serviceBlock = <Block extends Pick<FunctionBlock, "runtime">>(
955
+ block: Block,
956
+ ): block is Block & { runtime: ServiceRuntime } =>
957
+ block.runtime?.kind === "http" || block.runtime?.kind === "rpc";
889
958
 
890
959
  /** A service-call block: its HTTP or OPC UA client, the client's methods and, over OPC UA, its slots' global list. */
891
960
  export function emitServiceBlock(
@@ -893,43 +962,7 @@ export function emitServiceBlock(
893
962
  networkName: string | undefined,
894
963
  fn: CoreFunctionBlock,
895
964
  ): { objects: GeneratedObject[]; rpcChannels: RpcChannel[] } {
896
- const objects: GeneratedObject[] = [];
897
- const rpcChannels: RpcChannel[] = [];
898
965
  const endpoint = required(plan.http[fn.id]);
899
- const rpcGlobal =
900
- endpoint.transport === "opcua"
901
- ? symbols.names.allocateObject(
902
- "GVL",
903
- `TsplcRpc_${required(symbols.blockNames.get(fn.id))}`,
904
- )
905
- : undefined;
906
- if (rpcGlobal) {
907
- objects.push({
908
- id: `${fn.id}:rpc`,
909
- kind: "globalList",
910
- name: rpcGlobal,
911
- declaration: `{attribute 'qualified_only'}
912
- VAR_GLOBAL
913
- {attribute 'symbol' := 'read'} requests:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
914
- {attribute 'symbol' := 'read'} requestIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
915
- {attribute 'symbol' := 'readwrite'} replyIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
916
- {attribute 'symbol' := 'readwrite'} replies:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
917
- {attribute 'symbol' := 'readwrite'} epochs:ARRAY[1..${opcuaServiceCapacity}] OF STRING(32);
918
- inUse:ARRAY[1..${opcuaServiceCapacity}] OF __XWORD;
919
- sequence:ARRAY[1..${opcuaServiceCapacity}] OF UDINT;
920
- END_VAR`,
921
- });
922
- for (let slot = 1; slot <= opcuaServiceCapacity; slot++) {
923
- rpcChannels.push({
924
- path: endpoint.path,
925
- request: `${rpcGlobal}.requests[${slot}]`,
926
- reply: `${rpcGlobal}.replies[${slot}]`,
927
- requestId: `${rpcGlobal}.requestIds[${slot}]`,
928
- replyId: `${rpcGlobal}.replyIds[${slot}]`,
929
- epoch: `${rpcGlobal}.epochs[${slot}]`,
930
- });
931
- }
932
- }
933
966
  const name = required(symbols.blockNames.get(fn.id));
934
967
  const codecs = serviceCodecs(
935
968
  fn,
@@ -937,10 +970,34 @@ END_VAR`,
937
970
  symbols.typeMap,
938
971
  symbols.targetTypes,
939
972
  );
973
+ const methods = [
974
+ ...httpMethods(fn.id, endpoint.transport),
975
+ ...httpCertificateVerifier(fn.id, name, endpoint),
976
+ ];
977
+ if (endpoint.transport === "opcua") {
978
+ const slots = rpcSlots(symbols, fn.id, name, endpoint.path);
979
+ return {
980
+ objects: [
981
+ slots.list,
982
+ opcuaClient({
983
+ id: fn.id,
984
+ name,
985
+ ports: `VAR_INPUT ${codecs.inputs} END_VAR\nVAR_OUTPUT ${codecs.outputs} END_VAR`,
986
+ port: codecs.port,
987
+ timeoutMs: endpoint.timeoutMs,
988
+ rpcGlobal: slots.list.name,
989
+ body: `Append('{');${codecs.requestCode}Append('}');`,
990
+ decode: codecs.decodeResponse,
991
+ }),
992
+ ...methods,
993
+ ],
994
+ rpcChannels: slots.channels,
995
+ };
996
+ }
940
997
  const requestFields = instrumentation.fields.get(fn.id);
941
- const [generated, ...lifecycle] = rpcGlobal
942
- ? [opcuaServiceBlock(fn, name, codecs, endpoint, rpcGlobal)]
943
- : httpServiceBlock(
998
+ return {
999
+ objects: [
1000
+ ...httpServiceBlock(
944
1001
  fn,
945
1002
  name,
946
1003
  codecs,
@@ -949,14 +1006,11 @@ END_VAR`,
949
1006
  requestFields?.job && requestFields.sequence
950
1007
  ? { job: requestFields.job, sequence: requestFields.sequence }
951
1008
  : undefined,
952
- );
953
- objects.push(
954
- generated,
955
- ...lifecycle,
956
- ...httpMethods(generated.id, endpoint.transport),
957
- ...httpCertificateVerifier(generated.id, generated.name, endpoint),
958
- );
959
- return { objects, rpcChannels };
1009
+ ),
1010
+ ...methods,
1011
+ ],
1012
+ rpcChannels: [],
1013
+ };
960
1014
  }
961
1015
 
962
1016
  /** `GVL_TsplcNetwork`, the Net Base Services task every HTTP client runs on, when one does. */
@@ -6,17 +6,30 @@ import type {
6
6
  CoreStatement,
7
7
  GeneratedObject,
8
8
  SourceSpan,
9
+ VerifiedCoreModule,
9
10
  } from "@tsplc/compiler/ir";
10
- import type { DebugManifest } from "@tsplc/debug/manifest";
11
+ import type { ResolvedDebugConfig } from "@tsplc/config";
12
+ import type { DebugManifest, DebugType } from "@tsplc/debug/manifest";
13
+ import { createPaths, type PathManifest } from "@tsplc/debug/paths";
11
14
  import { elementaryType, integerRange } from "@tsplc/iec";
12
- import { DebugAnalysis, type InstancePath, type Operand } from "./debug";
15
+ import {
16
+ DebugAnalysis,
17
+ type InstancePath,
18
+ type Operand,
19
+ storagePath,
20
+ } from "./debug";
13
21
  import {
14
22
  expressionText,
15
23
  placeText,
16
24
  type StorageScope,
17
25
  storageName,
18
26
  } from "./expressions";
19
- import { isStoragePath, resolveStoragePath } from "./io-paths";
27
+ import { type RpcChannel, rpcSlots } from "./http";
28
+ import {
29
+ isStoragePath,
30
+ resolveStoragePath,
31
+ type StorageBinding,
32
+ } from "./io-paths";
20
33
  import { ioAddress } from "./manifest";
21
34
  import { Names } from "./names";
22
35
  import type { CodesysPlan } from "./plan";
@@ -24,6 +37,97 @@ import { type CodesysSymbols, type EmissionContext, required } from "./symbols";
24
37
  import { telemetryClient, telemetryObjects } from "./telemetry";
25
38
  import { stStringLiteral } from "./types";
26
39
 
40
+ /**
41
+ * The most storage paths `debug.writers.paths` may match. Each is a slot in `GVL_TsplcDebug` and
42
+ * a store on every statement that writes it.
43
+ */
44
+ export const maxWriterPaths = 256;
45
+
46
+ /** Module storage as the debugger's paths name it, for expanding `debug.writers.paths`. */
47
+ const storageShape = (core: VerifiedCoreModule): PathManifest => ({
48
+ roots: core.variables.flatMap((variable) => {
49
+ const path =
50
+ variable.storage === "module" ? storagePath(variable) : undefined;
51
+ return path
52
+ ? [{ path, target: "", type: variable.type, readable: true }]
53
+ : [];
54
+ }),
55
+ io: [],
56
+ constants: [],
57
+ types: Object.fromEntries(
58
+ core.types.flatMap((type): [string, DebugType][] => {
59
+ switch (type.kind) {
60
+ case "record":
61
+ return [
62
+ [
63
+ type.id,
64
+ {
65
+ kind: "record",
66
+ name: type.id,
67
+ fields: type.fields.map((field) => ({
68
+ name: field.name,
69
+ target: field.name,
70
+ type: field.type,
71
+ })),
72
+ },
73
+ ],
74
+ ];
75
+ case "array":
76
+ return [
77
+ [
78
+ type.id,
79
+ {
80
+ kind: "array",
81
+ element: type.element,
82
+ length: type.length,
83
+ lower: type.lowerBound,
84
+ },
85
+ ],
86
+ ];
87
+ default:
88
+ return [];
89
+ }
90
+ }),
91
+ ),
92
+ });
93
+
94
+ /**
95
+ * The module storage paths `debug.writers.paths` matches. A pattern that names a block's field or
96
+ * anything else that isn't module storage is reported, as is matching more than `maxWriterPaths`.
97
+ */
98
+ export function writerPaths(
99
+ core: VerifiedCoreModule,
100
+ settings: ResolvedDebugConfig | undefined,
101
+ report: (message: string) => void,
102
+ ): StorageBinding[] {
103
+ const writers = settings?.writers;
104
+ if (typeof writers !== "object") {
105
+ return [];
106
+ }
107
+ const expanded = (() => {
108
+ try {
109
+ return createPaths(storageShape(core)).expand(
110
+ writers.paths,
111
+ maxWriterPaths,
112
+ );
113
+ } catch (error) {
114
+ if (error instanceof RangeError) {
115
+ report(`debug.writers.paths match more than ${maxWriterPaths} values.`);
116
+ return [];
117
+ }
118
+ throw error;
119
+ }
120
+ })();
121
+ return expanded.flatMap((path) => {
122
+ const resolved = resolveStoragePath(core, path);
123
+ if ("error" in resolved) {
124
+ report(`debug.writers.paths: ${resolved.error}`);
125
+ return [];
126
+ }
127
+ return [resolved];
128
+ });
129
+ }
130
+
27
131
  /**
28
132
  * The debugger's and telemetry's names in the program: `GVL_TsplcDebug` and its fields, each
29
133
  * task's ring, and the instrumentation fields of each block.
@@ -58,6 +162,11 @@ export function planInstrumentation(
58
162
  )
59
163
  ).map(({ key, root, segments }) => ({ key, root, segments })),
60
164
  ];
165
+ for (const { key, root, segments } of plan.writerPaths) {
166
+ if (!outputs.some((output) => output.key === key)) {
167
+ outputs.push({ key, root, segments });
168
+ }
169
+ }
61
170
  const analysis = new DebugAnalysis(core, plan.deployment, settings, outputs);
62
171
  /** `GVL_TsplcDebug`, and the names of its fields. */
63
172
  const global = symbols.names.allocateObject("GVL", "TsplcDebug");
@@ -87,7 +196,12 @@ export function planInstrumentation(
87
196
  ? {
88
197
  writer: symbols.names.allocateObject("FB", "TsplcTelemetry"),
89
198
  record: symbols.names.allocateObject("ST", "TsplcRecord"),
90
- client: symbols.names.allocateObject("FB", "TsplcTelemetryHttp"),
199
+ client: symbols.names.allocateObject(
200
+ "FB",
201
+ plan.http[telemetryClient]?.transport === "opcua"
202
+ ? "TsplcTelemetryOpcUa"
203
+ : "TsplcTelemetryHttp",
204
+ ),
91
205
  }
92
206
  : undefined;
93
207
  /** Job instances in manifest order, and the job id each single-instance declaration passes to its service calls. */
@@ -130,11 +244,28 @@ export function planInstrumentation(
130
244
  );
131
245
  }
132
246
  }
247
+ // Without a ring, a task whose writers the debugger follows records the clock itself.
248
+ const scanClocks = new Map<string, string>(
249
+ plan.writerPaths.length
250
+ ? plan.deployment.tasks.flatMap((task) =>
251
+ rings.has(task.name)
252
+ ? []
253
+ : [
254
+ [
255
+ task.name,
256
+ `${global}.${names.allocate(`scanClock_${task.name}`)}`,
257
+ ],
258
+ ],
259
+ )
260
+ : [],
261
+ );
133
262
  return {
134
263
  analysis,
135
264
  global,
136
265
  slots,
137
266
  rings,
267
+ /** Each task's clock in `GVL_TsplcDebug`, by task, when it has no ring that reads the clock. */
268
+ scanClocks,
138
269
  telemetryNames,
139
270
  jobs,
140
271
  jobIds,
@@ -157,26 +288,44 @@ interface BlockInstrumentation {
157
288
  /** Stands for the build id in the sender until the id, a hash over everything else, is known. */
158
289
  const buildPlaceholder = "<build>";
159
290
 
291
+ /** The telemetry sender and its client; over OPC UA also the client's slots and their channels. */
160
292
  export function emitTelemetry(
161
293
  plan: CodesysPlan,
162
294
  symbols: CodesysSymbols,
163
295
  instrumentation: Instrumentation,
164
296
  networkName: string | undefined,
165
- ): GeneratedObject[] {
297
+ ): { objects: GeneratedObject[]; rpcChannels: RpcChannel[] } {
166
298
  const { telemetry } = plan;
167
299
  const names = instrumentation.telemetryNames;
168
300
  if (!telemetry || !names) {
169
- return [];
301
+ return { objects: [], rpcChannels: [] };
170
302
  }
171
- return telemetryObjects({
303
+ const endpoint = required(plan.http[telemetryClient]);
304
+ const slots =
305
+ endpoint.transport === "opcua"
306
+ ? rpcSlots(symbols, telemetryClient, names.client, endpoint.path)
307
+ : undefined;
308
+ const objects = telemetryObjects({
172
309
  plan: telemetry,
173
310
  names,
174
311
  target: symbols.targetTypes,
175
- endpoint: required(plan.http[telemetryClient]),
176
- network: `${required(networkName)}.network`,
312
+ transport: slots
313
+ ? {
314
+ kind: "opcua",
315
+ timeoutMs: endpoint.timeoutMs,
316
+ rpcGlobal: slots.list.name,
317
+ }
318
+ : {
319
+ kind: "http",
320
+ endpoint,
321
+ network: `${required(networkName)}.network`,
322
+ },
177
323
  build: buildPlaceholder,
178
324
  types: symbols.typeMap,
179
325
  });
326
+ return slots
327
+ ? { objects: [slots.list, ...objects], rpcChannels: slots.channels }
328
+ : { objects, rpcChannels: [] };
180
329
  }
181
330
 
182
331
  /**
@@ -207,6 +356,9 @@ export function emitDebugGlobal(
207
356
  }
208
357
 
209
358
  const fields = [`buildId : STRING(16) := '${id}'`];
359
+ for (const target of instrumentation.scanClocks.values()) {
360
+ fields.push(`${target.slice(instrumentation.global.length + 1)} : DINT`);
361
+ }
210
362
  for (const [task, field] of instrumentation.rings) {
211
363
  fields.push(
212
364
  `${field} : ${required(instrumentation.telemetryNames).writer} := (task := '${task}')`,
@@ -34,7 +34,7 @@ import { serviceOfPath } from "@tsplc/server";
34
34
  import type { HardwareCatalog } from "@tsplc/typegen/hardware";
35
35
  import { version } from "../../package.json";
36
36
  import { type InstancePath, storagePath } from "./debug";
37
- import { Sources } from "./sources";
37
+ import type { Sources } from "./sources";
38
38
  import {
39
39
  type CodesysSymbols,
40
40
  type EmissionContext,
@@ -168,7 +168,7 @@ function debugTypes(
168
168
  }
169
169
 
170
170
  /** A folded constant's JSON value; integers beyond doubles' exact range stay strings. */
171
- const constantValue = (value: Constant): unknown => {
171
+ export const constantValue = (value: Constant): unknown => {
172
172
  switch (value.kind) {
173
173
  case "integer":
174
174
  return Number.isSafeInteger(Number(value.value))
@@ -440,11 +440,13 @@ const routineTarget = (
440
440
  export function debugManifest(
441
441
  context: EmissionContext,
442
442
  ioTarget: (key: string) => { target: string; type: string } | undefined,
443
+ sources: Sources,
444
+ /** Filled with the id of each function the manifest lists, by routine. */
445
+ functionIds: Map<string, number>,
443
446
  ): DebugManifest {
444
447
  const { plan, symbols, instrumentation } = context;
445
448
  const { core, project, deployment, options } = plan;
446
449
  const settings = project.debug;
447
- const sources = new Sources(project.root);
448
450
  const global = (field: string) => `${instrumentation.global}.${field}`;
449
451
 
450
452
  const declaredFunctions = new Map<
@@ -452,18 +454,24 @@ export function debugManifest(
452
454
  { id: number; range: SourceRange }
453
455
  >();
454
456
  const routines = new Map(core.functions.map((fn) => [fn.id, fn]));
457
+ const emittedBlocks = new Map(core.blocks.map((block) => [block.id, block]));
455
458
  // A merged instance's own locals are not in the program's variables any more.
456
459
  const variables = new Map([
457
460
  ...instrumentation.analysis.variables,
458
- ...plan.specialized.flatMap((fn) =>
461
+ ...plan.specialized.functions.flatMap((fn) =>
459
462
  [...fn.parameters, ...fn.locals].map(
460
463
  (variable) => [variable.id, variable] as const,
461
464
  ),
462
465
  ),
466
+ ...plan.specialized.blocks.flatMap((block) =>
467
+ block.locals.map((variable) => [variable.id, variable] as const),
468
+ ),
463
469
  ]);
464
470
  const functions = [
465
- ...plan.specialized,
466
- ...core.blocks.filter((block) => !block.standard && !block.runtime),
471
+ ...plan.specialized.functions,
472
+ ...plan.specialized.blocks.filter(
473
+ (block) => !block.standard && !block.runtime,
474
+ ),
467
475
  ].flatMap((routine): DebugFunction[] => {
468
476
  const block = "inputs" in routine ? routine : undefined;
469
477
  const fn = "parameters" in routine ? routine : undefined;
@@ -475,12 +483,13 @@ export function debugManifest(
475
483
  // routine that only returned a constant was replaced by it, and has nothing to describe.
476
484
  const runs = fn
477
485
  ? routines.get(plan.sharedRoutines.get(fn.id) ?? fn.id)
478
- : routine;
486
+ : emittedBlocks.get(routine.id);
479
487
  if (!runs) {
480
488
  return [];
481
489
  }
482
490
  const id = declaredFunctions.size;
483
491
  declaredFunctions.set(routine.id, { id, range: declaration });
492
+ functionIds.set(routine.id, id);
484
493
  const task = instrumentation.analysis.tasks.get(runs.id);
485
494
  const origin = fn?.origin;
486
495
  return [
@@ -657,11 +666,19 @@ export function debugManifest(
657
666
  jobs,
658
667
  events,
659
668
  writers,
660
- tasks: deployment.tasks.map((task) => ({
661
- name: task.name,
662
- intervalMs: Number(task.intervalNanoseconds) / 1e6,
663
- priority: task.priority,
664
- })),
669
+ tasks: deployment.tasks.map((task) => {
670
+ // The task's ring sender reads the clock at the start of its first program.
671
+ const ring = instrumentation.rings.get(task.name);
672
+ const clock = ring
673
+ ? global(`${ring}.now`)
674
+ : instrumentation.scanClocks.get(task.name);
675
+ return {
676
+ name: task.name,
677
+ intervalMs: Number(task.intervalNanoseconds) / 1e6,
678
+ priority: task.priority,
679
+ ...(clock && { clock }),
680
+ };
681
+ }),
665
682
  errors: jobErrors,
666
683
  };
667
684
  }
@@ -2,18 +2,20 @@ import {
2
2
  type Constant,
3
3
  type CoreExpression,
4
4
  type CoreStatement,
5
- type ElementaryFunction,
6
- floatMaximum,
7
5
  type GeneratedObject,
8
6
  integerRange,
9
7
  integerType,
10
- isElementary,
11
8
  nestedBodies,
12
9
  type PlcType,
13
10
  pathIndexes,
14
11
  statementExpressions,
15
12
  subexpressions,
16
13
  } from "@tsplc/compiler/ir";
14
+ import {
15
+ type ElementaryFunction,
16
+ floatMaximum,
17
+ isElementary,
18
+ } from "@tsplc/iec/arithmetic";
17
19
 
18
20
  /** The Structured Text function each elementary function is. */
19
21
  const elementaryNames: Readonly<Record<ElementaryFunction, string>> = {