@tsplc/compiler 0.5.7 → 0.5.9

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 (59) hide show
  1. package/dist/bun-runtime.js +8 -2
  2. package/dist/bun-runtime.js.map +3 -3
  3. package/dist/cli.js +17 -5
  4. package/dist/cli.js.map +5 -5
  5. package/dist/codesys.js +2933 -1724
  6. package/dist/codesys.js.map +20 -19
  7. package/dist/index.js +870 -685
  8. package/dist/index.js.map +20 -19
  9. package/dist/ir.js +1654 -1364
  10. package/dist/ir.js.map +16 -14
  11. package/dist/project.js +5 -2
  12. package/dist/project.js.map +3 -3
  13. package/dist/telemetry.js +8 -2
  14. package/dist/telemetry.js.map +3 -3
  15. package/package.json +9 -9
  16. package/src/codesys/debug.ts +17 -2
  17. package/src/codesys/emit.ts +34 -11
  18. package/src/codesys/engineering.ts +27 -12
  19. package/src/codesys/explain.ts +1465 -0
  20. package/src/codesys/global-lists.ts +21 -9
  21. package/src/codesys/http.ts +12 -0
  22. package/src/codesys/instrumentation.ts +131 -3
  23. package/src/codesys/manifest.ts +29 -12
  24. package/src/codesys/numeric.ts +5 -3
  25. package/src/codesys/plan.ts +31 -28
  26. package/src/codesys/programs.ts +63 -1
  27. package/src/codesys/types.ts +34 -12
  28. package/src/frontend/async.ts +14 -8
  29. package/src/frontend/coroutines.ts +55 -16
  30. package/src/frontend/elaborate/expressions.ts +10 -2
  31. package/src/frontend/elaborate/filtered-arrays.ts +5 -5
  32. package/src/frontend/elaborate/index.ts +42 -4
  33. package/src/frontend/elaborate/model.ts +48 -1
  34. package/src/frontend/elaborate/references.ts +6 -6
  35. package/src/frontend/elaborate/specialize.ts +18 -4
  36. package/src/frontend/elaborate/storage.ts +58 -2
  37. package/src/frontend/expressions.ts +2 -2
  38. package/src/frontend/generated-names.ts +95 -0
  39. package/src/frontend/intrinsics.ts +1 -2
  40. package/src/frontend/promise-chains.ts +22 -8
  41. package/src/frontend/promises.ts +8 -10
  42. package/src/frontend/statements.ts +3 -2
  43. package/src/frontend/tasks.ts +8 -8
  44. package/src/frontend/typescript.ts +5 -2
  45. package/src/ir/conditions.ts +895 -0
  46. package/src/ir/core-model.ts +2 -2
  47. package/src/ir/fold.ts +15 -107
  48. package/src/ir/identity.ts +9 -0
  49. package/src/ir/index.ts +18 -13
  50. package/src/ir/job-errors.ts +14 -0
  51. package/src/ir/link.ts +1 -0
  52. package/src/ir/model.ts +16 -79
  53. package/src/ir/numeric.ts +5 -41
  54. package/src/ir/ranges.ts +8 -14
  55. package/src/ir/scalars.ts +6 -4
  56. package/src/ir/share.ts +0 -52
  57. package/src/project/debugger.ts +9 -0
  58. package/src/project/project.ts +6 -0
  59. package/src/project/release.ts +7 -4
@@ -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,
@@ -944,6 +945,17 @@ IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberVal
944
945
  );
945
946
  };
946
947
 
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";
958
+
947
959
  /** A service-call block: its HTTP or OPC UA client, the client's methods and, over OPC UA, its slots' global list. */
