@tsplc/compiler 0.2.13 → 0.2.16

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 +205 -36
  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 +74 -15
  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
@@ -10,13 +10,27 @@ import type {
10
10
  SourceSpan,
11
11
  Variable,
12
12
  } from "@tsplc/compiler/ir";
13
- import { defaultValue, instancedBlock, standardBlocks } from "@tsplc/compiler/ir";
13
+ import {
14
+ defaultValue,
15
+ instancedBlock,
16
+ jobErrors,
17
+ standardBlocks,
18
+ telemetryOperands,
19
+ } from "@tsplc/compiler/ir";
20
+ import { createHash } from "node:crypto";
21
+ import type { DebugEventSite, DebugFunction, DebugJob, DebugManifest } from "@tsplc/debug/manifest";
22
+ import { serviceOfPath } from "@tsplc/server";
23
+ import { DebugAnalysis, type InstancePath, type Operand, storagePath } from "./debug.ts";
24
+ import { Sources, debugConstants, debugHardware, debugTypes, ioAddress } from "./manifest.ts";
25
+ import { isStoragePath, resolveStoragePath, type StorageBinding } from "./io-paths.ts";
26
+ import { version } from "../../package.json";
14
27
  import { planGlobalNames } from "./global-names.ts";
15
28
  import { Names } from "./names.ts";
16
29
  import { NumericLowering } from "./numeric.ts";
17
30
  import { type CodesysPlan, diagnostic, isCodesysPlan } from "./plan.ts";
18
31
  import { accessedStorage } from "./task-access.ts";
19
32
  import { emitHttp, httpMethods, httpCertificateVerifier, opcuaServiceCapacity } from "./http.ts";
33
+ import { callParameters, generated, telemetryClient, telemetryObjects } from "./telemetry.ts";
20
34
  import type { Publication } from "@tsplc/config";
21
35
 