948
960
  export function emitServiceBlock(
949
961
  { plan, symbols, instrumentation }: EmissionContext,
@@ -6,10 +6,18 @@ 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,
@@ -17,7 +25,11 @@ import {
17
25
  storageName,
18
26
  } from "./expressions";
19
27
  import { type RpcChannel, rpcSlots } from "./http";
20
- import { isStoragePath, resolveStoragePath } from "./io-paths";
28
+ import {
29
+ isStoragePath,
30
+ resolveStoragePath,
31
+ type StorageBinding,
32
+ } from "./io-paths";
21
33
  import { ioAddress } from "./manifest";
22
34
  import { Names } from "./names";
23
35
  import type { CodesysPlan } from "./plan";
@@ -25,6 +37,97 @@ import { type CodesysSymbols, type EmissionContext, required } from "./symbols";
25
37
  import { telemetryClient, telemetryObjects } from "./telemetry";
26
38
  import { stStringLiteral } from "./types";
27
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
+
28
131
  /**
29
132
  * The debugger's and telemetry's names in the program: `GVL_TsplcDebug` and its fields, each
30
133
  * task's ring, and the instrumentation fields of each block.
@@ -59,6 +162,11 @@ export function planInstrumentation(
59
162
  )
60
163
  ).map(({ key, root, segments }) => ({ key, root, segments })),
61
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
+ }
62
170
  const analysis = new DebugAnalysis(core, plan.deployment, settings, outputs);
63
171
  /** `GVL_TsplcDebug`, and the names of its fields. */
64
172
  const global = symbols.names.allocateObject("GVL", "TsplcDebug");
@@ -136,11 +244,28 @@ export function planInstrumentation(
136
244
  );
137
245
  }