22
36
  export interface SourceMapping {
@@ -25,6 +39,9 @@ export interface SourceMapping {
25
39
  span: SourceSpan;
26
40
  }
27
41
 
42
+ /** Stands for the build id in the sender until the id, a hash over everything else, is known. */
43
+ const buildPlaceholder = "<build>";
44
+
28
45
  // All symbol relationships were checked by normalization and planning. Failure
29
46
  // here is an emitter invariant violation, rather than a recoverable source error.
30
47
  function required<T>(value: T | undefined): T {
@@ -38,6 +55,8 @@ type CodesysBundle = EmitResult & {
38
55
  mappings: readonly SourceMapping[];
39
56
  ioSymbols: Readonly<Record<string, string>>;
40
57
  publication: Publication;
58
+ /** The debugger's view of this build; its id is also published as `build.target`. */
59
+ debug?: DebugManifest;
41
60
  };
42
61
 
43
62
  export function emitCodesys(plan: CodesysPlan): CodesysBundle {
@@ -97,6 +116,35 @@ class CodesysEmitter {
97
116
  private readonly numeric: NumericLowering;
98
117
  private readonly globals;
99
118
  private readonly retainedVariables;
119
+ private readonly debug: DebugAnalysis;
120
+ /** `GVL_TsplcDebug`, and the names of its fields. */
121
+ private readonly debugGlobal: string;
122
+ private readonly debugNames = new Names();
123
+ /** Each task's ring and sender in `GVL_TsplcDebug`. */
124
+ private readonly rings = new Map<string, string>();
125
+ private readonly debugSlots: { decisions: string; writers: string };
126
+ private readonly telemetryNames: { writer: string; record: string; client: string } | undefined;
127
+ /** Instrumentation fields of each block: its job state and the requesting job's id. */
128
+ private readonly debugFields = new Map<
129
+ string,
130
+ {
131
+ busy?: string;
132
+ /** The method that records the job starting and finishing, allocated with `busy`. */
133
+ track?: string;
134
+ step?: string;
135
+ startedAt?: string;
136
+ job?: string;
137
+ sequence?: string;
138
+ }
139
+ >();
140
+ /** Job instances in manifest order, and the job id each single-instance declaration passes to its service calls. */
141
+ private readonly jobs: { block: CoreFunctionBlock; path: InstancePath }[];
142
+ private readonly jobIds = new Map<string, number>();
143
+ /** Raw bytes over each assembly, in `GVL_TsplcDebug`, by device. */
144
+ private readonly devices = new Map<
145
+ string,
146
+ Partial<Record<"input" | "output", { field: string; address: string; bytes: number }>>
147
+ >();
100
148
 
101
149
  constructor(private readonly plan: CodesysPlan) {
102
150
  const { core, options } = plan;
@@ -120,6 +168,69 @@ class CodesysEmitter {
120
168
  this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
121
169
  this.numeric = new NumericLowering(this.typeMap, (label) => this.names.allocate(label));
122
170
  this.objects.push(...this.targetTypes.objects);
171
+
172
+ const settings = plan.project.debug;
173
+ // A simulation build binds no fieldbus I/O, but its outputs are still the configured ones.
174
+ const hardware = plan.project.hardware;
175
+ const outputs = [
176
+ ...core.variables
177
+ .filter((variable) => variable.storage === "output")
178
+ .map((root) => ({ key: root.name, root, segments: [] })),
179
+ ...(hardware
180
+ ? Object.entries(hardware.config.io).flatMap(([key, binding]) => {
181
+ if (!isStoragePath(key) || !ioAddress(hardware, binding)?.startsWith("%Q")) return [];
182
+ const resolved = resolveStoragePath(core, key);
183
+ return "error" in resolved ? [] : [resolved];
184
+ })
185
+ : plan.storageBindings.filter(({ key }) =>
186
+ required(options.io[key]).address.startsWith("%Q"),
187
+ )
188
+ ).map(({ key, root, segments }) => ({ key, root, segments })),
189
+ ];
190
+ this.debug = new DebugAnalysis(core, plan.deployment, settings, outputs);
191
+ this.debugGlobal = this.names.allocateObject("GVL", "TsplcDebug");
192
+ this.debugNames.allocate("buildId");
193
+ this.debugSlots = {
194
+ decisions: this.debugNames.allocate("decisions"),
195
+ writers: this.debugNames.allocate("writers"),
196
+ };
197
+ const telemetry = plan.telemetry;
198
+ if (telemetry) {
199
+ const tasks = new Set([
200
+ ...[...telemetry.calls.values(), ...telemetry.failures.values()].map((site) => site.task),
201
+ ...this.debug.events.map((site) => site.task),
202
+ ]);
203
+ for (const task of plan.deployment.tasks)
204
+ if (tasks.has(task.name)) this.rings.set(task.name, this.debugNames.allocate(task.name));
205
+ if (this.rings.size)
206
+ this.telemetryNames = {
207
+ writer: this.names.allocateObject("FB", "TsplcTelemetry"),
208
+ record: this.names.allocateObject("ST", "TsplcRecord"),
209
+ client: this.names.allocateObject("FB", "TsplcTelemetryHttp"),
210
+ };
211
+ }
212
+ this.jobs = core.blocks
213
+ .filter((block) => block.job)
214
+ .flatMap((block) => this.debug.instances.get(block.id)!.map((path) => ({ block, path })));
215
+ this.jobs.forEach(({ path }, index) => {
216
+ const declared = path.at(-1)!.variable;
217
+ if (this.debug.owningPath(declared) === path) this.jobIds.set(declared.id, index + 1);
218
+ });
219
+ if (settings && hardware?.tree)
220
+ for (const device of hardware.catalog.devices)
221
+ this.devices.set(
222
+ device.id,
223
+ Object.fromEntries(
224
+ device.assemblies.map((assembly) => [
225
+ assembly.direction,
226
+ {
227
+ field: this.debugNames.allocate(`${device.id}_${assembly.direction}s`),
228
+ address: assembly.address,
229
+ bytes: assembly.size,
230
+ },
231
+ ]),
232
+ ),
233
+ );
123
234
  }
124
235
 
125
236
  emit(): CodesysBundle {
@@ -155,10 +266,12 @@ END_VAR
155
266
  this.objects.push(...this.numeric.objects);
156
267
  this.allocateBlockFields();
157
268
 
269
+ this.emitTelemetry();
158
270
  const routines = [...core.functions, ...core.blocks.filter((block) => !block.standard)];
159
271
  for (const fn of routines) this.allocateRoutineScope(fn);
160
272
  for (const fn of routines) this.emitRoutine(fn);
161
273
  for (const program of core.programs) this.emitProgram(program);
274
+ const debug = this.emitDebugGlobal();
162
275
 
163
276
  const { objects, mappings } = this;
164
277
  const paths = new Map<string, string>();
@@ -247,7 +360,16 @@ END_VAR
247
360
  content: `// Generated explicit read-only machine interfaces. Do not edit.\nexport const machines=${JSON.stringify(exposures, null, 2)} as const;\nexport const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as const;\n`,
248
361
  },
249
362
  );
250
- return { artifacts, objects, mappings, ioSymbols, ioMappings, publication, diagnostics: [] };
363
+ return {
364
+ artifacts,
365
+ objects,
366
+ mappings,
367
+ ioSymbols,
368
+ ioMappings,
369
+ publication,
370
+ debug,
371
+ diagnostics: [],
372
+ };
251
373
  }
252
374
 
253
375
  private objectPath(object: GeneratedObject): string {
@@ -379,13 +501,7 @@ END_VAR
379
501
  }
380
502
  for (const { key, root, segments, type } of this.plan.storageBindings) {
381
503
  const { address, mapped, inverted } = required(options.io[key]);
382
- const target = segments.reduce(
383
- (path, segment) =>
384
- segment.kind === "field"
385
- ? `${path}.${targetTypes.field(segment.record, segment.name)}`
386
- : `${path}[${segment.value}]`,
387
- required(references.get(root.id)),
388
- );
504
+ const target = this.bindingTarget({ root, segments });
389
505
  if (mapped) {
390
506
  ioMappings.push({ key, address, variable: target });
391
507
  continue;
@@ -413,6 +529,17 @@ END_VAR
413
529
  });
414
530
  }
415
531
 
532
+ /** The target symbol of an `io` storage path. */
533
+ private bindingTarget({ root, segments }: Pick<StorageBinding, "root" | "segments">): string {
534
+ return segments.reduce(
535
+ (path, segment) =>
536
+ segment.kind === "field"
537
+ ? `${path}.${this.targetTypes.field(segment.record, segment.name)}`
538
+ : `${path}[${segment.value}]`,
539
+ required(this.references.get(root.id)),
540
+ );
541
+ }
542
+
416
543
  private prepareStatements(items: readonly CoreStatement[]): void {
417
544
  const { numeric } = this;
418
545
  for (const item of items) {
@@ -440,6 +567,8 @@ END_VAR
440
567
  this.prepareStatements(item.body);
441
568
  }
442
569
  if (item.kind === "return" && item.value) numeric.prepare(item.value);
570
+ if (item.kind === "telemetry")
571
+ for (const value of telemetryOperands(item)) numeric.prepare(value);
443
572
  if (item.kind === "invoke") {
444
573
  if (item.index) numeric.prepare(item.index);
445
574
  for (const value of item.arguments) numeric.prepare(value);
@@ -458,6 +587,7 @@ END_VAR
458
587
  const fields = new Names(),
459
588
  mapped = new Map<string, string>();
460
589
  for (const object of objects) fields.reserve(object.name);
590
+ fields.reserve(this.debugGlobal);
461
591
  for (const objectName of [
462
592
  ...core.functions.filter((fn) => !fn.owner).map((fn) => required(functionNames.get(fn.id))),
463
593
  ...blockNames.values(),
@@ -478,6 +608,25 @@ END_VAR
478
608
  if (block.runtime?.kind === "mailbox")
479
609
  this.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
480
610
  blockFields.set(block.id, mapped);
611
+
612
+ const settings = this.plan.project.debug;
613
+ // Trace sites and an unhandled failure need the step a job finished at.
614
+ const stepped =
615
+ this.debug.jobSites.has(block.id) || this.plan.telemetry?.failures.has(block.id);
616
+ const tracked = Boolean(block.job && (settings?.jobs || stepped));
617
+ const carries = settings?.jobs && this.debug.carriers.has(block.id);
618
+ if (tracked || carries)
619
+ this.debugFields.set(block.id, {
620
+ ...(tracked && {
621
+ busy: fields.allocate("tsplcBusy"),
622
+ track: fields.allocate("TsplcTrack"),
623
+ }),
624
+ ...(tracked && settings?.jobs && { startedAt: fields.allocate("startedAt") }),
625
+ ...(stepped && { step: fields.allocate("tsplcStep") }),
626
+ ...(carries && { job: fields.allocate("requestJob") }),
627
+ ...(carries &&
628
+ block.runtime?.kind === "http" && { sequence: fields.allocate("sequence") }),
629
+ });
481
630
  }
482
631
  }
483
632
 
@@ -488,6 +637,7 @@ END_VAR
488
637
  const names = new Names(),
489
638
  references = new Map<string, string>();
490
639
  for (const object of this.objects) names.reserve(object.name);
640
+ names.reserve(this.debugGlobal);
491
641
  for (const name of [...this.functionNames.values(), ...this.blockNames.values()])
492
642
  names.reserve(name);
493
643
  if (this.programRoutines.has(fn.id) && "parameters" in fn && fn.result)
@@ -561,6 +711,7 @@ END_VAR`,
561
711
  epoch: `${rpcGlobal}.epochs[${slot}]`,
562
712
  });
563
713
  }
714
+ const requestFields = this.debugFields.get(fn.id);
564
715
  const generated = emitHttp(
565
716
  fn,
566
717
  required(this.blockNames.get(fn.id)),
@@ -570,6 +721,9 @@ END_VAR`,
570
721
  endpoint,
571
722
  this.networkName ? `${this.networkName}.network` : "",
572
723
  rpcGlobal,
724
+ requestFields?.job && requestFields.sequence
725
+ ? { job: requestFields.job, sequence: requestFields.sequence }
726
+ : undefined,
573
727
  );
574
728
  this.objects.push(
575
729
  generated,
@@ -730,10 +884,123 @@ END_VAR`,
730
884
  else write(`${destination} := ${targetTypes.literal(value, id)};`, depth, span);
731
885
  };
732
886
 
887
+ const ring = (task = this.debug.tasks.get(fn.id)) =>
888
+ `${this.debugGlobal}.${required(this.rings.get(required(task)))}`;
889
+ // Trace operands are DINTs: BOOL as 0/1, enums by value, integers clamped to the DINT range.
890
+ const encode = (value: CoreExpression): string => {
891
+ const type = required(typeMap.get(value.type));
892
+ const text = expression(value);
893
+ if (type.kind === "bool") return `BOOL_TO_DINT(${text})`;
894
+ if (type.kind !== "integer" && type.kind !== "bits") return `TO_DINT(${text})`;
895
+ const signed = type.kind === "integer" && type.signed;
896
+ if (type.bits < 32 || (signed && type.bits === 32)) return `TO_DINT(${text})`;
897
+ if (signed) return `TO_DINT(LIMIT(LINT#-2147483648, ${text}, LINT#2147483647))`;
898
+ const wide = type.bits === 32 ? "UDINT" : "ULINT";
899
+ return `TO_DINT(MIN(TO_${wide}(${text}), ${wide}#2147483647))`;
900
+ };
901
+ // CODESYS requires every input, so operands a site lacks are passed as 0.
902
+ const record = (site: number, value: string, operands: readonly Operand[] = []): string => {
903
+ const captured = Array.from(
904
+ { length: required(this.plan.telemetry?.traceOperands) },
905
+ (_, index) => {
906
+ const operand = operands[index];
907
+ return `, operand${index} := ${operand ? encode(operand.capture) : "DINT#0"}`;
908
+ },
909
+ );
910
+ return `${ring()}.Trace(site := UINT#${site}, value := ${value}, operands := USINT#${operands.length}${captured.join("")});`;
911
+ };
912
+ const instrument = (item: CoreStatement, depth: number): void => {
913
+ for (const probe of this.debug.probes.get(item) ?? []) {
914
+ if (probe.kind === "writer") {
915
+ const writer = `${this.debugGlobal}.${this.debugSlots.writers}[${probe.output}] := UINT#${probe.site};`;
916
+ if (!probe.when.length) {
917
+ write(writer, depth, item.span);
918
+ continue;
919
+ }
920
+ const reached = probe.when.map(
921
+ ({ index, value }) => `TO_DINT(${expression(index)}) = DINT#${value}`,
922
+ );
923
+ write(`IF ${reached.join(" AND ")} THEN`, depth, item.span);
924
+ write(writer, depth + 1, item.span);
925
+ write("END_IF;", depth, item.span);
926
+ continue;
927
+ }
928
+ const value = `TO_DINT(${expression(probe.value)})`;
929
+ if (item.kind === "assign")
930
+ write(
931
+ `IF ${place(item.root, item.path)} <> ${expression(probe.value)} THEN`,
932
+ depth,
933
+ item.span,
934
+ );
935
+ else {
936
+ const last = `${this.debugGlobal}.${this.debugSlots.decisions}[${required(probe.slot)}]`;
937
+ write(`IF ${value} <> ${last} THEN`, depth, item.span);
938
+ write(`${last} := ${value};`, depth + 1, item.span);
939
+ }
940
+ write(record(probe.site, value, probe.operands), depth + 1, item.span);
941
+ write("END_IF;", depth, item.span);
942
+ }
943
+ };
944
+
945
+ const tracked = block && this.debugFields.get(block.id);
946
+ const jobField = (job: CoreFunctionBlock, name: string) =>
947
+ load(required(job.state.find((item) => item.name === name)).id);
948
+ /**
949
+ * The job's tracking method, which records it starting or finishing. The job calls it on
950
+ * entry and on every exit: its caller stops calling it once it is done, so only the call that
951
+ * finishes it sees the finish.
952
+ */
953
+ const jobTracking = (job: CoreFunctionBlock, fields: NonNullable<typeof tracked>) => {
954
+ const busy = jobField(job, "busy");
955
+ const sites = this.debug.jobSites.get(job.id);
956
+ const failure = this.plan.telemetry?.failures.get(job.id);
957
+ const lines: string[] = [];
958
+ const line = (text: string, depth: number) => lines.push(" ".repeat(depth) + text);
959
+ line(`IF ${busy} = ${required(fields.busy)} THEN`, 0);
960
+ line("RETURN;", 1);
961
+ line("END_IF;", 0);
962
+ if (fields.startedAt || sites) {
963
+ line(`IF ${busy} THEN`, 0);
964
+ if (fields.startedAt) line(`${fields.startedAt} := TIME_TO_UDINT(TIME());`, 1);
965
+ if (sites) line(record(sites.start, `TO_DINT(${jobField(job, "step")})`), 1);
966
+ line("END_IF;", 0);
967
+ }
968
+ if (sites || failure) {
969
+ const error = jobField(job, "error");
970
+ line(`IF NOT ${busy} THEN`, 0);
971
+ if (sites) {
972
+ line(`IF ${error} <> 0 THEN`, 1);
973
+ line(record(sites.completion, `-TO_DINT(${error})`), 2);
974
+ line("ELSE", 1);
975
+ line(record(sites.completion, `TO_DINT(${required(fields.step)})`), 2);
976
+ line("END_IF;", 1);
977
+ }
978
+ // Cancellation is asked for, so it isn't a failure.
979
+ if (failure) {
980
+ line(`IF ${error} <> 0 AND ${error} <> 1 THEN`, 1);
981
+ line(
982
+ `${ring(failure.task)}.Failure${failure.id}(code := ${error}, step := ${required(fields.step)});`,
983
+ 2,
984
+ );
985
+ line("END_IF;", 1);
986
+ }
987
+ line("END_IF;", 0);
988
+ }
989
+ line(`${fields.busy} := ${busy};`, 0);
990
+ return `${lines.join("\n")}\n`;
991
+ };
992
+
733
993
  const body = (items: readonly CoreStatement[], depth: number): void => {
734
994
  for (const item of items) {
735
995
  switch (item.kind) {
736
996
  case "assign":
997
+ instrument(item, depth);
998
+ if (
999
+ tracked?.step &&
1000
+ block?.job &&
1001
+ item.root === block.state.find((field) => field.name === "step")?.id
1002
+ )
1003
+ write(`${tracked.step} := ${jobField(block, "step")};`, depth, item.span);
737
1004
  if (item.value.kind === "constant")
738
1005
  assignConstant(
739
1006
  place(item.root, item.path),
@@ -757,6 +1024,12 @@ END_VAR`,
757
1024
  const formal = required(target.inputs.find((field) => field.name === input));
758
1025
  return `${required(required(blockFields.get(target.id)).get(formal.id))} := ${expression(value)}`;
759
1026
  });
1027
+ // Service calls report the job that made them: a single-instance job passes its own id,
1028
+ // and everything between it and the call passes the id it was given.
1029
+ const job = this.debugFields.get(target.id)?.job;
1030
+ const id = this.jobIds.get(item.instance);
1031
+ const given = owner && this.debugFields.get(owner.id)?.job;
1032
+ if (job && (id || given)) arguments_.push(`${job} := ${id ? `UDINT#${id}` : given}`);
760
1033
  const receiver = item.index
761
1034
  ? `${load(item.instance)}[${expression(item.index)}]`
762
1035
  : load(item.instance);
@@ -883,6 +1156,7 @@ END_VAR`,
883
1156
  break;
884
1157
  }
885
1158
  case "return":
1159
+ instrument(item, depth);
886
1160
  if (block) {
887
1161
  if (item.value) {
888
1162
  const returned = expression(item.value);
@@ -907,6 +1181,7 @@ END_VAR`,
907
1181
  item.span,
908
1182
  );
909
1183
  if (mutex) release(mutex, depth, item.span);
1184
+ if (tracked?.track) write(`${tracked.track}();`, depth);
910
1185
  write("RETURN;", depth, item.span);
911
1186
  break;
912
1187
  case "break":
@@ -915,6 +1190,18 @@ END_VAR`,
915
1190
  case "continue":
916
1191
  write("CONTINUE;", depth, item.span);
917
1192
  break;
1193
+ case "telemetry": {
1194
+ const site = required(this.plan.telemetry?.calls.get(item));
1195
+ const arguments_ = callParameters(item).map(
1196
+ ({ name, value }) => `${name} := ${expression(value)}`,
1197
+ );
1198
+ write(
1199
+ `${ring(site.task)}.Record${site.id}(${arguments_.join(", ")});`,
1200
+ depth,
1201
+ item.span,
1202
+ );
1203
+ break;
1204
+ }
918
1205
  }
919
1206
  }
920
1207
  };
@@ -931,7 +1218,14 @@ END_VAR`,
931
1218
  write("RETURN;", 1);
932
1219
  write("END_IF;", 0);
933
1220
  }
1221
+ if (block && tracked?.track) {
1222
+ // Before the job's own early return, so a job started since its last call is seen.
1223
+ write(`${tracked.track}();`, 0);
1224
+ // The step it was in when it finished.
1225
+ if (tracked.step) write(`${tracked.step} := ${jobField(block, "step")};`, 0);
1226
+ }
934
1227
  body(fn.body, 0);
1228
+ if (tracked?.track) write(`${tracked.track}();`, 0);
935
1229
  if (mutex) release(mutex, 0);
936
1230
  if (!block && !method && !program && !fn.result) write(`${name} := TRUE;`, 0);
937
1231
 
@@ -964,6 +1258,8 @@ END_VAR`,
964
1258
  "VAR_IN_OUT",
965
1259
  inputs.filter((item) => item.mode === "inOut"),
966
1260
  );
1261
+ if (tracked && tracked.job)
1262
+ declaration.push("VAR_INPUT", ` ${tracked.job} : UDINT;`, "END_VAR");
967
1263
  if (program && "parameters" in fn && fn.result) {
968
1264
  declaration.push(
969
1265
  "VAR_OUTPUT",
@@ -987,6 +1283,14 @@ END_VAR`,
987
1283
  "VAR RETAIN",
988
1284
  block.state.filter((item) => retainedVariables.has(item.id)),
989
1285
  );
1286
+ const fields = (
1287
+ [
1288
+ [tracked && tracked.busy, "BOOL"],
1289
+ [tracked && tracked.step, "UINT"],
1290
+ [tracked && tracked.startedAt, "UDINT"],
1291
+ ] as const
1292
+ ).flatMap(([field, type]) => (field ? [` ${field} : ${type};`] : []));
1293
+ if (fields.length) declaration.push("VAR", ...fields, "END_VAR");
990
1294
  }
991
1295
  if (declarations.length) {
992
1296
  declaration.push(block || program ? "VAR_TEMP" : "VAR");
@@ -1007,6 +1311,15 @@ END_VAR`,
1007
1311
  declaration: `${declaration.join("\n")}\n`,
1008
1312
  implementation: `${lines.join("\n")}\n`,
1009
1313
  });
1314
+ if (block && tracked?.track)
1315
+ objects.push({
1316
+ id: `${fn.id}:${tracked.track}`,
1317
+ parent: fn.id,
1318
+ kind: "method",
1319
+ name: tracked.track,
1320
+ declaration: `METHOD PRIVATE ${tracked.track}\n`,
1321
+ implementation: jobTracking(block, tracked),
1322
+ });
1010
1323
  }
1011
1324
 
1012
1325
  private emitProgram(program: CodesysPlan["core"]["programs"][number]): void {
@@ -1025,6 +1338,7 @@ END_VAR`,
1025
1338
  const stateful = this.programRoutines.has(program.entry);
1026
1339
  const call = `${functionNames.get(program.entry)}();`;
1027
1340
  const lines = [
1341
+ ...this.scanPrologue(program.name),
1028
1342
  ...channels
1029
1343
  .filter((channel) => channel.input)
1030
1344
  .map(({ target, wire, inverted }) => `${target} := ${inverted ? "NOT " : ""}${wire};`),
@@ -1043,4 +1357,382 @@ END_VAR`,
1043
1357
  implementation: `${lines.join("\n")}\n`,
1044
1358
  });
1045
1359
  }
1360
+
1361
+ /** The first program of a task with a ring runs its sender first, which counts the scan and reads the clock. */
1362
+ private scanPrologue(program: string): string[] {
1363
+ const task = this.plan.deployment.tasks.find((item) => item.programs[0] === program);
1364
+ const ring = task && this.rings.get(task.name);
1365
+ return ring ? [`${this.debugGlobal}.${ring}();`] : [];
1366
+ }
1367
+
1368
+ private emitTelemetry(): void {
1369
+ const { telemetry } = this.plan;
1370
+ const names = this.telemetryNames;
1371
+ if (!telemetry || !names) return;
1372
+ this.objects.push(
1373
+ ...telemetryObjects({
1374
+ plan: telemetry,
1375
+ names,
1376
+ target: this.targetTypes,
1377
+ endpoint: required(this.plan.http[telemetryClient]),
1378
+ network: `${required(this.networkName)}.network`,
1379
+ build: buildPlaceholder,
1380
+ types: this.typeMap,
1381
+ }),
1382
+ );
1383
+ }
1384
+
1385
+ /**
1386
+ * `GVL_TsplcDebug` holds the build id, which identifies this ST and its manifest, so the id is
1387
+ * computed over everything else first.
1388
+ */
1389
+ private emitDebugGlobal(): DebugManifest {
1390
+ const manifest = this.manifest();
1391
+ const hash = createHash("sha256");
1392
+ for (const object of this.objects)
1393
+ hash.update(`${object.name}\n${object.declaration}\n${object.implementation ?? ""}\n`);
1394
+ hash.update(JSON.stringify(manifest));
1395
+ const id = hash.digest("hex").slice(0, 16);
1396
+
1397
+ // A batch names its build; the id is known only now, so the sender's literal is filled in last.
1398
+ const send = this.objects.find((object) => object.id === "tsplc:telemetryWriter:Send");
1399
+ if (send) send.implementation = send.implementation!.replace(buildPlaceholder, id);
1400
+
1401
+ const fields = [`buildId : STRING(16) := '${id}'`];
1402
+ for (const [task, field] of this.rings)
1403
+ fields.push(`${field} : ${required(this.telemetryNames).writer} := (task := '${task}')`);
1404
+ const settings = this.plan.project.debug;
1405
+ if (settings) {
1406
+ if (this.debug.decisions.size)
1407
+ fields.push(
1408
+ `${this.debugSlots.decisions} : ARRAY[0..${this.debug.decisions.size - 1}] OF DINT`,
1409
+ );
1410
+ if (settings.writers && this.debug.outputs.length)
1411
+ fields.push(
1412
+ `${this.debugSlots.writers} : ARRAY[0..${this.debug.outputs.length - 1}] OF UINT`,
1413
+ );
1414
+ for (const raw of [...this.devices.values()].flatMap((device) => Object.values(device)))
1415
+ fields.push(`${raw.field} AT ${raw.address} : ARRAY[0..${raw.bytes - 1}] OF BYTE`);
1416
+ }
1417
+ this.objects.push({
1418
+ id: "debug",
1419
+ kind: "globalList",
1420
+ name: this.debugGlobal,
1421
+ // Nothing in the program reads the build id; linkalways keeps it in the application.
1422
+ declaration: `{attribute 'linkalways'}
1423
+ {attribute 'qualified_only'}
1424
+ VAR_GLOBAL
1425
+ ${fields.map((field) => ` ${field};\n`).join("")}END_VAR
1426
+ `,
1427
+ });
1428
+ return { ...manifest, build: { ...manifest.build, id } };
1429
+ }
1430
+
1431
+ /** The IEC path of a block instance. */
1432
+ private instancePath(path: InstancePath): string {
1433
+ let text = "",
1434
+ holder: string | undefined;
1435
+ for (const { variable, index } of path) {
1436
+ text += holder
1437
+ ? `.${required(required(this.blockFields.get(holder)).get(variable.id))}`
1438
+ : required(this.references.get(variable.id));
1439
+ if (index !== undefined) text += `[${index}]`;
1440
+ holder = required(instancedBlock(variable.type, this.typeMap)).block;
1441
+ }
1442
+ return text;
1443
+ }
1444
+
1445
+ /** Service calls a job instance makes, down to (not into) the jobs it starts itself. */
1446
+ private requests(id: string, prefix: string, job?: number): DebugJob["requests"] {
1447
+ const block = required(this.blocks.get(id));
1448
+ return block.state.flatMap((child) => {
1449
+ const instance = instancedBlock(child.type, this.typeMap);
1450
+ if (!instance) return [];
1451
+ // A nested job tags the calls below it with its own id.
1452
+ const caller = this.jobIds.get(child.id) ?? job;
1453
+ const type = required(this.typeMap.get(child.type));
1454
+ const field = `${prefix}.${required(required(this.blockFields.get(id)).get(child.id))}`;
1455
+ const targets =
1456
+ type.kind === "array"
1457
+ ? Array.from(
1458
+ { length: type.length },
1459
+ (_, index) => `${field}[${type.lowerBound + index}]`,
1460
+ )
1461
+ : [field];
1462
+ const sequence = this.debugFields.get(instance.block)?.sequence;
1463
+ const path = this.plan.http[instance.block]?.path;
1464
+ return targets.flatMap((target) =>
1465
+ sequence && path
1466
+ ? [
1467
+ {
1468
+ service: serviceOfPath(path) ?? path,
1469
+ target,
1470
+ sequence: `${target}.${sequence}`,
1471
+ ...(caller !== undefined && { job: caller }),
1472
+ },
1473
+ ]
1474
+ : this.requests(instance.block, target, caller),
1475
+ );
1476
+ });
1477
+ }
1478
+
1479
+ /** Static member reads in a body, by TypeScript path. */
1480
+ private reads(body: readonly CoreStatement[], sources: Sources): DebugFunction["reads"] {
1481
+ const reads = new Map<string, DebugFunction["reads"][number]>();
1482
+ const path = (items: CorePath = []) => {
1483
+ for (const segment of items) if (segment.kind === "index") expression(segment.value);
1484
+ };
1485
+ const expression = (value: CoreExpression): void => {
1486
+ if (value.kind === "unary" || value.kind === "convert") expression(value.operand);
1487
+ if (value.kind === "binary") {
1488
+ expression(value.left);
1489
+ expression(value.right);
1490
+ }
1491
+ if (value.kind !== "load") return;
1492
+ path(value.path);
1493
+ const read = storagePath(required(this.debug.variables.get(value.root)), value.path);
1494
+ const range = read && sources.range(value.span);
1495
+ if (range) reads.set(`${JSON.stringify(range)}${read}`, { range, path: read });
1496
+ };
1497
+ const statements = (items: readonly CoreStatement[]): void => {
1498
+ for (const item of items) {
1499
+ if (item.kind === "assign") {
1500
+ path(item.path);
1501
+ expression(item.value);
1502
+ }
1503
+ if (item.kind === "if") {
1504
+ expression(item.condition);
1505
+ statements(item.then);
1506
+ statements(item.else);
1507
+ }
1508
+ if (item.kind === "switch") {
1509
+ expression(item.value);
1510
+ for (const branch of item.cases) statements(branch.body);
1511
+ statements(item.fallback);
1512
+ }
1513
+ if (item.kind === "for") {
1514
+ if (item.dynamic) {
1515
+ expression(item.dynamic.start);
1516
+ expression(item.dynamic.limit);
1517
+ }
1518
+ statements(item.body);
1519
+ }
1520
+ if (item.kind === "return" && item.value) expression(item.value);
1521
+ if (item.kind === "telemetry") telemetryOperands(item).forEach(expression);
1522
+ if (item.kind === "invoke") {
1523
+ if (item.index) expression(item.index);
1524
+ item.arguments.forEach(expression);
1525
+ }
1526
+ if (item.kind === "blockUpdate") {
1527
+ if (item.index) expression(item.index);
1528
+ Object.values(item.inputs).forEach(expression);
1529
+ }
1530
+ }
1531
+ };
1532
+ statements(body);
1533
+ return [...reads.values()];
1534
+ }
1535
+
1536
+ /** The target symbol and type that hold an `io` key's value, when this program has it. */
1537
+ private ioTarget(key: string): { target: string; type: string } | undefined {
1538
+ const { core } = this.plan;
1539
+ const logical = core.variables.find(
1540
+ (variable) =>
1541
+ (variable.storage === "input" || variable.storage === "output") && variable.name === key,
1542
+ );
1543
+ if (logical) return { target: required(this.references.get(logical.id)), type: logical.type };
1544
+ if (!isStoragePath(key)) return undefined;
1545
+ const resolved = resolveStoragePath(core, key);
1546
+ return "error" in resolved
1547
+ ? undefined
1548
+ : { target: this.bindingTarget(resolved), type: resolved.type.id };
1549
+ }
1550
+
1551
+ private manifest(): DebugManifest {
1552
+ const { core, project, deployment, options } = this.plan;
1553
+ const settings = project.debug;
1554
+ const sources = new Sources(project.root);
1555
+ const global = (field: string) => `${this.debugGlobal}.${field}`;
1556
+
1557
+ const functionIds = new Map<string, number>();
1558
+ const functions = [
1559
+ ...core.functions,
1560
+ ...core.blocks.filter((block) => !block.standard && !block.runtime),
1561
+ ].flatMap((routine): DebugFunction[] => {
1562
+ const block = "inputs" in routine ? routine : undefined;
1563
+ const fn = "parameters" in routine ? routine : undefined;
1564
+ const declaration = sources.range(block?.job?.span ?? routine.span);
1565
+ if (!declaration) return [];
1566
+ const id = functionIds.size;
1567
+ functionIds.set(routine.id, id);
1568
+ const task = this.debug.tasks.get(routine.id);
1569
+ const origin = fn?.origin;
1570
+ const method = fn?.owner;
1571
+ return [
1572
+ {
1573
+ id,
1574
+ name: block?.job?.name ?? origin?.name ?? routine.name,
1575
+ declaration,
1576
+ ...(origin?.instance && { instance: origin.instance }),
1577
+ ...(task && { task }),
1578
+ target: block
1579
+ ? required(this.blockNames.get(block.id))
1580
+ : method
1581
+ ? `${required(this.blockNames.get(method.block))}.${required(this.functionNames.get(routine.id))}`
1582
+ : required(this.functionNames.get(routine.id)),
1583
+ reads: this.reads(routine.body, sources),
1584
+ },
1585
+ ];
1586
+ });
1587
+ const declared = (routine: string | undefined) => {
1588
+ const id = routine === undefined ? undefined : functionIds.get(routine);
1589
+ return id === undefined ? undefined : { id, range: functions[id]!.declaration };
1590
+ };
1591
+
1592
+ const events = this.debug.events.flatMap((site): DebugEventSite[] => {
1593
+ const owner = declared(site.routine);
1594
+ const range = sources.range(site.span) ?? owner?.range;
1595
+ if (!range) return [];
1596
+ return [
1597
+ {
1598
+ id: site.id,
1599
+ kind: site.kind,
1600
+ ...(site.job && {
1601
+ job: this.jobs.findIndex(({ block }) => block.id === site.job!.block) + 1,
1602
+ phase: site.job.phase,
1603
+ }),
1604
+ path: site.path,
1605
+ ...(owner && { function: owner.id }),
1606
+ type: site.type,
1607
+ range,
1608
+ text: site.text ?? sources.text(site.span) ?? "",
1609
+ task: site.task,
1610
+ operands: site.operands.map((operand) => ({
1611
+ text: sources.text(operand.span) ?? "",
1612
+ range: sources.range(operand.span) ?? range,
1613
+ type: operand.capture.type,
1614
+ ...(operand.path && { path: operand.path }),
1615
+ stable: operand.stable,
1616
+ })),
1617
+ },
1618
+ ];
1619
+ });
1620
+
1621
+ const jobs = this.jobs.flatMap(({ block, path }, index): DebugJob[] => {
1622
+ const job = required(block.job);
1623
+ const declaration = sources.range(job.span);
1624
+ if (!declaration) return [];
1625
+ const target = this.instancePath(path);
1626
+ const startedAt = this.debugFields.get(block.id)?.startedAt;
1627
+ return [
1628
+ {
1629
+ id: index + 1,
1630
+ name: job.name,
1631
+ declaration,
1632
+ ...(job.instance && { instance: job.instance }),
1633
+ target,
1634
+ steps: job.steps.map((step) => ({
1635
+ step: step.step,
1636
+ kind: step.kind,
1637
+ range: sources.range(step.span) ?? declaration,
1638
+ text: step.text,
1639
+ })),
1640
+ ...(startedAt && { startedAt: `${target}.${startedAt}` }),
1641
+ requests: this.requests(block.id, target),
1642
+ // Compiler-made functions, such as each service call's own job, carry its prefix.
1643
+ ...(generated(job.name) && { generated: true as const }),
1644
+ },
1645
+ ];
1646
+ });
1647
+
1648
+ const writers = settings?.writers
1649
+ ? this.debug.outputs.map((output, index) => ({
1650
+ output: output.key,
1651
+ target: global(`${this.debugSlots.writers}[${index}]`),
1652
+ sites: required(this.debug.writers[index]).flatMap((site) => {
1653
+ const owner = declared(site.routine);
1654
+ return owner
1655
+ ? [
1656
+ {
1657
+ id: site.id,
1658
+ range: sources.range(site.span) ?? owner.range,
1659
+ function: owner.id,
1660
+ },
1661
+ ]
1662
+ : [];
1663
+ }),
1664
+ }))
1665
+ : [];
1666
+
1667
+ const roots = core.variables
1668
+ .filter((variable) => ["module", "instance", "input", "output"].includes(variable.storage))
1669
+ .map((variable) => {
1670
+ const declaration = sources.range(variable.span);
1671
+ return {
1672
+ path: required(storagePath(variable)),
1673
+ target: required(this.references.get(variable.id)),
1674
+ type: variable.type,
1675
+ ...(declaration && { declaration }),
1676
+ readable: true,
1677
+ ...(variable.name.startsWith("tsplc") && { generated: true as const }),
1678
+ };
1679
+ });
1680
+
1681
+ const types = debugTypes(
1682
+ core.types,
1683
+ this.targetTypes,
1684
+ this.blocks,
1685
+ (block, variable) => required(required(this.blockFields.get(block)).get(variable)),
1686
+ (block) => {
1687
+ const fields = this.debugFields.get(block);
1688
+ return (
1689
+ [
1690
+ [fields?.busy, "BOOL"],
1691
+ [fields?.step, "UINT"],
1692
+ [fields?.startedAt, "UDINT"],
1693
+ [fields?.job, "UDINT"],
1694
+ [fields?.sequence, "UDINT"],
1695
+ ] as const
1696
+ ).flatMap(([name, type]) => (name ? [{ name, target: name, type }] : []));
1697
+ },
1698
+ sources,
1699
+ );
1700
+ const hardware = debugHardware(
1701
+ project.hardware ?? {
1702
+ catalog: { descriptors: [], devices: [] },
1703
+ config: { devices: {}, io: options.io },
1704
+ tree: false,
1705
+ },
1706
+ (key) => this.ioTarget(key),
1707
+ (id) =>
1708
+ Object.fromEntries(
1709
+ Object.entries(this.devices.get(id) ?? {}).map(([direction, raw]) => [
1710
+ direction,
1711
+ global(raw.field),
1712
+ ]),
1713
+ ),
1714
+ );
1715
+ const constants = debugConstants(core.folded ?? [], sources);
1716
+
1717
+ return {
1718
+ kind: "tsplc-debug",
1719
+ version: 1,
1720
+ build: { id: "", target: global("buildId"), compiler: `@tsplc/compiler ${version}` },
1721
+ sources: sources.files,
1722
+ types,
1723
+ roots,
1724
+ constants,
1725
+ ...hardware,
1726
+ functions,
1727
+ jobs,
1728
+ events,
1729
+ writers,
1730
+ tasks: deployment.tasks.map((task) => ({
1731
+ name: task.name,
1732
+ intervalMs: Number(task.intervalNanoseconds) / 1e6,
1733
+ priority: task.priority,
1734
+ })),
1735
+ errors: jobErrors,
1736
+ };
1737
+ }
1046
1738
  }