138
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
+ );
139
262
  return {
140
263
  analysis,
141
264
  global,
142
265
  slots,
143
266
  rings,
267
+ /** Each task's clock in `GVL_TsplcDebug`, by task, when it has no ring that reads the clock. */
268
+ scanClocks,
144
269
  telemetryNames,
145
270
  jobs,
146
271
  jobIds,
@@ -231,6 +356,9 @@ export function emitDebugGlobal(
231
356
  }
232
357
 
233
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
+ }
234
362
  for (const [task, field] of instrumentation.rings) {
235
363
  fields.push(
236
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>> = {
@@ -2,7 +2,6 @@
2
2
  import {
3
3
  type Constant,
4
4
  type CoreExpression,
5
- type CoreFunction,
6
5
  type CoreStatement,
7
6
  type Deployment,
8
7
  type Diagnostic,
@@ -10,7 +9,6 @@ import {
10
9
  forwardTemporaries,
11
10
  instancedBlock,
12
11
  isVerifiedCore,
13
- joinPrograms,
14
12
  nestedBodies,
15
13
  type PlcType,
16
14
  type SourceSpan,
@@ -22,6 +20,7 @@ import {
22
20
  import type {
23
21
  Publication,
24
22
  ResolvedDebugConfig,
23
+ ResolvedHmiConfig,
25
24
  ResolvedTelemetryConfig,
26
25
  ResolvedTsplcConfig,
27
26
  } from "@tsplc/config";
@@ -32,8 +31,10 @@ import { type CodesysOptions, optionsSchema } from "./config";
32
31
  import {
33
32
  type HttpEndpoint,
34
33
  resolveHttpEndpoint,
34
+ serviceBlock,
35
35
  validateHttpLayout,
36
36
  } from "./http";
37
+ import { writerPaths } from "./instrumentation";
37
38
  import {
38
39
  iecSpelling,
39
40
  isStoragePath,
@@ -63,15 +64,20 @@ export interface CodesysPlan {
63
64
  readonly [planned]: true;
64
65
  readonly core: VerifiedCoreModule;
65
66
  /**
66
- * The functions as the frontend specialized them, one per instance, and the routine each that
67
- * `shareRoutines` merged away runs as. The debug manifest describes every instance.
67
+ * The module as the frontend specialized it, one routine per instance, before programs are joined
68
+ * and routines folded, shared and forwarded, with each task's programs in that module. The debug
69
+ * manifest and explanations describe every instance, whatever the emitted routines look like.
68
70
  */
69
- readonly specialized: readonly CoreFunction[];
71
+ readonly specialized: VerifiedCoreModule;
72
+ readonly specializedTasks: Deployment;
73
+ /** The routine each specialized function that `shareRoutines` merged away runs as. */
70
74
  readonly sharedRoutines: ReadonlyMap<string, string>;
71
75
  readonly deployment: Deployment;
72
76
  readonly options: CodesysOptions;
73
77
  /** `io` keys that name authored storage, resolved against the verified types. */
74
78
  readonly storageBindings: readonly StorageBinding[];
79
+ /** The storage paths `debug.writers.paths` matches, each recorded in a last-writer slot. */
80
+ readonly writerPaths: readonly StorageBinding[];
75
81
  readonly publication: Publication;
76
82
  readonly http: Readonly<Record<string, HttpEndpoint>>;
77
83
  readonly project: CodesysProject;
@@ -92,6 +98,8 @@ export interface CodesysProject {
92
98
  "transport" | "baseUrlEnv"
93
99
  >;
94
100
  hardware?: ProjectHardware;
101
+ /** The HMI's controls, whose targets the debugger names as clients that write. */
102
+ hmi?: Pick<ResolvedHmiConfig, "controls">;
95
103
  /** Where HTTP credentials and the telemetry base URL are read from; this process's environment by default. */
96
104
  environment?: Readonly<Record<string, string | undefined>>;
97
105
  }
@@ -148,7 +156,7 @@ export function planCodesys(
148
156
  };
149
157
  const http = new Map<string, HttpEndpoint>();
150
158
  for (const block of core.blocks) {
151
- if (block.runtime?.kind === "http" || block.runtime?.kind === "rpc") {
159
+ if (serviceBlock(block)) {
152
160
  try {
153
161
  validateHttpLayout(
154
162
  block,
@@ -179,6 +187,7 @@ export function planCodesys(
179
187
  }
180
188
 
181
189
  const storageBindings = validateIo(core, options, report);
190
+ const writerBindings = writerPaths(core, project.debug, report);
182
191
  validateTasks(core, scheduled, report);
183
192
  validateStorage(core, options, report);
184
193
  validateConstants(core, report);
@@ -203,11 +212,15 @@ export function planCodesys(
203
212
 
204
213
  const plan: CodesysPlan = Object.freeze({
205
214
  core,
206
- specialized: specialized.functions,
215
+ specialized,
216
+ specializedTasks: {
217
+ tasks: schedulePrograms(specialized, deployment.tasks, () => {}),
218
+ },
207
219
  sharedRoutines: routines,
208
220
  deployment: structuredClone(scheduled),
209
221
  options: structuredClone(options),
210
222
  storageBindings,
223
+ writerPaths: writerBindings,
211
224
  publication,
212
225
  http: Object.fromEntries(http),
213
226
  project,
@@ -225,8 +238,10 @@ export function planCodesys(
225
238
  Object.freeze(value);
226
239
  };
227
240
  freeze(plan.deployment);
241
+ freeze(plan.specializedTasks);
228
242
  freeze(plan.options);
229
243
  freeze(plan.storageBindings);
244
+ freeze(plan.writerPaths);
230
245
  freeze(plan.publication);
231
246
  plans.add(plan);
232
247
  return { plan, diagnostics: [] };
@@ -235,9 +250,10 @@ export function planCodesys(
235
250
  type Report = (message: string, span?: SourceSpan) => void;
236
251
 
237
252
  /**
238
- * Routines specialized per instance, merged where they run the same code in the same task, each
239
- * task's continuation programs joined into one, calls of routines that only return a constant
240
- * replaced by it, and temporaries read right after they are written folded into their reader.
253
+ * Routines specialized per instance, merged where they run the same code in the same task, calls
254
+ * of routines that only return a constant replaced by it, and temporaries read right after they
255
+ * are written folded into their reader. Continuation programs stay apart: each task's wrapper
256
+ * calls them, and joining them named the joined program after whichever came first.
241
257
  * The debugger's instrumentation is written per statement of each routine, so a program built
242
258
  * with `debug` keeps every instance's own routine, as does one whose scheduling is invalid: its
243
259
  * diagnostics name the routines as written.
@@ -252,33 +268,20 @@ function sharedRoutines(
252
268
  return unshared;
253
269
  }
254
270
  const issues: string[] = [];
255
- const scheduled = {
256
- tasks: schedulePrograms(core, deployment.tasks, (message) => {
257
- issues.push(message);
258
- }),
259
- };
271
+ schedulePrograms(core, deployment.tasks, (message) => {
272
+ issues.push(message);
273
+ });
260
274
  if (issues.length) {
261
275
  return unshared;
262
276
  }
263
- const continuations = new Set(
264
- core.programs.flatMap((program) =>
265
- program.continuation ? [program.name] : [],
266
- ),
267
- );
268
- const joined = joinPrograms(
269
- core,
270
- scheduled.tasks.map((task) =>
271
- task.programs.filter((name) => continuations.has(name)),
272
- ),
273
- );
274
- const folded = foldConstantRoutines(joined.core);
277
+ const folded = foldConstantRoutines(core);
275
278
  const tasks = routineTasks(folded.core, {
276
279
  tasks: schedulePrograms(folded.core, deployment.tasks, () => {}),
277
280
  });
278
281
  const shared = shareRoutines(folded.core, (routine) => tasks.get(routine.id));
279
282
  return {
280
283
  core: forwardTemporaries(shared.core),
281
- routines: new Map([...joined.routines, ...shared.routines]),
284
+ routines: shared.routines,
282
285
  };
283
286
  }
284
287
 
@@ -1,5 +1,6 @@
1
- import type { GeneratedObject, PlcProgram } from "@tsplc/compiler/ir";
1
+ import type { GeneratedObject, PlcProgram, Task } from "@tsplc/compiler/ir";
2
2
  import type { IoChannel } from "./global-lists";
3
+ import type { CodesysPlan } from "./plan";
3
4
  import { type EmissionContext, required } from "./symbols";
4
5
  import { accessedStorage } from "./task-access";
5
6
 
@@ -28,8 +29,10 @@ export function emitScanProgram(
28
29
  (item) => item.programs[0] === program.name,
29
30
  );
30
31
  const ring = task && instrumentation.rings.get(task.name);
32
+ const clock = task && instrumentation.scanClocks.get(task.name);
31
33
  const lines = [
32
34
  ...(ring ? [`${instrumentation.global}.${ring}();`] : []),
35
+ ...(clock ? [`${clock} := TO_DINT(TIME_TO_UDINT(TIME()));`] : []),
33
36
  ...channels
34
37
  .filter((channel) => channel.input)
35
38
  .map(
@@ -51,3 +54,62 @@ export function emitScanProgram(
51
54
  implementation: `${lines.join("\n")}\n`,
52
55
  };
53
56
  }
57
+
58
+ /**
59
+ * How a task's program list splits: the programs its configuration names, which it calls itself,
60
+ * and the ones the compiler adds (detached continuations, background jobs), which it calls through
61
+ * one wrapper. A task's configuration then depends on the project's configuration alone, so adding
62
+ * a continuation or a background job at an existing interval changes code, which an online change
63
+ * applies, never the task configuration, which it refuses.
64
+ */
65
+ export const taskPrograms = (plan: CodesysPlan, task: Task) => {
66
+ const programs = new Map(
67
+ plan.core.programs.map((program) => [program.name, program]),
68
+ );
69
+ const generated = (name: string) => {
70
+ const program = programs.get(name);
71
+ return Boolean(program?.continuation || program?.background);
72
+ };
73
+ const background = task.programs.every(
74
+ (name) => programs.get(name)?.background,
75
+ );
76
+ return {
77
+ configured: task.programs.filter((name) => !generated(name)),
78
+ wrapped: task.programs.filter(generated),
79
+ wrapper: {
80
+ id: `tsplc:task:${task.name}`,
81
+ label: background ? task.name : `TsplcContinuations_${task.name}`,
82
+ },
83
+ };
84
+ };
85
+
86
+ /** Each task's wrapper PROGRAM, which calls the programs the compiler added to it in their order. */
87
+ export function emitTaskWrappers(
88
+ { plan, symbols }: EmissionContext,
89
+ objects: readonly GeneratedObject[],
90
+ ): GeneratedObject[] {
91
+ const programObjects = new Map(
92
+ plan.core.programs.map((program) => [
93
+ program.name,
94
+ required(
95
+ objects.find(
96
+ (object) => object.id === program.id && object.kind === "program",
97
+ ),
98
+ ),
99
+ ]),
100
+ );
101
+ return plan.deployment.tasks.map((task) => {
102
+ const { wrapped, wrapper } = taskPrograms(plan, task);
103
+ const name = symbols.names.allocateObject("PRG", wrapper.label);
104
+ const calls = wrapped.map(
105
+ (program) => `${required(programObjects.get(program)).name}();`,
106
+ );
107
+ return {
108
+ id: wrapper.id,
109
+ kind: "program",
110
+ name,
111
+ declaration: `PROGRAM ${name}\n`,
112
+ implementation: calls.length ? `${calls.join("\n")}\n` : ";\n",
113
+ };
114
+ });
115
+ }