@tsplc/compiler 0.2.14 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/backends/codesys/debug.ts +509 -0
  2. package/backends/codesys/emit.ts +701 -9
  3. package/backends/codesys/http.ts +110 -34
  4. package/backends/codesys/index.ts +2 -1
  5. package/backends/codesys/io-paths.ts +3 -1
  6. package/backends/codesys/manifest.ts +312 -0
  7. package/backends/codesys/plan.ts +39 -9
  8. package/backends/codesys/publication.ts +2 -2
  9. package/backends/codesys/storage.ts +10 -3
  10. package/backends/codesys/task-access.ts +51 -1
  11. package/backends/codesys/telemetry.ts +593 -0
  12. package/backends/codesys/types.ts +2 -1
  13. package/dist/cli.js +190 -33
  14. package/dist/cli.js.map +6 -6
  15. package/dist/codesys.js +2148 -432
  16. package/dist/codesys.js.map +14 -11
  17. package/dist/elaborate-capture.js +7 -1
  18. package/dist/elaborate-capture.js.map +3 -3
  19. package/dist/index.js +877 -459
  20. package/dist/index.js.map +16 -15
  21. package/dist/ir.js +87 -23
  22. package/dist/ir.js.map +10 -9
  23. package/dist/project.js +42 -9
  24. package/dist/project.js.map +3 -3
  25. package/dist/telemetry.js +83 -0
  26. package/dist/telemetry.js.map +12 -0
  27. package/ir/core-model.ts +13 -0
  28. package/ir/core.ts +1 -0
  29. package/ir/errors.ts +20 -0
  30. package/ir/index.ts +1 -0
  31. package/ir/link.ts +17 -8
  32. package/ir/model.ts +39 -0
  33. package/ir/routine.ts +62 -29
  34. package/ir/types.ts +7 -1
  35. package/package.json +12 -6
  36. package/project/cli.ts +96 -6
  37. package/project/plant.ts +58 -9
  38. package/project/project.ts +56 -10
  39. package/src/frontend/async.ts +284 -195
  40. package/src/frontend/configuration.ts +7 -21
  41. package/src/frontend/const-functions.ts +44 -38
  42. package/src/frontend/elaborate/capture.ts +7 -0
  43. package/src/frontend/elaborate/index.ts +135 -61
  44. package/src/frontend/elaborate/layouts.ts +8 -0
  45. package/src/frontend/elaborate/model.ts +13 -0
  46. package/src/frontend/elaborate/specialize.ts +302 -111
  47. package/src/frontend/exposure.ts +28 -26
  48. package/src/frontend/positions.ts +272 -0
  49. package/src/frontend/promises.ts +52 -47
  50. package/src/frontend/services.ts +16 -26
  51. package/src/frontend/types.ts +14 -0
  52. package/src/frontend/typescript.ts +185 -65
  53. package/stdlib/telemetry.ts +72 -0
  54. package/types/telemetry.d.ts +44 -0
package/dist/codesys.js CHANGED
@@ -144,15 +144,257 @@ function direct(address) {
144
144
  return { kind: "direct", address };
145
145
  }
146
146
  // packages/compiler/backends/codesys/emit.ts
147
- import { defaultValue, instancedBlock as instancedBlock5, standardBlocks as standardBlocks2 } from "@tsplc/compiler/ir";
147
+ import {
148
+ defaultValue,
149
+ instancedBlock as instancedBlock6,
150
+ jobErrors as jobErrors2,
151
+ standardBlocks as standardBlocks3,
152
+ telemetryOperands as telemetryOperands3
153
+ } from "@tsplc/compiler/ir";
154
+ import { createHash } from "node:crypto";
155
+ import { serviceOfPath } from "@tsplc/server";
148
156
 
149
- // packages/compiler/backends/codesys/global-names.ts
150
- import { standardBlocks } from "@tsplc/compiler/ir";
157
+ // packages/compiler/backends/codesys/debug.ts
158
+ import { instancedBlock as instancedBlock3, nestedBodies as nestedBodies2 } from "@tsplc/compiler/ir";
159
+
160
+ // packages/compiler/backends/codesys/task-access.ts
161
+ import { instancedBlock, nestedBodies, telemetryOperands } from "@tsplc/compiler/ir";
162
+ function routineTasks(core, deployment) {
163
+ const tasks = new Map;
164
+ const types = new Map(core.types.map((type) => [type.id, type]));
165
+ const routines = new Map([...core.functions, ...core.blocks].map((routine) => [routine.id, routine]));
166
+ const variables = new Map([
167
+ ...core.variables,
168
+ ...core.functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
169
+ ...core.blocks.flatMap((block) => [
170
+ ...block.inputs,
171
+ ...block.outputs,
172
+ ...block.state,
173
+ ...block.locals
174
+ ])
175
+ ].map((variable) => [variable.id, variable]));
176
+ const programs = new Map(core.programs.map((program) => [program.name, program]));
177
+ for (const task of deployment.tasks)
178
+ for (const name of task.programs) {
179
+ const seen = new Set;
180
+ const visit = (id) => {
181
+ if (seen.has(id))
182
+ return;
183
+ seen.add(id);
184
+ tasks.set(id, tasks.has(id) && tasks.get(id) !== task.name ? undefined : task.name);
185
+ const inspect = (items) => {
186
+ for (const item of items) {
187
+ if (item.kind === "invoke")
188
+ visit(item.function);
189
+ if (item.kind === "blockUpdate") {
190
+ const block = instancedBlock(variables.get(item.instance).type, types);
191
+ if (block)
192
+ visit(block.block);
193
+ }
194
+ for (const body of nestedBodies(item))
195
+ inspect(body);
196
+ }
197
+ };
198
+ inspect(routines.get(id)?.body ?? []);
199
+ };
200
+ visit(programs.get(name).entry);
201
+ }
202
+ return tasks;
203
+ }
204
+ function schedulePrograms(core, tasks, report) {
205
+ const background = new Map;
206
+ for (const program of core.programs) {
207
+ if (!program.background)
208
+ continue;
209
+ const { priority, intervalNanoseconds } = program.background;
210
+ const name = `TsplcBackground_${priority}_${BigInt(intervalNanoseconds) / 1000000n}`;
211
+ const existing = background.get(name);
212
+ if (existing) {
213
+ existing.programs.push(program.name);
214
+ continue;
215
+ }
216
+ background.set(name, {
217
+ name,
218
+ priority,
219
+ intervalNanoseconds,
220
+ programs: [program.name]
221
+ });
222
+ }
223
+ return appendContinuations(core, [...tasks, ...background.values()], report);
224
+ }
225
+ function taskStorageOwnership(core, report) {
226
+ const owners = new Map;
227
+ const globals = new Map(core.variables.map((item) => [item.id, item]));
228
+ const functions = new Map(core.functions.map((item) => [item.id, item]));
229
+ const blocks = new Map(core.blocks.map((block) => [block.id, block.runtime?.kind]));
230
+ const runtimes = new Map(core.types.flatMap((type) => type.kind === "block" ? [[type.id, blocks.get(type.block)]] : []));
231
+ return (task, program) => {
232
+ const fn = functions.get(program.entry);
233
+ if (!fn)
234
+ throw new Error("Verified core has a missing entry.");
235
+ const worker = program.background?.worker;
236
+ const host = worker && core.variables.find((item) => item.name === worker && item.span.file === fn.span.file && runtimes.get(item.type) === "backgroundHost");
237
+ for (const id of accessedStorage(fn, core, host ? host.id : undefined)) {
238
+ const item = globals.get(id);
239
+ if (!item || item.storage === "constant" || runtimes.get(item.type) === "mailbox")
240
+ continue;
241
+ const ownsWorker = worker === item.name && item.span.file === fn.span.file;
242
+ if (program.background && (!ownsWorker || host && item.id === host.id))
243
+ report(`Background task ${program.name} accesses scan-owned storage ${item.name}; pass value snapshots through the mailbox.`, item.span);
244
+ const owner = owners.get(id);
245
+ if (owner && owner !== task)
246
+ report(`Storage ${item.name} is shared across cyclic tasks ${owner} and ${task}.`, item.span);
247
+ owners.set(id, task);
248
+ }
249
+ };
250
+ }
251
+ function accessedStorage(fn, core, scheduledHost) {
252
+ const scheduledCall = fn.body.find((item) => item.kind === "invoke" && item.instance === scheduledHost);
253
+ const result = new Set, seen = new Set;
254
+ const functions = new Map(core.functions.map((item) => [item.id, item]));
255
+ const blocks = new Map(core.blocks.map((item) => [item.id, item]));
256
+ const types = new Map(core.types.map((item) => [item.id, item]));
257
+ const variables = new Map([
258
+ ...core.variables,
259
+ ...core.functions.flatMap((item) => [...item.parameters, ...item.locals]),
260
+ ...core.blocks.flatMap((item) => [
261
+ ...item.inputs,
262
+ ...item.outputs,
263
+ ...item.state,
264
+ ...item.locals
265
+ ])
266
+ ].map((item) => [item.id, item]));
267
+ const path = (segments = []) => {
268
+ segments.forEach((segment) => {
269
+ if (segment.kind === "index")
270
+ expression(segment.value);
271
+ });
272
+ };
273
+ const expression = (value) => {
274
+ if (value.kind === "load") {
275
+ result.add(value.root);
276
+ path(value.path);
277
+ }
278
+ if (value.kind === "borrow") {
279
+ result.add(value.place.root);
280
+ path(value.place.path);
281
+ }
282
+ if (value.kind === "unary" || value.kind === "convert")
283
+ expression(value.operand);
284
+ if (value.kind === "binary") {
285
+ expression(value.left);
286
+ expression(value.right);
287
+ }
288
+ };
289
+ const body = (items) => {
290
+ for (const item of items) {
291
+ if (item.kind === "assign") {
292
+ result.add(item.root);
293
+ path(item.path);
294
+ expression(item.value);
295
+ }
296
+ if (item.kind === "if") {
297
+ expression(item.condition);
298
+ body(item.then);
299
+ body(item.else);
300
+ }
301
+ if (item.kind === "switch") {
302
+ expression(item.value);
303
+ for (const branch of item.cases)
304
+ body(branch.body);
305
+ body(item.fallback);
306
+ }
307
+ if (item.kind === "for") {
308
+ if (item.dynamic) {
309
+ expression(item.dynamic.start);
310
+ expression(item.dynamic.limit);
311
+ }
312
+ result.add(item.counter);
313
+ body(item.body);
314
+ }
315
+ if (item.kind === "return" && item.value)
316
+ expression(item.value);
317
+ if (item.kind === "telemetry")
318
+ telemetryOperands(item).forEach(expression);
319
+ if (item.kind === "invoke") {
320
+ if (item.instance && item !== scheduledCall)
321
+ result.add(item.instance);
322
+ if (item.index)
323
+ expression(item.index);
324
+ item.arguments.forEach(expression);
325
+ if (item.destination)
326
+ result.add(item.destination);
327
+ const called = functions.get(item.function);
328
+ if (called && !seen.has(called.id)) {
329
+ seen.add(called.id);
330
+ body(called.body);
331
+ }
332
+ }
333
+ if (item.kind === "blockUpdate") {
334
+ result.add(item.instance);
335
+ if (item.index)
336
+ expression(item.index);
337
+ Object.values(item.inputs).forEach(expression);
338
+ const variable = variables.get(item.instance);
339
+ if (!variable)
340
+ throw new Error("Missing verified instance during task planning.");
341
+ const type = instancedBlock(variable.type, types);
342
+ const block = type && blocks.get(type.block);
343
+ if (block && !seen.has(block.id)) {
344
+ seen.add(block.id);
345
+ body(block.body);
346
+ }
347
+ }
348
+ }
349
+ };
350
+ seen.add(fn.id);
351
+ body(fn.body);
352
+ return result;
353
+ }
354
+ function appendContinuations(core, tasks, report) {
355
+ const continuations = core.programs.flatMap((program) => program.continuation ? [{ name: program.name, scope: program.continuation }] : []);
356
+ if (!continuations.length)
357
+ return tasks;
358
+ const programs = new Map(core.programs.map((program) => [program.name, program]));
359
+ const functions = new Map(core.functions.map((routine) => [routine.id, routine]));
360
+ const placements = tasks.map((task) => {
361
+ const roots = new Set;
362
+ for (const name of task.programs) {
363
+ const program = programs.get(name);
364
+ if (!program || program.background)
365
+ continue;
366
+ const entry = functions.get(program.entry);
367
+ if (entry)
368
+ for (const id of accessedStorage(entry, core))
369
+ roots.add(id);
370
+ }
371
+ return { task, roots, additions: [] };
372
+ });
373
+ for (const { name, scope } of continuations) {
374
+ const root = core.variables.find((variable) => variable.name === scope.instance && variable.span.file === scope.file);
375
+ if (!root) {
376
+ report(`Missing continuation owner ${scope.instance}.`);
377
+ continue;
378
+ }
379
+ const owners = placements.filter(({ roots }) => roots.has(root.id));
380
+ const [owner] = owners;
381
+ if (!owner || owners.length !== 1) {
382
+ report(`Continuation owner ${scope.instance} must belong to exactly one caller task.`, root.span);
383
+ continue;
384
+ }
385
+ owner.additions.push(name);
386
+ }
387
+ return placements.map(({ task, additions }) => ({
388
+ ...task,
389
+ programs: task.programs.concat(additions)
390
+ }));
391
+ }
151
392
 
152
393
  // packages/compiler/backends/codesys/storage.ts
153
394
  import { basename } from "node:path";
154
- import { instancedBlock } from "@tsplc/compiler/ir";
155
- var moduleName = (variable) => basename(variable.span.file).replace(/\.[^.]+$/, "");
395
+ import { instancedBlock as instancedBlock2 } from "@tsplc/compiler/ir";
396
+ var moduleFile = (variable) => variable.id.slice(0, variable.id.indexOf(":"));
397
+ var moduleName = (variable) => basename(moduleFile(variable)).replace(/\.[^.]+$/, "");
156
398
  function storageLayout(core) {
157
399
  const types = new Map(core.types.map((type) => [type.id, type]));
158
400
  const blocks = new Map(core.blocks.map((block) => [block.id, block]));
@@ -165,7 +407,7 @@ function storageLayout(core) {
165
407
  if (!block)
166
408
  throw new Error("Missing verified block during retention planning.");
167
409
  const retained = block.state.some((field) => {
168
- const type = instancedBlock(field.type, types);
410
+ const type = instancedBlock2(field.type, types);
169
411
  return field.retain || type !== undefined && blockRetained(type.block);
170
412
  });
171
413
  retention.set(id, retained);
@@ -173,7 +415,7 @@ function storageLayout(core) {
173
415
  };
174
416
  const retainedBlocks = new Set(core.blocks.filter((block) => blockRetained(block.id)).map((block) => block.id));
175
417
  const retainedVariables = new Set([...core.variables, ...core.blocks.flatMap((block) => block.state)].filter((variable) => {
176
- const type = instancedBlock(variable.type, types);
418
+ const type = instancedBlock2(variable.type, types);
177
419
  return variable.retain || type !== undefined && retainedBlocks.has(type.block);
178
420
  }).map((variable) => variable.id));
179
421
  const groups = new Map;
@@ -181,7 +423,7 @@ function storageLayout(core) {
181
423
  if (variable.storage === "input" || variable.storage === "output")
182
424
  continue;
183
425
  const storage = variable.storage === "constant" ? "constants" : retainedVariables.has(variable.id) ? "retained" : "state";
184
- const id = `${variable.span.file}:${storage}`;
426
+ const id = `${moduleFile(variable)}:${storage}`;
185
427
  let group = groups.get(id);
186
428
  if (!group) {
187
429
  group = { id, module: moduleName(variable), storage, variables: [] };
@@ -192,43 +434,751 @@ function storageLayout(core) {
192
434
  return { retainedBlocks, retainedVariables, globalLists: [...groups.values()] };
193
435
  }
194
436
 
195
- // packages/compiler/backends/codesys/types.ts
196
- import { instancedBlock as instancedBlock2 } from "@tsplc/compiler/ir";
197
-
198
- // packages/compiler/backends/codesys/numeric.ts
199
- import {
200
- integerRange,
201
- floatMaximum,
202
- integerType
203
- } from "@tsplc/compiler/ir";
204
- function scalarLiteral(value, type) {
205
- if (value.kind === "bool")
206
- return value.value ? "TRUE" : "FALSE";
207
- if (value.kind === "integer")
208
- return `${type}#${value.value}`;
209
- if (value.kind === "float") {
210
- const text = Object.is(value.value, -0) ? "-0.0" : String(value.value).replace(/e/i, "E");
211
- return `${type}#${text}`;
437
+ // packages/compiler/backends/codesys/debug.ts
438
+ var temporary = (id) => id.includes(":temporary:");
439
+ var constantIndex = (value) => value.kind === "constant" && value.value.kind === "integer" ? Number(value.value.value) : undefined;
440
+ function blockInstances(core) {
441
+ const types = new Map(core.types.map((type) => [type.id, type]));
442
+ const blocks = new Map(core.blocks.map((block) => [block.id, block]));
443
+ const instances = new Map(core.blocks.map((block) => [block.id, []]));
444
+ const visit = (variable, path) => {
445
+ const type = types.get(variable.type);
446
+ const block = instancedBlock3(variable.type, types);
447
+ const declared = type.kind === "array" ? Array.from({ length: type.length }, (_, offset) => [
448
+ ...path,
449
+ { variable, index: type.lowerBound + offset }
450
+ ]) : [[...path, { variable }]];
451
+ for (const instance of declared) {
452
+ instances.get(block.block).push(instance);
453
+ for (const child of blocks.get(block.block).state)
454
+ if (instancedBlock3(child.type, types))
455
+ visit(child, instance);
456
+ }
457
+ };
458
+ for (const variable of core.variables)
459
+ if (instancedBlock3(variable.type, types))
460
+ visit(variable, []);
461
+ return instances;
462
+ }
463
+ function storagePath(root, path = []) {
464
+ const logical = root.storage === "input" || root.storage === "output";
465
+ if (!logical && root.storage !== "module" && root.storage !== "instance")
466
+ return;
467
+ let text = logical ? root.name : `${moduleName(root)}.${root.name}`;
468
+ for (const segment of path) {
469
+ if (segment.kind === "field") {
470
+ text += `.${segment.name}`;
471
+ continue;
472
+ }
473
+ const index = constantIndex(segment.value);
474
+ if (index === undefined)
475
+ return;
476
+ text += `[${index}]`;
212
477
  }
213
- throw new Error("Expected verified scalar constant");
478
+ return text;
214
479
  }
215
480
 
216
- class NumericLowering {
481
+ class DebugAnalysis {
482
+ core;
483
+ outputs;
484
+ tasks;
485
+ instances;
486
+ probes = new Map;
487
+ events = [];
488
+ writers;
489
+ jobSites = new Map;
490
+ decisions = new Map;
491
+ callSites = new Map;
492
+ carriers = new Set;
493
+ variables;
217
494
  types;
218
- allocate;
219
- objects = [];
220
- helpers = new Map;
221
- constructor(types, allocate) {
222
- this.types = types;
223
- this.allocate = allocate;
495
+ routines;
496
+ blocks;
497
+ routineWrites = new Map;
498
+ temporaries = new Map;
499
+ writerSites = 0;
500
+ constructor(core, deployment, settings, outputs) {
501
+ this.core = core;
502
+ this.outputs = outputs;
503
+ this.types = new Map(core.types.map((type) => [type.id, type]));
504
+ this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
505
+ this.routines = new Map([...core.functions, ...core.blocks].map((routine) => [routine.id, routine]));
506
+ this.variables = new Map([
507
+ ...core.variables,
508
+ ...core.functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
509
+ ...core.blocks.flatMap((block) => [
510
+ ...block.inputs,
511
+ ...block.outputs,
512
+ ...block.state,
513
+ ...block.locals
514
+ ])
515
+ ].map((variable) => [variable.id, variable]));
516
+ this.writers = outputs.map(() => []);
517
+ this.tasks = routineTasks(core, deployment);
518
+ this.instances = blockInstances(core);
519
+ this.findCarriers();
520
+ if (!settings)
521
+ return;
522
+ const routines = [...core.functions, ...core.blocks.filter((block) => !block.standard)];
523
+ for (const routine of routines)
524
+ this.countCalls(routine.body, 1);
525
+ for (const routine of routines)
526
+ this.walk(settings, routine, routine.body, [], []);
527
+ if (settings.trace)
528
+ for (const block of core.blocks) {
529
+ const { job } = block;
530
+ const task = this.tasks.get(block.id);
531
+ if (!job || !task || this.instances.get(block.id)?.length !== 1)
532
+ continue;
533
+ const site = (type, phase) => this.site({
534
+ kind: "job",
535
+ job: { block: block.id, phase },
536
+ path: job.name,
537
+ type,
538
+ span: job.span,
539
+ text: `${job.name}: ${phase}`,
540
+ task
541
+ });
542
+ this.jobSites.set(block.id, {
543
+ start: site("UINT", "started"),
544
+ completion: site("DINT", "finished")
545
+ });
546
+ }
224
547
  }
225
- prepare(value) {
226
- if (value.kind === "load") {
227
- value.path?.forEach((segment) => {
228
- if (segment.kind === "index")
229
- this.prepare(segment.value);
548
+ owningPath(variable) {
549
+ const type = this.types.get(variable.type);
550
+ const block = type?.kind === "block" ? this.blocks.get(type.block) : undefined;
551
+ if (!block?.job)
552
+ return;
553
+ const paths = this.instances.get(block.id).filter((path) => path.at(-1).variable.id === variable.id);
554
+ return paths.length === 1 ? paths[0] : undefined;
555
+ }
556
+ site(site) {
557
+ const id = this.events.length + 1;
558
+ this.events.push({ ...site, id, operands: site.operands ?? [] });
559
+ return id;
560
+ }
561
+ findCarriers() {
562
+ const carries = (id) => {
563
+ const block = this.blocks.get(id);
564
+ if (block.runtime?.kind === "http")
565
+ return true;
566
+ return block.state.some((child) => {
567
+ const type = instancedBlock3(child.type, this.types);
568
+ return type !== undefined && carries(type.block);
230
569
  });
231
- }
570
+ };
571
+ for (const block of this.core.blocks)
572
+ if (carries(block.id))
573
+ this.carriers.add(block.id);
574
+ }
575
+ placeType(root, path = []) {
576
+ let type = this.types.get(root.type);
577
+ for (const segment of path) {
578
+ if (segment.kind === "field" && type?.kind === "record")
579
+ type = this.types.get(type.fields.find((field) => field.name === segment.name).type);
580
+ else if (segment.kind === "index" && type?.kind === "array")
581
+ type = this.types.get(type.element);
582
+ else
583
+ return;
584
+ }
585
+ return type;
586
+ }
587
+ countCalls(items, weight) {
588
+ for (const item of items) {
589
+ if (item.kind === "invoke")
590
+ this.callSites.set(item.function, (this.callSites.get(item.function) ?? 0) + weight);
591
+ for (const body of nestedBodies2(item))
592
+ this.countCalls(body, item.kind === "for" ? 2 : weight);
593
+ }
594
+ }
595
+ writes(id) {
596
+ const cached = this.routineWrites.get(id);
597
+ if (cached)
598
+ return cached;
599
+ const result = new Set;
600
+ this.routineWrites.set(id, result);
601
+ for (const root of this.statementWrites(this.routines.get(id)?.body ?? []))
602
+ result.add(root);
603
+ return result;
604
+ }
605
+ statementWrites(items) {
606
+ const result = new Set;
607
+ for (const item of items) {
608
+ if (item.kind === "assign")
609
+ result.add(item.root);
610
+ if (item.kind === "for")
611
+ result.add(item.counter);
612
+ if (item.kind === "invoke") {
613
+ if (item.destination)
614
+ result.add(item.destination);
615
+ for (const argument of item.arguments)
616
+ if (argument.kind === "borrow")
617
+ result.add(argument.place.root);
618
+ for (const root of this.writes(item.function))
619
+ result.add(root);
620
+ }
621
+ if (item.kind === "blockUpdate") {
622
+ for (const input of Object.values(item.inputs))
623
+ if (input.kind === "borrow")
624
+ result.add(input.place.root);
625
+ const block = instancedBlock3(this.variables.get(item.instance).type, this.types);
626
+ if (block)
627
+ for (const root of this.writes(block.block))
628
+ result.add(root);
629
+ }
630
+ for (const body of nestedBodies2(item))
631
+ for (const root of this.statementWrites(body))
632
+ result.add(root);
633
+ }
634
+ return result;
635
+ }
636
+ walk(settings, routine, items, prefixes, guards) {
637
+ for (const [index, item] of items.entries()) {
638
+ const here = [...prefixes, items.slice(0, index)];
639
+ this.probe(settings, routine, item, here, guards);
640
+ const guard = (conditions) => [
641
+ ...guards,
642
+ { conditions, depth: here.length }
643
+ ];
644
+ if (item.kind === "if") {
645
+ this.walk(settings, routine, item.then, here, guard([item.condition]));
646
+ this.walk(settings, routine, item.else, here, guard([item.condition]));
647
+ }
648
+ if (item.kind === "switch")
649
+ for (const body of nestedBodies2(item))
650
+ this.walk(settings, routine, body, here, guard([item.value]));
651
+ if (item.kind === "for")
652
+ this.walk(settings, routine, item.body, here, guards);
653
+ }
654
+ }
655
+ probe(settings, routine, item, prefixes, guards) {
656
+ const task = this.tasks.get(routine.id);
657
+ const probes = [];
658
+ if (item.kind === "assign" && settings.writers) {
659
+ let site;
660
+ this.outputs.forEach((output, index) => {
661
+ const when = this.reaches(item.root, item.path ?? [], output);
662
+ if (!when)
663
+ return;
664
+ site ??= ++this.writerSites;
665
+ this.writers[index].push({ id: site, routine: routine.id, span: item.span });
666
+ probes.push({ kind: "writer", site, output: index, when });
667
+ });
668
+ }
669
+ if (settings.trace && task) {
670
+ if (item.kind === "assign") {
671
+ const root = this.variables.get(item.root);
672
+ const type = this.placeType(root, item.path);
673
+ const path = root.storage === "module" ? storagePath(root, item.path) : undefined;
674
+ if (type?.kind === "enum" && path) {
675
+ const operands = this.operands(routine, prefixes, guards, settings.trace);
676
+ const site = this.site({
677
+ kind: "state",
678
+ path,
679
+ routine: routine.id,
680
+ type: type.id,
681
+ span: item.span,
682
+ task,
683
+ operands
684
+ });
685
+ probes.push({ kind: "state", value: item.value, site, operands });
686
+ }
687
+ }
688
+ if (item.kind === "return" && item.value && "parameters" in routine && routine.result && this.callSites.get(routine.id) === 1) {
689
+ const type = this.types.get(routine.result);
690
+ if (type?.kind === "enum") {
691
+ const slot = this.decisions.get(routine.id) ?? this.decisions.size;
692
+ this.decisions.set(routine.id, slot);
693
+ const path = routine.origin?.instance ? `${routine.origin.instance}.${routine.origin.name.split(".").at(-1)}` : routine.origin?.name ?? routine.name;
694
+ const operands = this.operands(routine, prefixes, guards, settings.trace);
695
+ const site = this.site({
696
+ kind: "decision",
697
+ path,
698
+ routine: routine.id,
699
+ type: type.id,
700
+ span: item.span,
701
+ task,
702
+ operands
703
+ });
704
+ probes.push({ kind: "decision", value: item.value, site, slot, operands });
705
+ }
706
+ }
707
+ }
708
+ if (probes.length)
709
+ this.probes.set(item, probes);
710
+ }
711
+ reaches(root, path, output) {
712
+ if (root !== output.root.id)
713
+ return;
714
+ const when = [];
715
+ for (let index = 0;index < Math.min(path.length, output.segments.length); index++) {
716
+ const written = path[index], bound = output.segments[index];
717
+ if (written.kind === "field") {
718
+ if (bound.kind !== "field" || bound.name !== written.name)
719
+ return;
720
+ continue;
721
+ }
722
+ if (bound.kind !== "index")
723
+ return;
724
+ const value = constantIndex(written.value);
725
+ if (value === undefined)
726
+ when.push({ index: written.value, value: bound.value });
727
+ else if (value !== bound.value)
728
+ return;
729
+ }
730
+ return when;
731
+ }
732
+ definitions(routine) {
733
+ const cached = this.temporaries.get(routine.id);
734
+ if (cached)
735
+ return cached;
736
+ const definitions = new Map;
737
+ const define = (items) => {
738
+ for (const item of items) {
739
+ const target = item.kind === "assign" && !item.path?.length ? item.root : item.kind === "invoke" ? item.destination : undefined;
740
+ if (target && temporary(target))
741
+ definitions.set(target, [...definitions.get(target) ?? [], item]);
742
+ for (const body of nestedBodies2(item))
743
+ define(body);
744
+ }
745
+ };
746
+ define(routine.body);
747
+ this.temporaries.set(routine.id, definitions);
748
+ return definitions;
749
+ }
750
+ operands(routine, prefixes, guards, trace) {
751
+ const definitions = this.definitions(routine);
752
+ const result = [];
753
+ const seen = new Set;
754
+ for (const guard of [...guards].reverse()) {
755
+ const executed = new Set(prefixes.slice(0, guard.depth).flat());
756
+ const between = this.statementWrites(prefixes.slice(guard.depth).flat());
757
+ const add = (span, capture, read) => {
758
+ const kind = this.types.get(capture.type)?.kind;
759
+ const key = `${span.file}:${span.start}:${span.end}`;
760
+ if (seen.has(key) || !["bool", "enum", "integer", "bits"].includes(kind ?? ""))
761
+ return;
762
+ seen.add(key);
763
+ const path = read && storagePath(this.variables.get(read.root), read.path);
764
+ result.push({
765
+ capture,
766
+ span,
767
+ ...path && { path },
768
+ stable: !read || !between.has(read.root)
769
+ });
770
+ };
771
+ const direct = (value) => (value.path ?? []).every((segment) => segment.kind === "field" || constantIndex(segment.value) !== undefined);
772
+ const visit = (value, evaluated) => {
773
+ if (value.kind === "unary" || value.kind === "convert")
774
+ visit(value.operand, evaluated);
775
+ if (value.kind === "binary") {
776
+ visit(value.left, evaluated);
777
+ visit(value.right, evaluated);
778
+ }
779
+ if (value.kind !== "load")
780
+ return;
781
+ if (!temporary(value.root)) {
782
+ if (evaluated || direct(value))
783
+ add(value.span, value, value);
784
+ return;
785
+ }
786
+ const defined = definitions.get(value.root) ?? [];
787
+ if (defined.length !== 1) {
788
+ for (const item of defined)
789
+ if (item.kind === "assign")
790
+ visit(item.value, evaluated && executed.has(item));
791
+ return;
792
+ }
793
+ const item = defined[0];
794
+ const reached = evaluated && executed.has(item);
795
+ if (item.kind === "invoke") {
796
+ if (reached)
797
+ add(item.span, value);
798
+ return;
799
+ }
800
+ if (item.kind !== "assign")
801
+ return;
802
+ const source = item.value;
803
+ if (source.kind === "load" && !temporary(source.root)) {
804
+ const read = {
805
+ ...source,
806
+ type: value.type,
807
+ path: [...source.path ?? [], ...value.path ?? []]
808
+ };
809
+ if (reached)
810
+ add(source.span, value, read);
811
+ else if (direct(read))
812
+ add(source.span, read, read);
813
+ return;
814
+ }
815
+ visit(source, reached);
816
+ };
817
+ for (const condition of guard.conditions)
818
+ visit(condition, true);
819
+ }
820
+ return result.slice(0, trace.operands);
821
+ }
822
+ }
823
+
824
+ // packages/compiler/backends/codesys/manifest.ts
825
+ import { existsSync, readFileSync } from "node:fs";
826
+ import { isAbsolute, relative } from "node:path";
827
+ import { standardBlocks } from "@tsplc/compiler/ir";
828
+
829
+ class Sources {
830
+ root;
831
+ files = [];
832
+ loaded = new Map;
833
+ constructor(root) {
834
+ this.root = root;
835
+ }
836
+ load(file) {
837
+ if (this.loaded.has(file))
838
+ return this.loaded.get(file);
839
+ const path = relative(this.root, file);
840
+ const inside = !path.startsWith("..") && !isAbsolute(path) && !path.split(/[\\/]/).includes("node_modules");
841
+ let source;
842
+ if (inside && existsSync(file)) {
843
+ const text = readFileSync(file, "utf8");
844
+ const lines = [0];
845
+ for (let index = 0;index < text.length; index++)
846
+ if (text[index] === `
847
+ `)
848
+ lines.push(index + 1);
849
+ source = { text, lines };
850
+ }
851
+ this.loaded.set(file, source);
852
+ return source;
853
+ }
854
+ range(span) {
855
+ const source = this.load(span.file);
856
+ if (!source || span.end > source.text.length)
857
+ return;
858
+ const position = (offset) => {
859
+ let low = 0, high = source.lines.length - 1;
860
+ while (low < high) {
861
+ const middle = low + high + 1 >> 1;
862
+ if (source.lines[middle] <= offset)
863
+ low = middle;
864
+ else
865
+ high = middle - 1;
866
+ }
867
+ return { line: low + 1, column: offset - source.lines[low] + 1 };
868
+ };
869
+ const path = relative(this.root, span.file).replaceAll("\\", "/");
870
+ let file = this.files.indexOf(path);
871
+ if (file < 0)
872
+ file = this.files.push(path) - 1;
873
+ const start = position(span.start), end = position(span.end);
874
+ return { file, ...start, endLine: end.line, endColumn: end.column };
875
+ }
876
+ text(span) {
877
+ return this.load(span.file)?.text.slice(span.start, span.end);
878
+ }
879
+ }
880
+ var scalarTypes = {
881
+ bool: true,
882
+ integer: true,
883
+ bits: true,
884
+ float: true,
885
+ duration: true,
886
+ calendar: true
887
+ };
888
+ function debugTypes(types, target, blocks, fields, extras, sources) {
889
+ const name = (id) => id.split(":").at(-1);
890
+ return Object.fromEntries(types.map((type) => {
891
+ if (scalarTypes[type.kind])
892
+ return [type.id, { kind: "scalar", iec: type.id }];
893
+ switch (type.kind) {
894
+ case "string":
895
+ return [
896
+ type.id,
897
+ { kind: "scalar", iec: type.encoding === "utf8" ? "STRING" : "WSTRING" }
898
+ ];
899
+ case "enum":
900
+ return [
901
+ type.id,
902
+ {
903
+ kind: "enum",
904
+ name: name(type.id),
905
+ members: Object.fromEntries(type.members.map((member) => [member.name, Number(member.value)]))
906
+ }
907
+ ];
908
+ case "array":
909
+ return [
910
+ type.id,
911
+ { kind: "array", element: type.element, length: type.length, lower: type.lowerBound }
912
+ ];
913
+ case "record":
914
+ return [
915
+ type.id,
916
+ {
917
+ kind: "record",
918
+ name: name(type.id),
919
+ fields: type.fields.map((field) => ({
920
+ name: field.name,
921
+ target: target.field(type.id, field.name),
922
+ type: field.type
923
+ }))
924
+ }
925
+ ];
926
+ case "block": {
927
+ const block = blocks.get(type.block);
928
+ const native = block.standard && standardBlocks[block.standard];
929
+ const generated = Boolean(block.job || block.runtime);
930
+ const declaration = sources.range(block.span);
931
+ return [
932
+ type.id,
933
+ {
934
+ kind: "record",
935
+ name: block.job?.name ?? block.name,
936
+ ...declaration && { declaration },
937
+ fields: [
938
+ ...[...block.inputs, ...block.outputs, ...block.state].map((variable) => {
939
+ const declaration = !native && sources.range(variable.span);
940
+ return {
941
+ name: variable.name,
942
+ target: fields(block.id, variable.id),
943
+ type: variable.type,
944
+ ...declaration && { declaration },
945
+ ...generated && { generated: true }
946
+ };
947
+ }),
948
+ ...extras(block.id).map((field) => ({ ...field, generated: true }))
949
+ ]
950
+ }
951
+ ];
952
+ }
953
+ }
954
+ throw new Error(`Unsupported verified type ${type.id}`);
955
+ }));
956
+ }
957
+ var constantValue = (value) => {
958
+ switch (value.kind) {
959
+ case "integer":
960
+ return Number.isSafeInteger(Number(value.value)) ? Number(value.value) : value.value;
961
+ case "duration":
962
+ return `${BigInt(value.nanoseconds) / 1000000n}ms`;
963
+ case "array":
964
+ return value.items.map(constantValue);
965
+ case "record":
966
+ return Object.fromEntries(Object.entries(value.fields).map(([field, item]) => [field, constantValue(item)]));
967
+ default:
968
+ return value.value;
969
+ }
970
+ };
971
+ var constantTypes = {
972
+ bool: "BOOL",
973
+ integer: "LINT",
974
+ float: "LREAL",
975
+ duration: "TIME",
976
+ calendar: "DATE_AND_TIME",
977
+ string: "STRING",
978
+ array: "ARRAY",
979
+ record: "STRUCT"
980
+ };
981
+ var debugConstants = (folded, sources) => folded.map((item) => {
982
+ const declaration = sources.range(item.span);
983
+ return {
984
+ path: item.path,
985
+ type: item.type ?? constantTypes[item.value.kind],
986
+ value: constantValue(item.value),
987
+ ...declaration && { declaration }
988
+ };
989
+ });
990
+ var ioAddress = ({ catalog }, binding) => ("address" in binding) ? binding.address : catalog.devices.find((device) => device.id === binding.device)?.channels.find((item) => item.id === binding.channel)?.address;
991
+ function debugHardware(hardware, io, raw) {
992
+ const { catalog, config } = hardware;
993
+ const rows = Object.entries(config.io).flatMap(([key, binding]) => {
994
+ const held = io(key);
995
+ if (!held)
996
+ return [];
997
+ const address = ioAddress(hardware, binding);
998
+ return [
999
+ {
1000
+ path: key,
1001
+ ...held,
1002
+ direction: address?.startsWith("%Q") ? "output" : "input",
1003
+ ..."device" in binding && { device: binding.device, channel: binding.channel },
1004
+ ...address && { address },
1005
+ ...binding.inverted && { inverted: true },
1006
+ ...binding.shared && { shared: true }
1007
+ }
1008
+ ];
1009
+ });
1010
+ return {
1011
+ io: rows,
1012
+ devices: catalog.devices.map((device) => {
1013
+ const descriptor = catalog.descriptors.find((item) => item.file === device.descriptor);
1014
+ const network = config.devices[device.id]?.network;
1015
+ const bytes = raw(device.id);
1016
+ const status = {
1017
+ ...device.statusSymbols,
1018
+ ...hardware.tree && device.modbus && {
1019
+ "Modbus error": `${device.id}_Modbus.xError`,
1020
+ "Modbus error code": `${device.id}_Modbus.byModbusError`
1021
+ }
1022
+ };
1023
+ return {
1024
+ id: device.id,
1025
+ ...descriptor && {
1026
+ product: descriptor.name,
1027
+ vendor: descriptor.vendor,
1028
+ productCode: descriptor.productCode
1029
+ },
1030
+ ...network?.address && {
1031
+ network: {
1032
+ address: network.address,
1033
+ ...network.rpi && { rpiMs: Number(BigInt(network.rpi.nanoseconds)) / 1e6 }
1034
+ }
1035
+ },
1036
+ ...device.connection && { connection: device.connection.name },
1037
+ assemblies: device.assemblies.map((assembly) => ({
1038
+ direction: assembly.direction,
1039
+ bytes: assembly.size,
1040
+ address: assembly.address,
1041
+ ...bytes[assembly.direction] && { raw: bytes[assembly.direction] }
1042
+ })),
1043
+ ...hardware.tree && {
1044
+ health: {
1045
+ state: `${device.id}.eState`,
1046
+ diagnostic: `${device.id}.xDiagnosticAvailable`,
1047
+ message: `${device.id}.sDiagString`
1048
+ }
1049
+ },
1050
+ ...Object.keys(status).length && { status },
1051
+ channels: device.channels.filter((channel) => !channel.parent && !/^(inputs|outputs)\.Byte\d+$/.test(channel.id)).map((channel) => ({
1052
+ id: channel.id,
1053
+ name: channel.name,
1054
+ direction: channel.direction,
1055
+ type: channel.type,
1056
+ offsetBits: channel.offsetBits,
1057
+ bits: channel.bits,
1058
+ ...channel.address && { address: channel.address },
1059
+ ...channel.unit && { unit: channel.unit },
1060
+ ...channel.description && { description: channel.description }
1061
+ }))
1062
+ };
1063
+ })
1064
+ };
1065
+ }
1066
+
1067
+ // packages/compiler/backends/codesys/io-paths.ts
1068
+ import { ioLayout } from "@tsplc/typegen/hardware";
1069
+ var pathPattern = /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
1070
+ var isStoragePath = (key) => key.includes(".") || key.includes("[");
1071
+ function resolveStoragePath(core, key) {
1072
+ const match = pathPattern.exec(key);
1073
+ if (!match)
1074
+ return { error: `${key}: expected Module.variable followed by .field or [index].` };
1075
+ const [, module, name, rest] = match;
1076
+ const roots = core.variables.filter((item) => item.storage === "module" && item.name === name && moduleName(item) === module);
1077
+ if (roots.length !== 1)
1078
+ return {
1079
+ error: roots.length ? `${key}: ${module}.${name} is declared by more than one module named ${module}.` : `${key}: no mutable module variable ${module}.${name}.`
1080
+ };
1081
+ const root = roots[0];
1082
+ const types = new Map(core.types.map((type) => [type.id, type]));
1083
+ let type = types.get(root.type);
1084
+ const segments = [];
1085
+ for (const [, field, index] of rest.matchAll(/\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g)) {
1086
+ if (field !== undefined) {
1087
+ const member = type.kind === "record" ? type.fields.find((f) => f.name === field) : undefined;
1088
+ if (!member)
1089
+ return { error: `${key}: no field ${field}.` };
1090
+ segments.push({ kind: "field", record: type.id, name: field });
1091
+ type = types.get(member.type);
1092
+ } else {
1093
+ const value = Number(index);
1094
+ if (type.kind !== "array")
1095
+ return { error: `${key}: ${index} indexes a non-array value.` };
1096
+ if (value < type.lowerBound || value >= type.lowerBound + type.length)
1097
+ return {
1098
+ error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`
1099
+ };
1100
+ segments.push({ kind: "index", value });
1101
+ type = types.get(type.element);
1102
+ }
1103
+ }
1104
+ return { key, root, segments, type };
1105
+ }
1106
+ function iecSpelling(type, types) {
1107
+ if (type.kind === "bool" || type.kind === "integer" || type.kind === "bits" || type.kind === "float" || type.kind === "duration" || type.kind === "calendar")
1108
+ return type.id;
1109
+ if (type.kind !== "array")
1110
+ return;
1111
+ const element = iecSpelling(types.get(type.element), types);
1112
+ const upper = type.lowerBound + type.length - 1;
1113
+ return element && !element.startsWith("ARRAY") ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}` : undefined;
1114
+ }
1115
+ function ioTargets(core) {
1116
+ const types = new Map(core.types.map((type) => [type.id, type]));
1117
+ const targets = [];
1118
+ const add = (key, type) => {
1119
+ const layout = ioLayout(iecSpelling(type, types) ?? "");
1120
+ if (layout)
1121
+ targets.push({ key, layout });
1122
+ };
1123
+ const visit = (key, type) => {
1124
+ add(key, type);
1125
+ if (type.kind === "record")
1126
+ for (const field of type.fields)
1127
+ visit(`${key}.${field.name}`, types.get(field.type));
1128
+ if (type.kind === "array")
1129
+ visit(`${key}[` + "${number}" + "]", types.get(type.element));
1130
+ };
1131
+ for (const variable of core.variables) {
1132
+ if (variable.storage === "input" || variable.storage === "output")
1133
+ add(variable.name, types.get(variable.type));
1134
+ else if (variable.storage === "module")
1135
+ visit(`${moduleName(variable)}.${variable.name}`, types.get(variable.type));
1136
+ }
1137
+ return targets;
1138
+ }
1139
+ // packages/compiler/package.json
1140
+ var version = "0.2.17";
1141
+
1142
+ // packages/compiler/backends/codesys/global-names.ts
1143
+ import { standardBlocks as standardBlocks2 } from "@tsplc/compiler/ir";
1144
+
1145
+ // packages/compiler/backends/codesys/types.ts
1146
+ import { instancedBlock as instancedBlock4 } from "@tsplc/compiler/ir";
1147
+
1148
+ // packages/compiler/backends/codesys/numeric.ts
1149
+ import {
1150
+ integerRange,
1151
+ floatMaximum,
1152
+ integerType
1153
+ } from "@tsplc/compiler/ir";
1154
+ function scalarLiteral(value, type) {
1155
+ if (value.kind === "bool")
1156
+ return value.value ? "TRUE" : "FALSE";
1157
+ if (value.kind === "integer")
1158
+ return `${type}#${value.value}`;
1159
+ if (value.kind === "float") {
1160
+ const text = Object.is(value.value, -0) ? "-0.0" : String(value.value).replace(/e/i, "E");
1161
+ return `${type}#${text}`;
1162
+ }
1163
+ throw new Error("Expected verified scalar constant");
1164
+ }
1165
+
1166
+ class NumericLowering {
1167
+ types;
1168
+ allocate;
1169
+ objects = [];
1170
+ helpers = new Map;
1171
+ constructor(types, allocate) {
1172
+ this.types = types;
1173
+ this.allocate = allocate;
1174
+ }
1175
+ prepare(value) {
1176
+ if (value.kind === "load") {
1177
+ value.path?.forEach((segment) => {
1178
+ if (segment.kind === "index")
1179
+ this.prepare(segment.value);
1180
+ });
1181
+ }
232
1182
  if (value.kind === "borrow") {
233
1183
  value.place.path.forEach((segment) => {
234
1184
  if (segment.kind === "index")
@@ -505,11 +1455,11 @@ class CodesysTypes {
505
1455
  }
506
1456
  }
507
1457
  for (const type of types.values())
508
- if (type.kind === "array" && instancedBlock2(type.id, types))
1458
+ if (type.kind === "array" && instancedBlock4(type.id, types))
509
1459
  this.names.set(type.id, `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`);
510
1460
  const emitted = new Set;
511
1461
  const emit = (type) => {
512
- if (instancedBlock2(type.id, types) || !this.names.has(type.id) || emitted.has(type.id))
1462
+ if (instancedBlock4(type.id, types) || !this.names.has(type.id) || emitted.has(type.id))
513
1463
  return;
514
1464
  if (type.kind === "array")
515
1465
  emit(this.type(type.element));
@@ -530,7 +1480,8 @@ END_STRUCT
530
1480
  END_TYPE
531
1481
  `;
532
1482
  } else if (type.kind === "array") {
533
- declaration = `TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
1483
+ declaration = `${type.index ? `{attribute 'tsplc_keyed'}
1484
+ ` : ""}TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
534
1485
  END_TYPE
535
1486
  `;
536
1487
  } else if (type.kind === "string") {
@@ -648,7 +1599,7 @@ var planGlobalNames = (core, programNames = {}) => {
648
1599
  const typeMap = new Map(core.types.map((type) => [type.id, type]));
649
1600
  const blockNames = new Map(core.blocks.map((block) => [
650
1601
  block.id,
651
- block.standard ? standardBlocks[block.standard].native : names.allocateObject("FB", block.name)
1602
+ block.standard ? standardBlocks2[block.standard].native : names.allocateObject("FB", block.name)
652
1603
  ]));
653
1604
  for (const name of blockNames.values())
654
1605
  names.reserve(name);
@@ -672,83 +1623,11 @@ var planGlobalNames = (core, programNames = {}) => {
672
1623
 
673
1624
  // packages/compiler/backends/codesys/plan.ts
674
1625
  import {
675
- instancedBlock as instancedBlock4,
676
- isVerifiedCore
1626
+ instancedBlock as instancedBlock5,
1627
+ isVerifiedCore,
1628
+ telemetryOperands as telemetryOperands2
677
1629
  } from "@tsplc/compiler/ir";
678
- import { ioLayout as ioLayout2 } from "@tsplc/typegen/hardware";
679
-
680
- // packages/compiler/backends/codesys/io-paths.ts
681
- import { ioLayout } from "@tsplc/typegen/hardware";
682
- var pathPattern = /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
683
- var isStoragePath = (key) => key.includes(".") || key.includes("[");
684
- function resolveStoragePath(core, key) {
685
- const match = pathPattern.exec(key);
686
- if (!match)
687
- return { error: `${key}: expected Module.variable followed by .field or [index].` };
688
- const [, module, name, rest] = match;
689
- const roots = core.variables.filter((item) => item.storage === "module" && item.name === name && moduleName(item) === module);
690
- if (roots.length !== 1)
691
- return {
692
- error: roots.length ? `${key}: ${module}.${name} is declared by more than one module named ${module}.` : `${key}: no mutable module variable ${module}.${name}.`
693
- };
694
- const root = roots[0];
695
- const types = new Map(core.types.map((type) => [type.id, type]));
696
- let type = types.get(root.type);
697
- const segments = [];
698
- for (const [, field, index] of rest.matchAll(/\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g)) {
699
- if (field !== undefined) {
700
- const member = type.kind === "record" ? type.fields.find((f) => f.name === field) : undefined;
701
- if (!member)
702
- return { error: `${key}: no field ${field}.` };
703
- segments.push({ kind: "field", record: type.id, name: field });
704
- type = types.get(member.type);
705
- } else {
706
- const value = Number(index);
707
- if (type.kind !== "array")
708
- return { error: `${key}: ${index} indexes a non-array value.` };
709
- if (value < type.lowerBound || value >= type.lowerBound + type.length)
710
- return {
711
- error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`
712
- };
713
- segments.push({ kind: "index", value });
714
- type = types.get(type.element);
715
- }
716
- }
717
- return { key, root, segments, type };
718
- }
719
- function iecSpelling(type, types) {
720
- if (type.kind === "bool" || type.kind === "integer" || type.kind === "bits" || type.kind === "float")
721
- return type.id;
722
- if (type.kind !== "array")
723
- return;
724
- const element = iecSpelling(types.get(type.element), types);
725
- const upper = type.lowerBound + type.length - 1;
726
- return element && !element.startsWith("ARRAY") ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}` : undefined;
727
- }
728
- function ioTargets(core) {
729
- const types = new Map(core.types.map((type) => [type.id, type]));
730
- const targets = [];
731
- const add = (key, type) => {
732
- const layout = ioLayout(iecSpelling(type, types) ?? "");
733
- if (layout)
734
- targets.push({ key, layout });
735
- };
736
- const visit = (key, type) => {
737
- add(key, type);
738
- if (type.kind === "record")
739
- for (const field of type.fields)
740
- visit(`${key}.${field.name}`, types.get(field.type));
741
- if (type.kind === "array")
742
- visit(`${key}[` + "${number}" + "]", types.get(type.element));
743
- };
744
- for (const variable of core.variables) {
745
- if (variable.storage === "input" || variable.storage === "output")
746
- add(variable.name, types.get(variable.type));
747
- else if (variable.storage === "module")
748
- visit(`${moduleName(variable)}.${variable.name}`, types.get(variable.type));
749
- }
750
- return targets;
751
- }
1630
+ import { ioLayout as ioLayout2, ioScalarBits } from "@tsplc/typegen/hardware";
752
1631
 
753
1632
  // packages/compiler/backends/codesys/http.ts
754
1633
  var opcuaServiceCapacity = 16;
@@ -785,8 +1664,29 @@ var resolveHttpEndpoint = (value, input) => {
785
1664
  tls: url.protocol === "https:"
786
1665
  };
787
1666
  };
788
- var quote = (text) => "'" + text.replaceAll("$", "$$").replaceAll("'", "$'").replaceAll("\r", "$R").replaceAll(`
789
- `, "$N") + "'";
1667
+ var escapes = { $: "$$", "'": "$'", "\r": "$R", "\n": "$N" };
1668
+ var quote = (text) => `'${text.replace(/[$'\r\n]/g, (character) => escapes[character])}'`;
1669
+ var jsonScalar = (type, value) => {
1670
+ if (type.kind === "string" && type.encoding === "utf8" && type.capacity <= 2048)
1671
+ return { code: `WriteString(${value});`, size: type.capacity * 6 + 2 };
1672
+ if (type.kind === "bool")
1673
+ return { code: `IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`, size: 5 };
1674
+ if (type.kind === "bits") {
1675
+ const wide = type.bits <= 32 ? "UDINT" : "ULINT";
1676
+ return {
1677
+ code: `Append(${wide}_TO_STRING(TO_${wide}(${value})));`,
1678
+ size: String(2n ** BigInt(type.bits) - 1n).length
1679
+ };
1680
+ }
1681
+ if (type.kind === "integer") {
1682
+ const bits = BigInt(type.bits);
1683
+ return {
1684
+ code: `Append(${type.id}_TO_STRING(${value}));`,
1685
+ size: String(type.signed ? -(2n ** (bits - 1n)) : 2n ** bits - 1n).length
1686
+ };
1687
+ }
1688
+ return;
1689
+ };
790
1690
  var httpLayouts = (block, types) => {
791
1691
  const request = block.inputs.find((v) => v.name === "request"), response = block.outputs.find((v) => v.name === "result");
792
1692
  if (!request || !response)
@@ -796,17 +1696,12 @@ var httpLayouts = (block, types) => {
796
1696
  throw new Error("HTTP requires closed request/response records with 1..31 response fields.");
797
1697
  const scalarSize = (id) => {
798
1698
  const type = types.get(id);
799
- if (type?.kind === "string" && type.encoding === "utf8" && type.capacity <= 2048)
800
- return type.capacity * 6 + 2;
801
- if (type?.kind === "bool")
802
- return 5;
803
1699
  if (type?.kind === "enum")
804
1700
  return Math.max(...type.members.map((member) => member.value.length));
805
- if ((type?.kind === "integer" || type?.kind === "bits") && type.bits <= 32) {
806
- const signed = type.kind === "integer" && type.signed;
807
- return String(signed ? -(2 ** (type.bits - 1)) : 2 ** type.bits - 1).length;
808
- }
809
- throw new Error("HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.");
1701
+ const scalar = type && !((type.kind === "integer" || type.kind === "bits") && type.bits > 32) ? jsonScalar(type, "") : undefined;
1702
+ if (!scalar)
1703
+ throw new Error("HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.");
1704
+ return scalar.size;
810
1705
  };
811
1706
  const recordSize = (record, response) => 2 + record.fields.reduce((size, field) => {
812
1707
  const type = types.get(field.type);
@@ -820,7 +1715,7 @@ var httpLayouts = (block, types) => {
820
1715
  var validateHttpLayout = (block, types) => {
821
1716
  httpLayouts(block, types);
822
1717
  };
823
- var emitHttp = (block, name, fields, types, target, endpoint, network, rpcGlobal) => {
1718
+ var emitHttp = (block, name, fields, types, target, endpoint, network, rpcGlobal, trace) => {
824
1719
  const port = (label) => {
825
1720
  const variable = [...block.inputs, ...block.outputs].find((v) => v.name === label);
826
1721
  if (!variable)
@@ -833,16 +1728,11 @@ var emitHttp = (block, name, fields, types, target, endpoint, network, rpcGlobal
833
1728
  if (type.kind === "array")
834
1729
  return Array.from({ length: type.length }, (_, i) => `${i ? "Append(',');" : ""}${encode(type.element, `${value}[${i + type.lowerBound}]`)}`).join(`
835
1730
  `);
836
- if (type.kind === "string" && type.encoding === "utf8" && type.capacity <= 2048)
837
- return `WriteString(${value});`;
838
- if (type.kind === "bool")
839
- return `IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`;
840
1731
  if (type.kind === "enum")
841
1732
  return `Append(DINT_TO_STRING(TO_DINT(${value})));`;
842
- if (type.kind === "bits" && type.bits <= 32)
843
- return `Append(UDINT_TO_STRING(TO_UDINT(${value})));`;
844
- if (type.kind === "integer" && type.bits <= 32)
845
- return `Append(${target.name(typeId)}_TO_STRING(${value}));`;
1733
+ const scalar = jsonScalar(type, value);
1734
+ if (scalar)
1735
+ return scalar.code;
846
1736
  throw new Error("HTTP JSON supports bounded UTF-8 strings, BOOL, enums, integers up to 32 bits and fixed arrays.");
847
1737
  };
848
1738
  const requestCode = requestLayout.fields.map((field, i) => {
@@ -957,17 +1847,46 @@ IF stage=90 THEN
957
1847
  END_IF;`
958
1848
  };
959
1849
  }
960
- return {
1850
+ return nativeHttp({
961
1851
  id: block.id,
962
- kind: "functionBlock",
963
1852
  name,
964
- declaration: `FUNCTION_BLOCK ${name}
965
- VAR_INPUT
966
- ${inputs}
1853
+ ports: `VAR_INPUT
1854
+ ${inputs}${trace ? `
1855
+ ${trace.job} : UDINT;` : ""}
967
1856
  END_VAR
968
1857
  VAR_OUTPUT
969
1858
  ${outputs}
970
- END_VAR
1859
+ END_VAR`,
1860
+ port,
1861
+ endpoint,
1862
+ network,
1863
+ method: block.runtime?.kind === "http" ? block.runtime.method : "GET",
1864
+ json: block.runtime?.kind === "http" && block.runtime.json,
1865
+ body: block.runtime?.kind === "http" && block.runtime.json ? `Append('{'); ${requestCode} Append('}');` : "",
1866
+ decode: decodeResponse,
1867
+ ...trace && { trace }
1868
+ });
1869
+ };
1870
+ var nativeHttp = ({
1871
+ id,
1872
+ name,
1873
+ ports,
1874
+ port,
1875
+ endpoint,
1876
+ network,
1877
+ method,
1878
+ json,
1879
+ body,
1880
+ decode,
1881
+ trace
1882
+ }) => {
1883
+ const requestHeader = trace ? `AppendWire(UDINT_TO_STRING(${trace.job}));AppendWire(':');AppendWire(UDINT_TO_STRING(${trace.sequence}));AppendWire('$R$NContent-Length: ');` : "";
1884
+ return {
1885
+ id,
1886
+ kind: "functionBlock",
1887
+ name,
1888
+ declaration: `FUNCTION_BLOCK ${name}
1889
+ ${ports}
971
1890
  VAR
972
1891
  remoteAddress : NBS.IPv4Address;
973
1892
  remoteIP : NBS.IIPAddress := remoteAddress;
@@ -995,7 +1914,8 @@ VAR
995
1914
  numberValue : LINT;
996
1915
  wireUsed : UINT;
997
1916
  tokenUsed : UINT;
998
- index : UINT;
1917
+ index : UINT;${trace ? `
1918
+ ${trace.sequence} : UDINT;` : ""}
999
1919
  END_VAR
1000
1920
  `,
1001
1921
  implementation: `IF NOT ${port("start")} OR ${port("cancel")} THEN
@@ -1004,18 +1924,19 @@ END_VAR
1004
1924
  RETURN;
1005
1925
  END_IF;
1006
1926
  IF stage=0 THEN
1007
- payload:=''; malformed:=FALSE; used:=0; received:='';
1008
- ${block.runtime?.kind === "http" && block.runtime.json ? `Append('{'); ${requestCode} Append('}');` : ""}
1927
+ payload:=''; malformed:=FALSE; used:=0; received:='';${trace ? `
1928
+ ${trace.sequence}:=${trace.sequence}+1;` : ""}
1929
+ ${body}
1009
1930
  IF malformed THEN ${port("error")}:=3; stage:=90;
1010
1931
  ELSE
1011
1932
  wire:='';wireUsed:=0;
1012
- AppendWire(${quote((block.runtime?.kind === "http" ? block.runtime.method : "GET") + " " + endpoint.path + ` HTTP/1.1\r
1933
+ AppendWire(${quote(method + " " + endpoint.path + ` HTTP/1.1\r
1013
1934
  Host: ` + endpoint.authority + `\r
1014
1935
  ` + (endpoint.token ? "Authorization: Bearer " + endpoint.token + `\r
1015
- ` : "") + (block.runtime?.kind === "http" && block.runtime.json ? `Content-Type: application/json\r
1936
+ ` : "") + (json ? `Content-Type: application/json\r
1016
1937
  ` : "") + `Accept: application/json\r
1017
1938
  Connection: close\r
1018
- Content-Length: `)});
1939
+ ` + (trace ? "x-tsplc-request: " : "Content-Length: "))});${requestHeader}
1019
1940
  AppendWire(UINT_TO_STRING(ByteLength(payload)));AppendWire('$R$N$R$N');AppendWire(payload); stage:=10;
1020
1941
  END_IF;
1021
1942
  END_IF;
@@ -1054,7 +1975,7 @@ IF stage=3 THEN
1054
1975
  ELSIF TO_DINT(used)>=TO_DINT(headerEnd)+3+contentLength THEN
1055
1976
  IF status<200 OR status>=300 THEN ${port("error")}:=10000+status;stage:=90;
1056
1977
  ELSE
1057
- payload:='';IF contentLength>0 THEN FOR index:=0 TO TO_UINT(contentLength)-1 DO payload[index]:=received[headerEnd+3+index]; END_FOR;END_IF;payload[TO_UINT(contentLength)]:=0; ${decodeResponse}
1978
+ payload:='';IF contentLength>0 THEN FOR index:=0 TO TO_UINT(contentLength)-1 DO payload[index]:=received[headerEnd+3+index]; END_FOR;END_IF;payload[TO_UINT(contentLength)]:=0; ${decode}
1058
1979
  stage:=90;
1059
1980
  END_IF;
1060
1981
  END_IF;
@@ -1132,268 +2053,79 @@ lineStart:=1;
1132
2053
  WHILE lineStart<headerEnd DO
1133
2054
  lineEnd:=lineStart;WHILE lineEnd<headerEnd AND received[lineEnd-1]<>13 DO lineEnd:=lineEnd+1;END_WHILE;
1134
2055
  key:='';j:=0;i:=lineStart;
1135
- WHILE i<lineEnd AND received[i-1]<>58 AND j<63 DO octet:=received[i-1];IF octet>=65 AND octet<=90 THEN octet:=octet+32;END_IF;key[j]:=octet;j:=j+1;i:=i+1;END_WHILE;key[j]:=0;
1136
- IF key='transfer-encoding' THEN malformed:=TRUE;RETURN;END_IF;
1137
- IF key='content-length' THEN
1138
- IF found THEN malformed:=TRUE;RETURN;END_IF;found:=TRUE;contentLength:=0;digits:=0;i:=i+1;
1139
- WHILE i<lineEnd AND received[i-1]=32 DO i:=i+1;END_WHILE;
1140
- WHILE i<lineEnd DO octet:=received[i-1];IF octet<48 OR octet>57 OR digits>=5 THEN malformed:=TRUE;RETURN;END_IF;contentLength:=contentLength*10+TO_DINT(octet-48);digits:=digits+1;i:=i+1;END_WHILE;
1141
- IF digits=0 THEN malformed:=TRUE;RETURN;END_IF;
1142
- END_IF;
1143
- lineStart:=lineEnd+2;
1144
- END_WHILE;`),
1145
- method("WriteString", `VAR_INPUT value : STRING(2048); END_VAR
1146
- VAR i:UINT; one:STRING(1); hex:STRING(16):='0123456789abcdef'; END_VAR`, `Append('"');IF ByteLength(value)>0 THEN FOR i:=0 TO ByteLength(value)-1 DO
1147
- one[0]:=value[i];one[1]:=0;
1148
- IF value[i]=34 OR value[i]=92 THEN Append('\\');Append(one);
1149
- ELSIF value[i]<32 THEN Append('\\u00');one[0]:=hex[SHR(value[i],4)];Append(one);one[0]:=hex[value[i] AND 15];Append(one);
1150
- ELSE Append(one);END_IF;
1151
- END_FOR;END_IF;Append('"');`),
1152
- method("SkipWhitespace", "", `WHILE cursor<=TO_UINT(ByteLength(payload)) DO IF payload[cursor-1]<>32 AND payload[cursor-1]<>9 AND payload[cursor-1]<>10 AND payload[cursor-1]<>13 THEN EXIT;END_IF;cursor:=cursor+1;END_WHILE;`),
1153
- method("Expect", "VAR_INPUT value:BYTE; END_VAR", `IF cursor>TO_UINT(ByteLength(payload)) OR_ELSE payload[cursor-1]<>value THEN malformed:=TRUE;ELSE cursor:=cursor+1;END_IF;`),
1154
- method("TokenByte", "VAR_INPUT value:BYTE;END_VAR", `IF tokenUsed>=2048 OR value=0 THEN malformed:=TRUE;RETURN;END_IF;token[tokenUsed]:=value;tokenUsed:=tokenUsed+1;token[tokenUsed]:=0;`),
1155
- method("ReadHex", "VAR value:UDINT;i:UINT;octet:BYTE;END_VAR", `numberValue:=0;FOR i:=1 TO 4 DO
1156
- IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
1157
- octet:=payload[cursor-1];cursor:=cursor+1;
1158
- IF octet>=48 AND octet<=57 THEN value:=TO_UDINT(octet-48);ELSIF octet>=65 AND octet<=70 THEN value:=TO_UDINT(octet-55);ELSIF octet>=97 AND octet<=102 THEN value:=TO_UDINT(octet-87);ELSE malformed:=TRUE;RETURN;END_IF;
1159
- numberValue:=numberValue*16+TO_LINT(value);END_FOR;`),
1160
- method("ReadString", `VAR octet:BYTE;point:UDINT;high:UDINT;END_VAR`, `token:='';tokenUsed:=0;Expect(34);
1161
- WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
1162
- octet:=payload[cursor-1];cursor:=cursor+1;
1163
- IF octet=34 THEN ValidateUtf8();RETURN;END_IF;
1164
- IF octet=92 THEN
1165
- IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
1166
- octet:=payload[cursor-1];cursor:=cursor+1;
1167
- CASE octet OF
1168
- 34,47,92: TokenByte(octet);
1169
- 98:TokenByte(8);102:TokenByte(12);110:TokenByte(10);114:TokenByte(13);116:TokenByte(9);
1170
- 117:
1171
- ReadHex();point:=TO_UDINT(numberValue);
1172
- IF point>=55296 AND point<=56319 THEN
1173
- high:=point;Expect(92);Expect(117);ReadHex();
1174
- IF numberValue<56320 OR numberValue>57343 THEN malformed:=TRUE;RETURN;END_IF;
1175
- point:=65536+(high-55296)*1024+TO_UDINT(numberValue)-56320;
1176
- ELSIF point>=56320 AND point<=57343 THEN malformed:=TRUE;RETURN;END_IF;
1177
- IF point<128 THEN TokenByte(TO_BYTE(point));
1178
- ELSIF point<2048 THEN TokenByte(TO_BYTE(192+SHR(point,6)));TokenByte(TO_BYTE(128+(point AND 63)));
1179
- ELSIF point<65536 THEN TokenByte(TO_BYTE(224+SHR(point,12)));TokenByte(TO_BYTE(128+(SHR(point,6) AND 63)));TokenByte(TO_BYTE(128+(point AND 63)));
1180
- ELSE TokenByte(TO_BYTE(240+SHR(point,18)));TokenByte(TO_BYTE(128+(SHR(point,12) AND 63)));TokenByte(TO_BYTE(128+(SHR(point,6) AND 63)));TokenByte(TO_BYTE(128+(point AND 63)));END_IF;
1181
- ELSE malformed:=TRUE;RETURN;
1182
- END_CASE;
1183
- ELSIF octet<32 THEN malformed:=TRUE;RETURN;ELSE TokenByte(octet);END_IF;
1184
- END_WHILE;malformed:=TRUE;`),
1185
- method("ValidateUtf8", "VAR i:UINT;j:UINT;count:UINT;first:BYTE;next:BYTE;END_VAR", `i:=0;
1186
- WHILE i<tokenUsed AND NOT malformed DO
1187
- first:=token[i];
1188
- IF first<128 THEN i:=i+1;
1189
- ELSE
1190
- IF first>=194 AND first<=223 THEN count:=1;ELSIF first>=224 AND first<=239 THEN count:=2;ELSIF first>=240 AND first<=244 THEN count:=3;ELSE malformed:=TRUE;RETURN;END_IF;
1191
- IF i+count>=tokenUsed THEN malformed:=TRUE;RETURN;END_IF;
1192
- next:=token[i+1];
1193
- IF (first=224 AND next<160) OR (first=237 AND next>=160) OR (first=240 AND next<144) OR (first=244 AND next>=144) THEN malformed:=TRUE;RETURN;END_IF;
1194
- FOR j:=1 TO count DO IF token[i+j]<128 OR token[i+j]>191 THEN malformed:=TRUE;RETURN;END_IF;END_FOR;
1195
- i:=i+count+1;
1196
- END_IF;
1197
- END_WHILE;`),
1198
- method("ReadInteger", "VAR negative:BOOL;digits:UINT;octet:BYTE;END_VAR", `numberValue:=0;negative:=FALSE;digits:=0;
1199
- IF payload[cursor-1]=45 THEN negative:=TRUE;cursor:=cursor+1;END_IF;
1200
- WHILE cursor<=TO_UINT(ByteLength(payload)) DO
1201
- octet:=payload[cursor-1];IF octet<48 OR octet>57 THEN EXIT;END_IF;
1202
- IF digits>=10 THEN malformed:=TRUE;RETURN;END_IF;
1203
- IF digits>0 AND numberValue=0 THEN malformed:=TRUE;RETURN;END_IF;numberValue:=numberValue*10+TO_LINT(octet-48);digits:=digits+1;cursor:=cursor+1;
1204
- END_WHILE;
1205
- IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberValue;END_IF;`)
1206
- ].filter((item) => transport === "http" || !["AppendWire", "FindHeaders", "ReadHeaders"].includes(item.name));
1207
- };
1208
-
1209
- // packages/compiler/backends/codesys/task-access.ts
1210
- import { instancedBlock as instancedBlock3 } from "@tsplc/compiler/ir";
1211
- function schedulePrograms(core, tasks, report) {
1212
- const background = new Map;
1213
- for (const program of core.programs) {
1214
- if (!program.background)
1215
- continue;
1216
- const { priority, intervalNanoseconds } = program.background;
1217
- const name = `TsplcBackground_${priority}_${BigInt(intervalNanoseconds) / 1000000n}`;
1218
- const existing = background.get(name);
1219
- if (existing) {
1220
- existing.programs.push(program.name);
1221
- continue;
1222
- }
1223
- background.set(name, {
1224
- name,
1225
- priority,
1226
- intervalNanoseconds,
1227
- programs: [program.name]
1228
- });
1229
- }
1230
- return appendContinuations(core, [...tasks, ...background.values()], report);
1231
- }
1232
- function taskStorageOwnership(core, report) {
1233
- const owners = new Map;
1234
- const globals = new Map(core.variables.map((item) => [item.id, item]));
1235
- const functions = new Map(core.functions.map((item) => [item.id, item]));
1236
- const blocks = new Map(core.blocks.map((block) => [block.id, block.runtime?.kind]));
1237
- const runtimes = new Map(core.types.flatMap((type) => type.kind === "block" ? [[type.id, blocks.get(type.block)]] : []));
1238
- return (task, program) => {
1239
- const fn = functions.get(program.entry);
1240
- if (!fn)
1241
- throw new Error("Verified core has a missing entry.");
1242
- const worker = program.background?.worker;
1243
- const host = worker && core.variables.find((item) => item.name === worker && item.span.file === fn.span.file && runtimes.get(item.type) === "backgroundHost");
1244
- for (const id of accessedStorage(fn, core, host ? host.id : undefined)) {
1245
- const item = globals.get(id);
1246
- if (!item || item.storage === "constant" || runtimes.get(item.type) === "mailbox")
1247
- continue;
1248
- const ownsWorker = worker === item.name && item.span.file === fn.span.file;
1249
- if (program.background && (!ownsWorker || host && item.id === host.id))
1250
- report(`Background task ${program.name} accesses scan-owned storage ${item.name}; pass value snapshots through the mailbox.`, item.span);
1251
- const owner = owners.get(id);
1252
- if (owner && owner !== task)
1253
- report(`Storage ${item.name} is shared across cyclic tasks ${owner} and ${task}.`, item.span);
1254
- owners.set(id, task);
1255
- }
1256
- };
1257
- }
1258
- function accessedStorage(fn, core, scheduledHost) {
1259
- const scheduledCall = fn.body.find((item) => item.kind === "invoke" && item.instance === scheduledHost);
1260
- const result = new Set, seen = new Set;
1261
- const functions = new Map(core.functions.map((item) => [item.id, item]));
1262
- const blocks = new Map(core.blocks.map((item) => [item.id, item]));
1263
- const types = new Map(core.types.map((item) => [item.id, item]));
1264
- const variables = new Map([
1265
- ...core.variables,
1266
- ...core.functions.flatMap((item) => [...item.parameters, ...item.locals]),
1267
- ...core.blocks.flatMap((item) => [
1268
- ...item.inputs,
1269
- ...item.outputs,
1270
- ...item.state,
1271
- ...item.locals
1272
- ])
1273
- ].map((item) => [item.id, item]));
1274
- const path = (segments = []) => {
1275
- segments.forEach((segment) => {
1276
- if (segment.kind === "index")
1277
- expression(segment.value);
1278
- });
1279
- };
1280
- const expression = (value) => {
1281
- if (value.kind === "load") {
1282
- result.add(value.root);
1283
- path(value.path);
1284
- }
1285
- if (value.kind === "borrow") {
1286
- result.add(value.place.root);
1287
- path(value.place.path);
1288
- }
1289
- if (value.kind === "unary" || value.kind === "convert")
1290
- expression(value.operand);
1291
- if (value.kind === "binary") {
1292
- expression(value.left);
1293
- expression(value.right);
1294
- }
1295
- };
1296
- const body = (items) => {
1297
- for (const item of items) {
1298
- if (item.kind === "assign") {
1299
- result.add(item.root);
1300
- path(item.path);
1301
- expression(item.value);
1302
- }
1303
- if (item.kind === "if") {
1304
- expression(item.condition);
1305
- body(item.then);
1306
- body(item.else);
1307
- }
1308
- if (item.kind === "switch") {
1309
- expression(item.value);
1310
- for (const branch of item.cases)
1311
- body(branch.body);
1312
- body(item.fallback);
1313
- }
1314
- if (item.kind === "for") {
1315
- if (item.dynamic) {
1316
- expression(item.dynamic.start);
1317
- expression(item.dynamic.limit);
1318
- }
1319
- result.add(item.counter);
1320
- body(item.body);
1321
- }
1322
- if (item.kind === "return" && item.value)
1323
- expression(item.value);
1324
- if (item.kind === "invoke") {
1325
- if (item.instance && item !== scheduledCall)
1326
- result.add(item.instance);
1327
- if (item.index)
1328
- expression(item.index);
1329
- item.arguments.forEach(expression);
1330
- if (item.destination)
1331
- result.add(item.destination);
1332
- const called = functions.get(item.function);
1333
- if (called && !seen.has(called.id)) {
1334
- seen.add(called.id);
1335
- body(called.body);
1336
- }
1337
- }
1338
- if (item.kind === "blockUpdate") {
1339
- result.add(item.instance);
1340
- if (item.index)
1341
- expression(item.index);
1342
- Object.values(item.inputs).forEach(expression);
1343
- const variable = variables.get(item.instance);
1344
- if (!variable)
1345
- throw new Error("Missing verified instance during task planning.");
1346
- const type = instancedBlock3(variable.type, types);
1347
- const block = type && blocks.get(type.block);
1348
- if (block && !seen.has(block.id)) {
1349
- seen.add(block.id);
1350
- body(block.body);
1351
- }
1352
- }
1353
- }
1354
- };
1355
- seen.add(fn.id);
1356
- body(fn.body);
1357
- return result;
1358
- }
1359
- function appendContinuations(core, tasks, report) {
1360
- const continuations = core.programs.flatMap((program) => program.continuation ? [{ name: program.name, scope: program.continuation }] : []);
1361
- if (!continuations.length)
1362
- return tasks;
1363
- const programs = new Map(core.programs.map((program) => [program.name, program]));
1364
- const functions = new Map(core.functions.map((routine) => [routine.id, routine]));
1365
- const placements = tasks.map((task) => {
1366
- const roots = new Set;
1367
- for (const name of task.programs) {
1368
- const program = programs.get(name);
1369
- if (!program || program.background)
1370
- continue;
1371
- const entry = functions.get(program.entry);
1372
- if (entry)
1373
- for (const id of accessedStorage(entry, core))
1374
- roots.add(id);
1375
- }
1376
- return { task, roots, additions: [] };
1377
- });
1378
- for (const { name, scope } of continuations) {
1379
- const root = core.variables.find((variable) => variable.name === scope.instance && variable.span.file === scope.file);
1380
- if (!root) {
1381
- report(`Missing continuation owner ${scope.instance}.`);
1382
- continue;
1383
- }
1384
- const owners = placements.filter(({ roots }) => roots.has(root.id));
1385
- const [owner] = owners;
1386
- if (!owner || owners.length !== 1) {
1387
- report(`Continuation owner ${scope.instance} must belong to exactly one caller task.`, root.span);
1388
- continue;
1389
- }
1390
- owner.additions.push(name);
1391
- }
1392
- return placements.map(({ task, additions }) => ({
1393
- ...task,
1394
- programs: task.programs.concat(additions)
1395
- }));
1396
- }
2056
+ WHILE i<lineEnd AND received[i-1]<>58 AND j<63 DO octet:=received[i-1];IF octet>=65 AND octet<=90 THEN octet:=octet+32;END_IF;key[j]:=octet;j:=j+1;i:=i+1;END_WHILE;key[j]:=0;
2057
+ IF key='transfer-encoding' THEN malformed:=TRUE;RETURN;END_IF;
2058
+ IF key='content-length' THEN
2059
+ IF found THEN malformed:=TRUE;RETURN;END_IF;found:=TRUE;contentLength:=0;digits:=0;i:=i+1;
2060
+ WHILE i<lineEnd AND received[i-1]=32 DO i:=i+1;END_WHILE;
2061
+ WHILE i<lineEnd DO octet:=received[i-1];IF octet<48 OR octet>57 OR digits>=5 THEN malformed:=TRUE;RETURN;END_IF;contentLength:=contentLength*10+TO_DINT(octet-48);digits:=digits+1;i:=i+1;END_WHILE;
2062
+ IF digits=0 THEN malformed:=TRUE;RETURN;END_IF;
2063
+ END_IF;
2064
+ lineStart:=lineEnd+2;
2065
+ END_WHILE;`),
2066
+ method("WriteString", `VAR_INPUT value : STRING(2048); END_VAR
2067
+ VAR i:UINT; one:STRING(1); hex:STRING(16):='0123456789abcdef'; END_VAR`, `Append('"');IF ByteLength(value)>0 THEN FOR i:=0 TO ByteLength(value)-1 DO
2068
+ one[0]:=value[i];one[1]:=0;
2069
+ IF value[i]=34 OR value[i]=92 THEN Append('\\');Append(one);
2070
+ ELSIF value[i]<32 THEN Append('\\u00');one[0]:=hex[SHR(value[i],4)];Append(one);one[0]:=hex[value[i] AND 15];Append(one);
2071
+ ELSE Append(one);END_IF;
2072
+ END_FOR;END_IF;Append('"');`),
2073
+ method("SkipWhitespace", "", `WHILE cursor<=TO_UINT(ByteLength(payload)) DO IF payload[cursor-1]<>32 AND payload[cursor-1]<>9 AND payload[cursor-1]<>10 AND payload[cursor-1]<>13 THEN EXIT;END_IF;cursor:=cursor+1;END_WHILE;`),
2074
+ method("Expect", "VAR_INPUT value:BYTE; END_VAR", `IF cursor>TO_UINT(ByteLength(payload)) OR_ELSE payload[cursor-1]<>value THEN malformed:=TRUE;ELSE cursor:=cursor+1;END_IF;`),
2075
+ method("TokenByte", "VAR_INPUT value:BYTE;END_VAR", `IF tokenUsed>=2048 OR value=0 THEN malformed:=TRUE;RETURN;END_IF;token[tokenUsed]:=value;tokenUsed:=tokenUsed+1;token[tokenUsed]:=0;`),
2076
+ method("ReadHex", "VAR value:UDINT;i:UINT;octet:BYTE;END_VAR", `numberValue:=0;FOR i:=1 TO 4 DO
2077
+ IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
2078
+ octet:=payload[cursor-1];cursor:=cursor+1;
2079
+ IF octet>=48 AND octet<=57 THEN value:=TO_UDINT(octet-48);ELSIF octet>=65 AND octet<=70 THEN value:=TO_UDINT(octet-55);ELSIF octet>=97 AND octet<=102 THEN value:=TO_UDINT(octet-87);ELSE malformed:=TRUE;RETURN;END_IF;
2080
+ numberValue:=numberValue*16+TO_LINT(value);END_FOR;`),
2081
+ method("ReadString", `VAR octet:BYTE;point:UDINT;high:UDINT;END_VAR`, `token:='';tokenUsed:=0;Expect(34);
2082
+ WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
2083
+ octet:=payload[cursor-1];cursor:=cursor+1;
2084
+ IF octet=34 THEN ValidateUtf8();RETURN;END_IF;
2085
+ IF octet=92 THEN
2086
+ IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
2087
+ octet:=payload[cursor-1];cursor:=cursor+1;
2088
+ CASE octet OF
2089
+ 34,47,92: TokenByte(octet);
2090
+ 98:TokenByte(8);102:TokenByte(12);110:TokenByte(10);114:TokenByte(13);116:TokenByte(9);
2091
+ 117:
2092
+ ReadHex();point:=TO_UDINT(numberValue);
2093
+ IF point>=55296 AND point<=56319 THEN
2094
+ high:=point;Expect(92);Expect(117);ReadHex();
2095
+ IF numberValue<56320 OR numberValue>57343 THEN malformed:=TRUE;RETURN;END_IF;
2096
+ point:=65536+(high-55296)*1024+TO_UDINT(numberValue)-56320;
2097
+ ELSIF point>=56320 AND point<=57343 THEN malformed:=TRUE;RETURN;END_IF;
2098
+ IF point<128 THEN TokenByte(TO_BYTE(point));
2099
+ ELSIF point<2048 THEN TokenByte(TO_BYTE(192+SHR(point,6)));TokenByte(TO_BYTE(128+(point AND 63)));
2100
+ ELSIF point<65536 THEN TokenByte(TO_BYTE(224+SHR(point,12)));TokenByte(TO_BYTE(128+(SHR(point,6) AND 63)));TokenByte(TO_BYTE(128+(point AND 63)));
2101
+ ELSE TokenByte(TO_BYTE(240+SHR(point,18)));TokenByte(TO_BYTE(128+(SHR(point,12) AND 63)));TokenByte(TO_BYTE(128+(SHR(point,6) AND 63)));TokenByte(TO_BYTE(128+(point AND 63)));END_IF;
2102
+ ELSE malformed:=TRUE;RETURN;
2103
+ END_CASE;
2104
+ ELSIF octet<32 THEN malformed:=TRUE;RETURN;ELSE TokenByte(octet);END_IF;
2105
+ END_WHILE;malformed:=TRUE;`),
2106
+ method("ValidateUtf8", "VAR i:UINT;j:UINT;count:UINT;first:BYTE;next:BYTE;END_VAR", `i:=0;
2107
+ WHILE i<tokenUsed AND NOT malformed DO
2108
+ first:=token[i];
2109
+ IF first<128 THEN i:=i+1;
2110
+ ELSE
2111
+ IF first>=194 AND first<=223 THEN count:=1;ELSIF first>=224 AND first<=239 THEN count:=2;ELSIF first>=240 AND first<=244 THEN count:=3;ELSE malformed:=TRUE;RETURN;END_IF;
2112
+ IF i+count>=tokenUsed THEN malformed:=TRUE;RETURN;END_IF;
2113
+ next:=token[i+1];
2114
+ IF (first=224 AND next<160) OR (first=237 AND next>=160) OR (first=240 AND next<144) OR (first=244 AND next>=144) THEN malformed:=TRUE;RETURN;END_IF;
2115
+ FOR j:=1 TO count DO IF token[i+j]<128 OR token[i+j]>191 THEN malformed:=TRUE;RETURN;END_IF;END_FOR;
2116
+ i:=i+count+1;
2117
+ END_IF;
2118
+ END_WHILE;`),
2119
+ method("ReadInteger", "VAR negative:BOOL;digits:UINT;octet:BYTE;END_VAR", `numberValue:=0;negative:=FALSE;digits:=0;
2120
+ IF payload[cursor-1]=45 THEN negative:=TRUE;cursor:=cursor+1;END_IF;
2121
+ WHILE cursor<=TO_UINT(ByteLength(payload)) DO
2122
+ octet:=payload[cursor-1];IF octet<48 OR octet>57 THEN EXIT;END_IF;
2123
+ IF digits>=10 THEN malformed:=TRUE;RETURN;END_IF;
2124
+ IF digits>0 AND numberValue=0 THEN malformed:=TRUE;RETURN;END_IF;numberValue:=numberValue*10+TO_LINT(octet-48);digits:=digits+1;cursor:=cursor+1;
2125
+ END_WHILE;
2126
+ IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberValue;END_IF;`)
2127
+ ].filter((item) => transport === "http" || !["AppendWire", "FindHeaders", "ReadHeaders"].includes(item.name));
2128
+ };
1397
2129
 
1398
2130
  // packages/compiler/backends/codesys/publication.ts
1399
2131
  var globals = (core) => core.variables.filter((variable) => variable.storage === "module" && variable.exported);
@@ -1421,7 +2153,7 @@ var resolvePublication = (core, policy) => {
1421
2153
  errors.push(`Unknown publication selector ${selector}; select an exported mutable global or its module.`);
1422
2154
  continue;
1423
2155
  }
1424
- if (new Set(candidates.map((variable) => variable.span.file)).size !== 1) {
2156
+ if (new Set(candidates.map(moduleFile)).size !== 1) {
1425
2157
  errors.push(`Ambiguous publication selector ${selector}.`);
1426
2158
  continue;
1427
2159
  }
@@ -1437,6 +2169,436 @@ var resolvePublication = (core, policy) => {
1437
2169
  return { publication, errors };
1438
2170
  };
1439
2171
 
2172
+ // packages/compiler/backends/codesys/telemetry.ts
2173
+ import {
2174
+ errorName,
2175
+ httpErrors,
2176
+ jobErrors,
2177
+ nestedBodies as nestedBodies3
2178
+ } from "@tsplc/compiler/ir";
2179
+ import { telemetrySchema } from "@tsplc/config";
2180
+ var telemetryClient = "tsplc:telemetry";
2181
+ var telemetryPath = "/tsplc/telemetry";
2182
+ var sendIntervalMs = 200;
2183
+ var batchBytes = 2048;
2184
+ var taskBytes = 64;
2185
+ var json = (value) => JSON.stringify(value).replace(/[^ -~]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
2186
+ var generated = (name) => name.startsWith("tsplc");
2187
+ var maximum = (values) => values.reduce((a, b) => Math.max(a, b), 0);
2188
+ var commitSize = ',"scan":,"time":}'.length + 2 * 10;
2189
+ var errorNames = Object.entries(jobErrors).filter(([code]) => Number(code) < httpErrors.base);
2190
+ var codeSize = ',"code":'.length + 10 + ',"name":'.length + maximum([...errorNames.map(([, name]) => json(name).length), json("HTTP 999").length]);
2191
+ function valueSize(type, text) {
2192
+ if (text && type.kind === "array")
2193
+ return type.length * 6 + 2;
2194
+ if (type.kind === "enum")
2195
+ return maximum([4, ...type.members.map((member) => json(member.text ?? member.name).length)]);
2196
+ if (type.kind === "float")
2197
+ return type.bits === 32 ? 16 : 25;
2198
+ const scalar = jsonScalar(type, "");
2199
+ if (!scalar)
2200
+ throw new Error(`Unverified telemetry value type ${type.id}.`);
2201
+ return scalar.size;
2202
+ }
2203
+ var traceRecord = (operands) => ({
2204
+ prefix: '{"kind":"trace","site":',
2205
+ size: '{"kind":"trace","site":,"value":,"operands":[]'.length + 5 + 11 + operands * 12 + commitSize
2206
+ });
2207
+ function planTelemetry(core, deployment, options, project, report) {
2208
+ const types = new Map(core.types.map((type) => [type.id, type]));
2209
+ const routines = [...core.functions, ...core.blocks.filter((block) => !block.standard)];
2210
+ const statements = [];
2211
+ const find = (routine, items) => {
2212
+ for (const item of items) {
2213
+ if (item.kind === "telemetry")
2214
+ statements.push({ routine, call: item });
2215
+ for (const body of nestedBodies3(item))
2216
+ find(routine, body);
2217
+ }
2218
+ };
2219
+ for (const routine of routines)
2220
+ find(routine.id, routine.body);
2221
+ if (!statements.length && !project.telemetry && !project.trace)
2222
+ return {};
2223
+ const settings = project.telemetry ?? telemetrySchema.parse({});
2224
+ const sources = new Sources(project.root);
2225
+ const location = (span) => {
2226
+ const range = sources.range(span);
2227
+ return range ? `${sources.files[range.file]}:${range.line}` : "";
2228
+ };
2229
+ const tasks = routineTasks(core, deployment);
2230
+ const tooLarge = (size, what, span) => {
2231
+ if (size > settings.recordBytes)
2232
+ report(`${what} can take ${size} bytes of JSON, more than telemetry.recordBytes (${settings.recordBytes}). Use fewer or shorter properties, smaller STRING or byte array bounds, or raise recordBytes.`, span);
2233
+ };
2234
+ const calls = new Map;
2235
+ for (const { routine, call } of statements) {
2236
+ const task = tasks.get(routine);
2237
+ if (!task) {
2238
+ report("Telemetry calls must be in code that one task runs: each task writes its own records.", call.span);
2239
+ continue;
2240
+ }
2241
+ const source = json(location(call.span));
2242
+ const { record } = call;
2243
+ const head = record.kind === "event" ? `{"kind":"event","event":${json(record.event)}` : record.kind === "log" ? `{"kind":"log","level":"${record.level}","message":${json(record.message)}` : '{"kind":"exception","handled":true';
2244
+ const prefix = `${head},"source":${source},"properties":{`;
2245
+ const size = prefix.length + call.properties.reduce((total, { name, value, length }, index) => total + (index ? 1 : 0) + json(name).length + 1 + valueSize(types.get(value.type), length !== undefined), 0) + 1 + (record.kind === "exception" ? codeSize : 0) + commitSize;
2246
+ tooLarge(size, "This telemetry record", call.span);
2247
+ calls.set(call, { id: calls.size + 1, task, record: prefix, call });
2248
+ }
2249
+ const failures = new Map;
2250
+ const blocks = new Map(core.blocks.map((block) => [block.id, block]));
2251
+ const instances = blockInstances(core);
2252
+ const awaited = (path) => path.slice(0, -1).some(({ variable }) => {
2253
+ const type = types.get(variable.type);
2254
+ const element = type?.kind === "array" ? types.get(type.element) : type;
2255
+ return element?.kind === "block" && blocks.get(element.block)?.job;
2256
+ });
2257
+ for (const block of core.blocks) {
2258
+ const { job } = block;
2259
+ const task = tasks.get(block.id);
2260
+ const paths = instances.get(block.id);
2261
+ if (!job || !task || !paths.length || paths.some(awaited))
2262
+ continue;
2263
+ const children = block.state.flatMap((child) => {
2264
+ const type = types.get(child.type);
2265
+ const called = type?.kind === "block" ? blocks.get(type.block)?.job : undefined;
2266
+ return called && !generated(called.name) ? [called] : [];
2267
+ });
2268
+ const named = generated(job.name) && children.length === 1 ? children[0] : job;
2269
+ const fallback = location(job.span);
2270
+ const steps = new Map;
2271
+ for (const step of job.steps) {
2272
+ const source = location(step.span) || fallback;
2273
+ steps.set(source, [...steps.get(source) ?? [], step.step]);
2274
+ }
2275
+ const record = `{"kind":"exception","handled":false,"function":${json(named.name)},${named.instance ? `"instance":${json(named.instance)},` : ""}"properties":{}`;
2276
+ tooLarge(record.length + codeSize + ',"source":""'.length + maximum([...steps.keys(), fallback].map((source) => json(source).length - 2)) + commitSize, `The failure record of ${named.name}`, job.span);
2277
+ failures.set(block.id, {
2278
+ id: failures.size + 1,
2279
+ task,
2280
+ record,
2281
+ sources: [...steps].map(([source, numbers]) => ({ source, steps: numbers }))
2282
+ });
2283
+ }
2284
+ if (project.trace)
2285
+ tooLarge(traceRecord(project.trace.operands).size, "A debug.trace record with its operands");
2286
+ const server = project.server;
2287
+ const base = server?.baseUrlEnv && process.env[server.baseUrlEnv];
2288
+ if (server?.transport === "opcua") {
2289
+ report(`Telemetry posts to the app server's ${telemetryPath} over HTTP; set server.transport to "http".`);
2290
+ return {};
2291
+ }
2292
+ if (!base) {
2293
+ report(`Telemetry posts to the app server: set server.baseUrlEnv and that environment variable to its base URL.`);
2294
+ return {};
2295
+ }
2296
+ try {
2297
+ return {
2298
+ telemetry: {
2299
+ ...settings,
2300
+ capacity: Math.max(settings.capacity, project.trace ? project.trace.capacity : 0),
2301
+ calls,
2302
+ failures,
2303
+ ...project.trace && { traceOperands: project.trace.operands }
2304
+ },
2305
+ endpoint: resolveHttpEndpoint(`${base.replace(/\/+$/, "")}${telemetryPath}`, options.http)
2306
+ };
2307
+ } catch (cause) {
2308
+ report(cause instanceof Error ? cause.message : String(cause));
2309
+ return {};
2310
+ }
2311
+ }
2312
+ var callParameters = ({ record, properties }) => [
2313
+ ...properties.flatMap(({ value, length }, index) => [
2314
+ { name: `p${index}`, value, text: length !== undefined },
2315
+ ...length ? [{ name: `p${index}Length`, value: length, text: false }] : []
2316
+ ]),
2317
+ ...record.kind === "exception" ? [{ name: "code", value: record.code, text: false }] : []
2318
+ ];
2319
+ var header = (build) => ({
2320
+ start: `{"build":${json(build)},"task":"`,
2321
+ rest: ['","now":', ',"scan":', ',"first":', ',"dropped":', ',"records":[']
2322
+ });
2323
+ var batchRecords = (recordBytes) => {
2324
+ const { start, rest } = header("0".repeat(16));
2325
+ const fixed = start.length + taskBytes + rest.join("").length + 2 * 10 + 2 * 20 + "]}".length;
2326
+ return Math.max(1, Math.floor((batchBytes - fixed) / (recordBytes + 1)));
2327
+ };
2328
+ function telemetryObjects({
2329
+ plan,
2330
+ names,
2331
+ target,
2332
+ endpoint,
2333
+ network,
2334
+ build,
2335
+ types
2336
+ }) {
2337
+ const writer = "tsplc:telemetryWriter";
2338
+ const { capacity, recordBytes } = plan;
2339
+ const method = (name, declaration, implementation, access = "") => ({
2340
+ id: `${writer}:${name}`,
2341
+ parent: writer,
2342
+ kind: "method",
2343
+ name,
2344
+ declaration: `METHOD ${access}${name}
2345
+ ${declaration}`,
2346
+ implementation
2347
+ });
2348
+ const encode = (type, parameter, text) => {
2349
+ if (text && type.kind === "array")
2350
+ return `WriteText(ADR(${parameter}), LINT_TO_DINT(LIMIT(0, TO_LINT(${parameter}Length), ${type.length})));`;
2351
+ if (type.kind === "enum")
2352
+ return `CASE ${parameter} OF ${type.members.map((member) => `${target.name(type.id)}.${target.field(type.id, member.name)}: Append(${quote(json(member.text ?? member.name))});`).join(" ")} ELSE Append('null'); END_CASE;`;
2353
+ if (type.kind === "float") {
2354
+ const iec = type.bits === 32 ? "REAL" : "LREAL";
2355
+ return `IF ${parameter} = ${parameter} AND ABS(${parameter}) < ${iec}#${type.bits === 32 ? "3.4E38" : "1.7E308"} THEN Append(${iec}_TO_STRING(${parameter})); ELSE Append('null'); END_IF;`;
2356
+ }
2357
+ return jsonScalar(type, parameter).code;
2358
+ };
2359
+ const calls = [...plan.calls.values()].map(({ id, record, call }) => {
2360
+ const parameters = callParameters(call);
2361
+ const inputs = parameters.filter((parameter) => !parameter.text);
2362
+ const references = parameters.filter((parameter) => parameter.text);
2363
+ const properties = call.properties.map(({ name, value, length }, index) => {
2364
+ const code = encode(types.get(value.type), `p${index}`, length !== undefined);
2365
+ return `Append(${quote(`${index ? "," : ""}${json(name)}:`)});
2366
+ ${code}`;
2367
+ });
2368
+ return method(`Record${id}`, [
2369
+ ...inputs.length ? [
2370
+ "VAR_INPUT",
2371
+ ...inputs.map((input) => ` ${input.name} : ${target.name(input.value.type)};`),
2372
+ "END_VAR"
2373
+ ] : [],
2374
+ ...references.length ? [
2375
+ "VAR_IN_OUT",
2376
+ ...references.map((input) => ` ${input.name} : ${target.name(input.value.type)};`),
2377
+ "END_VAR"
2378
+ ] : []
2379
+ ].map((line) => `${line}
2380
+ `).join(""), [
2381
+ "payload := '';",
2382
+ `Append(${quote(record)});`,
2383
+ ...properties,
2384
+ "Append('}');",
2385
+ ...call.record.kind === "exception" ? [`Append(',"code":');`, "Append(UDINT_TO_STRING(code));", "ErrorName(code);"] : [],
2386
+ "Commit();"
2387
+ ].join(`
2388
+ `) + `
2389
+ `);
2390
+ });
2391
+ const failures = [...plan.failures.values()].map(({ id, record, sources }) => method(`Failure${id}`, `VAR_INPUT
2392
+ code : UDINT;
2393
+ step : UINT;
2394
+ END_VAR
2395
+ `, [
2396
+ "payload := '';",
2397
+ `Append(${quote(`${record},"code":`)});`,
2398
+ "Append(UDINT_TO_STRING(code));",
2399
+ "ErrorName(code);",
2400
+ `Append(',"source":"');`,
2401
+ "CASE step OF",
2402
+ ...sources.map(({ source, steps }) => `${steps.join(", ")}: Append(${quote(json(source).slice(1, -1))});`),
2403
+ "END_CASE;",
2404
+ `Append('"');`,
2405
+ "Commit();"
2406
+ ].join(`
2407
+ `) + `
2408
+ `));
2409
+ const operands = plan.traceOperands;
2410
+ const trace = operands === undefined ? [] : [
2411
+ method("Trace", [
2412
+ "VAR_INPUT",
2413
+ " site : UINT;",
2414
+ " value : DINT;",
2415
+ " operands : USINT;",
2416
+ ...Array.from({ length: operands }, (_, index) => ` operand${index} : DINT;`),
2417
+ "END_VAR"
2418
+ ].join(`
2419
+ `) + `
2420
+ `, [
2421
+ "payload := '';",
2422
+ `Append(${quote(traceRecord(operands).prefix)});`,
2423
+ "Append(UINT_TO_STRING(site));",
2424
+ `Append(',"value":');`,
2425
+ "Append(DINT_TO_STRING(value));",
2426
+ `Append(',"operands":[');`,
2427
+ ...Array.from({ length: operands }, (_, index) => `IF operands > ${index} THEN ${index ? "Append(','); " : ""}Append(DINT_TO_STRING(operand${index})); END_IF;`),
2428
+ "Append(']');",
2429
+ "Commit();"
2430
+ ].join(`
2431
+ `) + `
2432
+ `)
2433
+ ];
2434
+ const { start, rest } = header(build);
2435
+ const helpers = httpMethods(writer).filter((item) => ["ByteLength", "Append", "WriteString"].includes(item.name));
2436
+ const client = nativeHttp({
2437
+ id: telemetryClient,
2438
+ name: names.client,
2439
+ ports: `VAR_INPUT
2440
+ start : BOOL;
2441
+ cancel : BOOL;
2442
+ END_VAR
2443
+ VAR_IN_OUT
2444
+ body : STRING(2048);
2445
+ END_VAR
2446
+ VAR_OUTPUT
2447
+ busy : BOOL;
2448
+ done : BOOL;
2449
+ error : UDINT;
2450
+ END_VAR`,
2451
+ port: (label) => label,
2452
+ endpoint,
2453
+ network,
2454
+ method: "POST",
2455
+ json: true,
2456
+ body: "Append(body);",
2457
+ decode: ""
2458
+ });
2459
+ return [
2460
+ {
2461
+ id: "tsplc:telemetryRecord",
2462
+ kind: "dataType",
2463
+ name: names.record,
2464
+ declaration: `TYPE ${names.record} :
2465
+ STRUCT
2466
+ sequence : ULINT;
2467
+ json : STRING(${recordBytes});
2468
+ END_STRUCT
2469
+ END_TYPE
2470
+ `
2471
+ },
2472
+ {
2473
+ id: writer,
2474
+ kind: "functionBlock",
2475
+ name: names.writer,
2476
+ declaration: `FUNCTION_BLOCK ${names.writer}
2477
+ VAR_INPUT
2478
+ task : STRING(${taskBytes});
2479
+ END_VAR
2480
+ VAR_OUTPUT
2481
+ scan : UDINT;
2482
+ now : UDINT;
2483
+ END_VAR
2484
+ VAR
2485
+ head : ULINT;
2486
+ sent : ULINT;
2487
+ dropped : ULINT;
2488
+ records : ARRAY[0..${capacity - 1}] OF ${names.record};
2489
+ payload : STRING(2048);
2490
+ malformed : BOOL;
2491
+ text : STRING(${recordBytes});
2492
+ batch : STRING(2048);
2493
+ batched : ULINT;
2494
+ sending : BOOL;
2495
+ lastSend : UDINT;
2496
+ client : ${names.client};
2497
+ END_VAR
2498
+ `,
2499
+ implementation: `scan := scan + 1;
2500
+ now := TIME_TO_UDINT(TIME());
2501
+ IF sending THEN
2502
+ client(start := TRUE, cancel := FALSE, body := batch);
2503
+ IF client.done THEN
2504
+ IF client.error = ${httpErrors.base + 400} THEN
2505
+ dropped := dropped + (batched - sent);
2506
+ END_IF;
2507
+ IF client.error = 0 OR client.error = ${httpErrors.base + 400} THEN
2508
+ sent := batched;
2509
+ END_IF;
2510
+ sending := FALSE;
2511
+ lastSend := now;
2512
+ client(start := FALSE, cancel := FALSE, body := batch);
2513
+ END_IF;
2514
+ ELSIF head <> sent AND_THEN (head - sent >= ${batchRecords(recordBytes)} OR now - lastSend >= ${sendIntervalMs}) THEN
2515
+ Send();
2516
+ END_IF;
2517
+ `
2518
+ },
2519
+ method("Send", `VAR
2520
+ slot : UDINT;
2521
+ END_VAR
2522
+ `, `IF head - sent > ${capacity} THEN
2523
+ dropped := dropped + (head - sent - ${capacity});
2524
+ sent := head - ${capacity};
2525
+ END_IF;
2526
+ payload := '';
2527
+ Append(${quote(start)});
2528
+ Append(task);
2529
+ Append(${quote(rest[0])});
2530
+ Append(UDINT_TO_STRING(now));
2531
+ Append(${quote(rest[1])});
2532
+ Append(UDINT_TO_STRING(scan));
2533
+ Append(${quote(rest[2])});
2534
+ Append(ULINT_TO_STRING(sent + 1));
2535
+ Append(${quote(rest[3])});
2536
+ Append(ULINT_TO_STRING(dropped));
2537
+ Append(${quote(rest[4])});
2538
+ batched := sent;
2539
+ WHILE batched <> head DO
2540
+ slot := ULINT_TO_UDINT((batched + 1) MOD ${capacity});
2541
+ IF ByteLength(payload) + ByteLength(records[slot].json) + 3 > ${batchBytes} THEN
2542
+ EXIT;
2543
+ END_IF;
2544
+ IF batched <> sent THEN
2545
+ Append(',');
2546
+ END_IF;
2547
+ Append(records[slot].json);
2548
+ batched := batched + 1;
2549
+ END_WHILE;
2550
+ Append(']}');
2551
+ batch := payload;
2552
+ sending := TRUE;
2553
+ client(start := TRUE, cancel := FALSE, body := batch);
2554
+ `, "PRIVATE "),
2555
+ method("Commit", `VAR
2556
+ slot : UDINT;
2557
+ END_VAR
2558
+ `, `Append(',"scan":');
2559
+ Append(UDINT_TO_STRING(scan));
2560
+ Append(',"time":');
2561
+ Append(UDINT_TO_STRING(now));
2562
+ Append('}');
2563
+ slot := ULINT_TO_UDINT((head + 1) MOD ${capacity});
2564
+ records[slot].json := payload;
2565
+ records[slot].sequence := head + 1;
2566
+ head := head + 1;
2567
+ `, "PRIVATE "),
2568
+ method("ErrorName", `VAR_INPUT
2569
+ code : UDINT;
2570
+ END_VAR
2571
+ `, `CASE code OF
2572
+ ${errorNames.map(([code]) => `${code}: Append(${quote(`,"name":${json(errorName(Number(code)))}`)});`).join(`
2573
+ `)}
2574
+ ${httpErrors.base + 1}..${httpErrors.last}: Append(',"name":"HTTP '); Append(UDINT_TO_STRING(code - ${httpErrors.base})); Append('"');
2575
+ END_CASE;
2576
+ `, "PRIVATE "),
2577
+ method("WriteText", `VAR_INPUT
2578
+ data : POINTER TO BYTE;
2579
+ length : DINT;
2580
+ END_VAR
2581
+ VAR
2582
+ index : DINT;
2583
+ END_VAR
2584
+ `, `index := 0;
2585
+ WHILE index < length AND_THEN data[index] <> 0 DO
2586
+ text[index] := data[index];
2587
+ index := index + 1;
2588
+ END_WHILE;
2589
+ text[index] := 0;
2590
+ WriteString(text);
2591
+ `, "PRIVATE "),
2592
+ ...helpers,
2593
+ ...calls,
2594
+ ...failures,
2595
+ ...trace,
2596
+ client,
2597
+ ...httpMethods(telemetryClient),
2598
+ ...httpCertificateVerifier(telemetryClient, names.client, endpoint)
2599
+ ];
2600
+ }
2601
+
1440
2602
  // packages/compiler/backends/codesys/plan.ts
1441
2603
  var planned = Symbol("CODESYS plan");
1442
2604
  var plans = new WeakSet;
@@ -1446,7 +2608,7 @@ function diagnostic(message, span) {
1446
2608
  function isCodesysPlan(plan) {
1447
2609
  return plans.has(plan);
1448
2610
  }
1449
- function planCodesys(core, deployment, value) {
2611
+ function planCodesys(core, deployment, value, project = { root: process.cwd() }) {
1450
2612
  if (!isVerifiedCore(core))
1451
2613
  return { diagnostics: [diagnostic("CODESYS requires a verified, normalized core module.")] };
1452
2614
  const parsed = optionsSchema.safeParse(value);
@@ -1483,6 +2645,9 @@ function planCodesys(core, deployment, value) {
1483
2645
  validateTasks(core, deployment, report);
1484
2646
  validateStorage(core, options, report);
1485
2647
  validateConstants(core, report);
2648
+ const { telemetry, endpoint } = planTelemetry(core, deployment, options, { ...project, trace: project.debug?.trace }, report);
2649
+ if (endpoint)
2650
+ http.set(telemetryClient, endpoint);
1486
2651
  const { publication, errors } = resolvePublication(core, options.publish);
1487
2652
  for (const error of errors)
1488
2653
  report(error);
@@ -1495,6 +2660,8 @@ function planCodesys(core, deployment, value) {
1495
2660
  storageBindings,
1496
2661
  publication,
1497
2662
  http: Object.fromEntries(http),
2663
+ project,
2664
+ ...telemetry && { telemetry },
1498
2665
  [planned]: true
1499
2666
  });
1500
2667
  const freeze = (value) => {
@@ -1581,7 +2748,8 @@ function validateIo(core, options, report) {
1581
2748
  if (array && element?.kind === "bool")
1582
2749
  report(`BOOL arrays are not bit-packed in CODESYS I/O; bind each element of ${name} separately.`, span);
1583
2750
  const size = match[2] === "X" ? 1 : match[2] === "B" ? 8 : match[2] === "W" ? 16 : 32;
1584
- if (ioBits(element) !== size)
2751
+ const elementBits = element && ioScalarBits(iecSpelling(element, types) ?? "");
2752
+ if (elementBits !== size)
1585
2753
  report(`Address size does not match ${name}:${type.id}.`, span);
1586
2754
  const unit = size === 1 ? 8n : BigInt(size);
1587
2755
  const offset = BigInt(match[3]);
@@ -1607,11 +2775,6 @@ function nested(left, right) {
1607
2775
  return a.kind === "field" ? b.kind === "field" && a.name === b.name : b.kind === "index" && a.value === b.value;
1608
2776
  });
1609
2777
  }
1610
- function ioBits(type) {
1611
- if (type?.kind === "bool")
1612
- return 1;
1613
- return type && "bits" in type ? type.bits : 0;
1614
- }
1615
2778
  function validateTasks(core, deployment, report) {
1616
2779
  const programs = new Map(core.programs.map((program) => [program.name, program]));
1617
2780
  const assignment = new Map;
@@ -1671,7 +2834,7 @@ function validateStorage(core, options, report) {
1671
2834
  const blockHasInOut = (id) => {
1672
2835
  const block = blocks.get(id);
1673
2836
  return block.inputs.some((input) => input.mode === "inOut") || block.state.some((field) => {
1674
- const type = instancedBlock4(field.type, types);
2837
+ const type = instancedBlock5(field.type, types);
1675
2838
  return type !== undefined && blockHasInOut(type.block);
1676
2839
  });
1677
2840
  };
@@ -1680,7 +2843,7 @@ function validateStorage(core, options, report) {
1680
2843
  if (layout.retainedBlocks.has(block.id) && blockHasInOut(block.id))
1681
2844
  report("Retained function blocks cannot contain direct or nested InOut references.", block.span);
1682
2845
  for (const variable of core.variables) {
1683
- const type = instancedBlock4(variable.type, types);
2846
+ const type = instancedBlock5(variable.type, types);
1684
2847
  if (variable.retain && type && blockHasInOut(type.block))
1685
2848
  report("Retained function blocks cannot contain direct or nested InOut references.", variable.span);
1686
2849
  }
@@ -1755,6 +2918,8 @@ function validateConstants(core, report) {
1755
2918
  }
1756
2919
  if (item.kind === "return" && item.value)
1757
2920
  constantsInExpression(item.value);
2921
+ if (item.kind === "telemetry")
2922
+ telemetryOperands2(item).forEach(constantsInExpression);
1758
2923
  }
1759
2924
  };
1760
2925
  core.variables.forEach((variable) => {
@@ -1773,6 +2938,7 @@ function validateConstants(core, report) {
1773
2938
  }
1774
2939
 
1775
2940
  // packages/compiler/backends/codesys/emit.ts
2941
+ var buildPlaceholder = "<build>";
1776
2942
  function required(value) {
1777
2943
  if (value === undefined)
1778
2944
  throw new Error("Missing verified CODESYS symbol.");
@@ -1816,6 +2982,16 @@ class CodesysEmitter {
1816
2982
  numeric;
1817
2983
  globals;
1818
2984
  retainedVariables;
2985
+ debug;
2986
+ debugGlobal;
2987
+ debugNames = new Names;
2988
+ rings = new Map;
2989
+ debugSlots;
2990
+ telemetryNames;
2991
+ debugFields = new Map;
2992
+ jobs;
2993
+ jobIds = new Map;
2994
+ devices = new Map;
1819
2995
  constructor(plan) {
1820
2996
  this.plan = plan;
1821
2997
  const { core, options } = plan;
@@ -1834,6 +3010,56 @@ class CodesysEmitter {
1834
3010
  this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
1835
3011
  this.numeric = new NumericLowering(this.typeMap, (label) => this.names.allocate(label));
1836
3012
  this.objects.push(...this.targetTypes.objects);
3013
+ const settings = plan.project.debug;
3014
+ const hardware = plan.project.hardware;
3015
+ const outputs = [
3016
+ ...core.variables.filter((variable) => variable.storage === "output").map((root) => ({ key: root.name, root, segments: [] })),
3017
+ ...(hardware ? Object.entries(hardware.config.io).flatMap(([key, binding]) => {
3018
+ if (!isStoragePath(key) || !ioAddress(hardware, binding)?.startsWith("%Q"))
3019
+ return [];
3020
+ const resolved = resolveStoragePath(core, key);
3021
+ return "error" in resolved ? [] : [resolved];
3022
+ }) : plan.storageBindings.filter(({ key }) => required(options.io[key]).address.startsWith("%Q"))).map(({ key, root, segments }) => ({ key, root, segments }))
3023
+ ];
3024
+ this.debug = new DebugAnalysis(core, plan.deployment, settings, outputs);
3025
+ this.debugGlobal = this.names.allocateObject("GVL", "TsplcDebug");
3026
+ this.debugNames.allocate("buildId");
3027
+ this.debugSlots = {
3028
+ decisions: this.debugNames.allocate("decisions"),
3029
+ writers: this.debugNames.allocate("writers")
3030
+ };
3031
+ const telemetry = plan.telemetry;
3032
+ if (telemetry) {
3033
+ const tasks = new Set([
3034
+ ...[...telemetry.calls.values(), ...telemetry.failures.values()].map((site) => site.task),
3035
+ ...this.debug.events.map((site) => site.task)
3036
+ ]);
3037
+ for (const task of plan.deployment.tasks)
3038
+ if (tasks.has(task.name))
3039
+ this.rings.set(task.name, this.debugNames.allocate(task.name));
3040
+ if (this.rings.size)
3041
+ this.telemetryNames = {
3042
+ writer: this.names.allocateObject("FB", "TsplcTelemetry"),
3043
+ record: this.names.allocateObject("ST", "TsplcRecord"),
3044
+ client: this.names.allocateObject("FB", "TsplcTelemetryHttp")
3045
+ };
3046
+ }
3047
+ this.jobs = core.blocks.filter((block) => block.job).flatMap((block) => this.debug.instances.get(block.id).map((path) => ({ block, path })));
3048
+ this.jobs.forEach(({ path }, index) => {
3049
+ const declared = path.at(-1).variable;
3050
+ if (this.debug.owningPath(declared) === path)
3051
+ this.jobIds.set(declared.id, index + 1);
3052
+ });
3053
+ if (settings && hardware?.tree)
3054
+ for (const device of hardware.catalog.devices)
3055
+ this.devices.set(device.id, Object.fromEntries(device.assemblies.map((assembly) => [
3056
+ assembly.direction,
3057
+ {
3058
+ field: this.debugNames.allocate(`${device.id}_${assembly.direction}s`),
3059
+ address: assembly.address,
3060
+ bytes: assembly.size
3061
+ }
3062
+ ])));
1837
3063
  }
1838
3064
  emit() {
1839
3065
  this.emitGlobals();
@@ -1865,6 +3091,7 @@ END_VAR
1865
3091
  this.prepareStatements(block.body);
1866
3092
  this.objects.push(...this.numeric.objects);
1867
3093
  this.allocateBlockFields();
3094
+ this.emitTelemetry();
1868
3095
  const routines = [...core.functions, ...core.blocks.filter((block) => !block.standard)];
1869
3096
  for (const fn of routines)
1870
3097
  this.allocateRoutineScope(fn);
@@ -1872,6 +3099,7 @@ END_VAR
1872
3099
  this.emitRoutine(fn);
1873
3100
  for (const program of core.programs)
1874
3101
  this.emitProgram(program);
3102
+ const debug = this.emitDebugGlobal();
1875
3103
  const { objects, mappings } = this;
1876
3104
  const paths = new Map;
1877
3105
  for (const object of objects) {
@@ -1940,7 +3168,16 @@ export const machines=${JSON.stringify(exposures, null, 2)} as const;
1940
3168
  export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as const;
1941
3169
  `
1942
3170
  });
1943
- return { artifacts, objects, mappings, ioSymbols, ioMappings, publication, diagnostics: [] };
3171
+ return {
3172
+ artifacts,
3173
+ objects,
3174
+ mappings,
3175
+ ioSymbols,
3176
+ ioMappings,
3177
+ publication,
3178
+ debug,
3179
+ diagnostics: []
3180
+ };
1944
3181
  }
1945
3182
  objectPath(object) {
1946
3183
  const { core } = this.plan;
@@ -1990,7 +3227,7 @@ export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as con
1990
3227
  lines.push(` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`);
1991
3228
  mappings.push({ path: `${name}.st`, line: lines.length + 1, span: item.span });
1992
3229
  let initial = "";
1993
- if (!instancedBlock5(item.type, typeMap)) {
3230
+ if (!instancedBlock6(item.type, typeMap)) {
1994
3231
  const value = item.initial ?? defaultValue(item.type, typeMap);
1995
3232
  initial = group.storage === "constants" ? ` := ${targetTypes.literal(value, item.type)}` : targetTypes.declarationInitializer(value, item.type);
1996
3233
  }
@@ -2044,7 +3281,7 @@ export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as con
2044
3281
  }
2045
3282
  for (const { key, root, segments, type } of this.plan.storageBindings) {
2046
3283
  const { address, mapped, inverted } = required(options.io[key]);
2047
- const target = segments.reduce((path, segment) => segment.kind === "field" ? `${path}.${targetTypes.field(segment.record, segment.name)}` : `${path}[${segment.value}]`, required(references.get(root.id)));
3284
+ const target = this.bindingTarget({ root, segments });
2048
3285
  if (mapped) {
2049
3286
  ioMappings.push({ key, address, variable: target });
2050
3287
  continue;
@@ -2071,6 +3308,9 @@ export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as con
2071
3308
  `
2072
3309
  });
2073
3310
  }
3311
+ bindingTarget({ root, segments }) {
3312
+ return segments.reduce((path, segment) => segment.kind === "field" ? `${path}.${this.targetTypes.field(segment.record, segment.name)}` : `${path}[${segment.value}]`, required(this.references.get(root.id)));
3313
+ }
2074
3314
  prepareStatements(items) {
2075
3315
  const { numeric } = this;
2076
3316
  for (const item of items) {
@@ -2101,6 +3341,9 @@ export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as con
2101
3341
  }
2102
3342
  if (item.kind === "return" && item.value)
2103
3343
  numeric.prepare(item.value);
3344
+ if (item.kind === "telemetry")
3345
+ for (const value of telemetryOperands3(item))
3346
+ numeric.prepare(value);
2104
3347
  if (item.kind === "invoke") {
2105
3348
  if (item.index)
2106
3349
  numeric.prepare(item.index);
@@ -2122,6 +3365,7 @@ export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as con
2122
3365
  const fields = new Names, mapped = new Map;
2123
3366
  for (const object of objects)
2124
3367
  fields.reserve(object.name);
3368
+ fields.reserve(this.debugGlobal);
2125
3369
  for (const objectName of [
2126
3370
  ...core.functions.filter((fn) => !fn.owner).map((fn) => required(functionNames.get(fn.id))),
2127
3371
  ...blockNames.values()
@@ -2129,12 +3373,27 @@ export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as con
2129
3373
  fields.reserve(objectName);
2130
3374
  for (const method of core.functions.filter((fn) => fn.owner?.block === block.id))
2131
3375
  functionNames.set(method.id, fields.allocate(method.name));
2132
- const native = block.standard && standardBlocks2[block.standard];
3376
+ const native = block.standard && standardBlocks3[block.standard];
2133
3377
  for (const item of [...block.inputs, ...block.outputs, ...block.state])
2134
3378
  mapped.set(item.id, native ? required([...native.inputs, ...native.outputs].find(([name]) => name === item.name))[1] : fields.allocate(item.name, true));
2135
3379
  if (block.runtime?.kind === "mailbox")
2136
3380
  this.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
2137
3381
  blockFields.set(block.id, mapped);
3382
+ const settings = this.plan.project.debug;
3383
+ const stepped = this.debug.jobSites.has(block.id) || this.plan.telemetry?.failures.has(block.id);
3384
+ const tracked = Boolean(block.job && (settings?.jobs || stepped));
3385
+ const carries = settings?.jobs && this.debug.carriers.has(block.id);
3386
+ if (tracked || carries)
3387
+ this.debugFields.set(block.id, {
3388
+ ...tracked && {
3389
+ busy: fields.allocate("tsplcBusy"),
3390
+ track: fields.allocate("TsplcTrack")
3391
+ },
3392
+ ...tracked && settings?.jobs && { startedAt: fields.allocate("startedAt") },
3393
+ ...stepped && { step: fields.allocate("tsplcStep") },
3394
+ ...carries && { job: fields.allocate("requestJob") },
3395
+ ...carries && block.runtime?.kind === "http" && { sequence: fields.allocate("sequence") }
3396
+ });
2138
3397
  }
2139
3398
  }
2140
3399
  allocateRoutineScope(fn) {
@@ -2143,6 +3402,7 @@ export const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as con
2143
3402
  const names = new Names, references = new Map;
2144
3403
  for (const object of this.objects)
2145
3404
  names.reserve(object.name);
3405
+ names.reserve(this.debugGlobal);
2146
3406
  for (const name of [...this.functionNames.values(), ...this.blockNames.values()])
2147
3407
  names.reserve(name);
2148
3408
  if (this.programRoutines.has(fn.id) && "parameters" in fn && fn.result)
@@ -2209,7 +3469,8 @@ END_VAR`
2209
3469
  epoch: `${rpcGlobal}.epochs[${slot}]`
2210
3470
  });
2211
3471
  }
2212
- const generated = emitHttp(fn, required(this.blockNames.get(fn.id)), required(this.blockFields.get(fn.id)), this.typeMap, this.targetTypes, endpoint, this.networkName ? `${this.networkName}.network` : "", rpcGlobal);
3472
+ const requestFields = this.debugFields.get(fn.id);
3473
+ const generated = emitHttp(fn, required(this.blockNames.get(fn.id)), required(this.blockFields.get(fn.id)), this.typeMap, this.targetTypes, endpoint, this.networkName ? `${this.networkName}.network` : "", rpcGlobal, requestFields?.job && requestFields.sequence ? { job: requestFields.job, sequence: requestFields.sequence } : undefined);
2213
3474
  this.objects.push(generated, ...httpMethods(generated.id, endpoint.transport), ...httpCertificateVerifier(generated.id, generated.name, required(this.plan.http[fn.id])));
2214
3475
  return;
2215
3476
  }
@@ -2326,17 +3587,110 @@ END_VAR`
2326
3587
  else
2327
3588
  write(`${destination} := ${targetTypes.literal(value, id)};`, depth, span);
2328
3589
  };
3590
+ const ring = (task = this.debug.tasks.get(fn.id)) => `${this.debugGlobal}.${required(this.rings.get(required(task)))}`;
3591
+ const encode = (value) => {
3592
+ const type = required(typeMap.get(value.type));
3593
+ const text = expression(value);
3594
+ if (type.kind === "bool")
3595
+ return `BOOL_TO_DINT(${text})`;
3596
+ if (type.kind !== "integer" && type.kind !== "bits")
3597
+ return `TO_DINT(${text})`;
3598
+ const signed = type.kind === "integer" && type.signed;
3599
+ if (type.bits < 32 || signed && type.bits === 32)
3600
+ return `TO_DINT(${text})`;
3601
+ if (signed)
3602
+ return `TO_DINT(LIMIT(LINT#-2147483648, ${text}, LINT#2147483647))`;
3603
+ const wide = type.bits === 32 ? "UDINT" : "ULINT";
3604
+ return `TO_DINT(MIN(TO_${wide}(${text}), ${wide}#2147483647))`;
3605
+ };
3606
+ const record = (site, value, operands = []) => {
3607
+ const captured = Array.from({ length: required(this.plan.telemetry?.traceOperands) }, (_, index) => {
3608
+ const operand = operands[index];
3609
+ return `, operand${index} := ${operand ? encode(operand.capture) : "DINT#0"}`;
3610
+ });
3611
+ return `${ring()}.Trace(site := UINT#${site}, value := ${value}, operands := USINT#${operands.length}${captured.join("")});`;
3612
+ };
3613
+ const instrument = (item, depth) => {
3614
+ for (const probe of this.debug.probes.get(item) ?? []) {
3615
+ if (probe.kind === "writer") {
3616
+ const writer = `${this.debugGlobal}.${this.debugSlots.writers}[${probe.output}] := UINT#${probe.site};`;
3617
+ if (!probe.when.length) {
3618
+ write(writer, depth, item.span);
3619
+ continue;
3620
+ }
3621
+ const reached = probe.when.map(({ index, value }) => `TO_DINT(${expression(index)}) = DINT#${value}`);
3622
+ write(`IF ${reached.join(" AND ")} THEN`, depth, item.span);
3623
+ write(writer, depth + 1, item.span);
3624
+ write("END_IF;", depth, item.span);
3625
+ continue;
3626
+ }
3627
+ const value = `TO_DINT(${expression(probe.value)})`;
3628
+ if (item.kind === "assign")
3629
+ write(`IF ${place(item.root, item.path)} <> ${expression(probe.value)} THEN`, depth, item.span);
3630
+ else {
3631
+ const last = `${this.debugGlobal}.${this.debugSlots.decisions}[${required(probe.slot)}]`;
3632
+ write(`IF ${value} <> ${last} THEN`, depth, item.span);
3633
+ write(`${last} := ${value};`, depth + 1, item.span);
3634
+ }
3635
+ write(record(probe.site, value, probe.operands), depth + 1, item.span);
3636
+ write("END_IF;", depth, item.span);
3637
+ }
3638
+ };
3639
+ const tracked = block && this.debugFields.get(block.id);
3640
+ const jobField = (job, name) => load(required(job.state.find((item) => item.name === name)).id);
3641
+ const jobTracking = (job, fields) => {
3642
+ const busy = jobField(job, "busy");
3643
+ const sites = this.debug.jobSites.get(job.id);
3644
+ const failure = this.plan.telemetry?.failures.get(job.id);
3645
+ const lines = [];
3646
+ const line = (text, depth) => lines.push(" ".repeat(depth) + text);
3647
+ line(`IF ${busy} = ${required(fields.busy)} THEN`, 0);
3648
+ line("RETURN;", 1);
3649
+ line("END_IF;", 0);
3650
+ if (fields.startedAt || sites) {
3651
+ line(`IF ${busy} THEN`, 0);
3652
+ if (fields.startedAt)
3653
+ line(`${fields.startedAt} := TIME_TO_UDINT(TIME());`, 1);
3654
+ if (sites)
3655
+ line(record(sites.start, `TO_DINT(${jobField(job, "step")})`), 1);
3656
+ line("END_IF;", 0);
3657
+ }
3658
+ if (sites || failure) {
3659
+ const error = jobField(job, "error");
3660
+ line(`IF NOT ${busy} THEN`, 0);
3661
+ if (sites) {
3662
+ line(`IF ${error} <> 0 THEN`, 1);
3663
+ line(record(sites.completion, `-TO_DINT(${error})`), 2);
3664
+ line("ELSE", 1);
3665
+ line(record(sites.completion, `TO_DINT(${required(fields.step)})`), 2);
3666
+ line("END_IF;", 1);
3667
+ }
3668
+ if (failure) {
3669
+ line(`IF ${error} <> 0 AND ${error} <> 1 THEN`, 1);
3670
+ line(`${ring(failure.task)}.Failure${failure.id}(code := ${error}, step := ${required(fields.step)});`, 2);
3671
+ line("END_IF;", 1);
3672
+ }
3673
+ line("END_IF;", 0);
3674
+ }
3675
+ line(`${fields.busy} := ${busy};`, 0);
3676
+ return `${lines.join(`
3677
+ `)}
3678
+ `;
3679
+ };
2329
3680
  const body = (items, depth) => {
2330
3681
  for (const item of items) {
2331
3682
  switch (item.kind) {
2332
3683
  case "assign":
3684
+ instrument(item, depth);
3685
+ if (tracked?.step && block?.job && item.root === block.state.find((field) => field.name === "step")?.id)
3686
+ write(`${tracked.step} := ${jobField(block, "step")};`, depth, item.span);
2333
3687
  if (item.value.kind === "constant")
2334
3688
  assignConstant(place(item.root, item.path), item.value.value, item.value.type, depth, item.span);
2335
3689
  else
2336
3690
  write(`${place(item.root, item.path)} := ${expression(item.value)};`, depth, item.span);
2337
3691
  break;
2338
3692
  case "blockUpdate": {
2339
- const instance = instancedBlock5(required(scopeTypes.get(item.instance)), typeMap);
3693
+ const instance = instancedBlock6(required(scopeTypes.get(item.instance)), typeMap);
2340
3694
  if (!instance)
2341
3695
  throw new Error("Invalid verified block receiver");
2342
3696
  const target = required(blocks.get(instance.block));
@@ -2344,6 +3698,11 @@ END_VAR`
2344
3698
  const formal = required(target.inputs.find((field) => field.name === input));
2345
3699
  return `${required(required(blockFields.get(target.id)).get(formal.id))} := ${expression(value)}`;
2346
3700
  });
3701
+ const job = this.debugFields.get(target.id)?.job;
3702
+ const id = this.jobIds.get(item.instance);
3703
+ const given = owner && this.debugFields.get(owner.id)?.job;
3704
+ if (job && (id || given))
3705
+ arguments_.push(`${job} := ${id ? `UDINT#${id}` : given}`);
2347
3706
  const receiver = item.index ? `${load(item.instance)}[${expression(item.index)}]` : load(item.instance);
2348
3707
  write(`${receiver}(${arguments_.join(", ")});`, depth, item.span);
2349
3708
  break;
@@ -2436,6 +3795,7 @@ END_VAR`
2436
3795
  break;
2437
3796
  }
2438
3797
  case "return":
3798
+ instrument(item, depth);
2439
3799
  if (block) {
2440
3800
  if (item.value) {
2441
3801
  const returned = expression(item.value);
@@ -2449,6 +3809,8 @@ END_VAR`
2449
3809
  write(`${name} := ${item.value ? expression(item.value) : "TRUE"};`, depth, item.span);
2450
3810
  if (mutex)
2451
3811
  release(mutex, depth, item.span);
3812
+ if (tracked?.track)
3813
+ write(`${tracked.track}();`, depth);
2452
3814
  write("RETURN;", depth, item.span);
2453
3815
  break;
2454
3816
  case "break":
@@ -2457,6 +3819,12 @@ END_VAR`
2457
3819
  case "continue":
2458
3820
  write("CONTINUE;", depth, item.span);
2459
3821
  break;
3822
+ case "telemetry": {
3823
+ const site = required(this.plan.telemetry?.calls.get(item));
3824
+ const arguments_ = callParameters(item).map(({ name, value }) => `${name} := ${expression(value)}`);
3825
+ write(`${ring(site.task)}.Record${site.id}(${arguments_.join(", ")});`, depth, item.span);
3826
+ break;
3827
+ }
2460
3828
  }
2461
3829
  }
2462
3830
  };
@@ -2471,7 +3839,14 @@ END_VAR`
2471
3839
  write("RETURN;", 1);
2472
3840
  write("END_IF;", 0);
2473
3841
  }
3842
+ if (block && tracked?.track) {
3843
+ write(`${tracked.track}();`, 0);
3844
+ if (tracked.step)
3845
+ write(`${tracked.step} := ${jobField(block, "step")};`, 0);
3846
+ }
2474
3847
  body(fn.body, 0);
3848
+ if (tracked?.track)
3849
+ write(`${tracked.track}();`, 0);
2475
3850
  if (mutex)
2476
3851
  release(mutex, 0);
2477
3852
  if (!block && !method && !program && !fn.result)
@@ -2489,13 +3864,15 @@ END_VAR`
2489
3864
  line: declaration.length + 1,
2490
3865
  span: item.span
2491
3866
  });
2492
- const initial = item.initial && !instancedBlock5(item.type, typeMap) ? targetTypes.declarationInitializer(item.initial, item.type) : "";
3867
+ const initial = item.initial && !instancedBlock6(item.type, typeMap) ? targetTypes.declarationInitializer(item.initial, item.type) : "";
2493
3868
  declaration.push(` ${load(item.id)} : ${targetTypes.name(item.type)}${initial};`);
2494
3869
  }
2495
3870
  declaration.push("END_VAR");
2496
3871
  };
2497
3872
  section("VAR_INPUT", inputs.filter((item) => item.mode !== "inOut"));
2498
3873
  section("VAR_IN_OUT", inputs.filter((item) => item.mode === "inOut"));
3874
+ if (tracked && tracked.job)
3875
+ declaration.push("VAR_INPUT", ` ${tracked.job} : UDINT;`, "END_VAR");
2499
3876
  if (program && "parameters" in fn && fn.result) {
2500
3877
  declaration.push("VAR_OUTPUT", ` ${required(this.programResults.get(fn.id))} : ${targetTypes.name(fn.result)};`, "END_VAR");
2501
3878
  }
@@ -2505,6 +3882,13 @@ END_VAR`
2505
3882
  section("VAR_OUTPUT", block.outputs);
2506
3883
  section("VAR", block.state.filter((item) => !retainedVariables.has(item.id)));
2507
3884
  section("VAR RETAIN", block.state.filter((item) => retainedVariables.has(item.id)));
3885
+ const fields = [
3886
+ [tracked && tracked.busy, "BOOL"],
3887
+ [tracked && tracked.step, "UINT"],
3888
+ [tracked && tracked.startedAt, "UDINT"]
3889
+ ].flatMap(([field, type]) => field ? [` ${field} : ${type};`] : []);
3890
+ if (fields.length)
3891
+ declaration.push("VAR", ...fields, "END_VAR");
2508
3892
  }
2509
3893
  if (declarations.length) {
2510
3894
  declaration.push(block || program ? "VAR_TEMP" : "VAR");
@@ -2528,6 +3912,16 @@ END_VAR`
2528
3912
  `)}
2529
3913
  `
2530
3914
  });
3915
+ if (block && tracked?.track)
3916
+ objects.push({
3917
+ id: `${fn.id}:${tracked.track}`,
3918
+ parent: fn.id,
3919
+ kind: "method",
3920
+ name: tracked.track,
3921
+ declaration: `METHOD PRIVATE ${tracked.track}
3922
+ `,
3923
+ implementation: jobTracking(block, tracked)
3924
+ });
2531
3925
  }
2532
3926
  emitProgram(program) {
2533
3927
  const { core, options } = this.plan;
@@ -2540,6 +3934,7 @@ END_VAR`
2540
3934
  const stateful = this.programRoutines.has(program.entry);
2541
3935
  const call = `${functionNames.get(program.entry)}();`;
2542
3936
  const lines = [
3937
+ ...this.scanPrologue(program.name),
2543
3938
  ...channels.filter((channel) => channel.input).map(({ target, wire, inverted }) => `${target} := ${inverted ? "NOT " : ""}${wire};`),
2544
3939
  stateful ? call : `plc_discard := ${call}`,
2545
3940
  ...channels.filter((channel) => !channel.input).map(({ target, wire }) => `${wire} := ${target};`)
@@ -2559,6 +3954,327 @@ END_VAR
2559
3954
  `
2560
3955
  });
2561
3956
  }
3957
+ scanPrologue(program) {
3958
+ const task = this.plan.deployment.tasks.find((item) => item.programs[0] === program);
3959
+ const ring = task && this.rings.get(task.name);
3960
+ return ring ? [`${this.debugGlobal}.${ring}();`] : [];
3961
+ }
3962
+ emitTelemetry() {
3963
+ const { telemetry } = this.plan;
3964
+ const names = this.telemetryNames;
3965
+ if (!telemetry || !names)
3966
+ return;
3967
+ this.objects.push(...telemetryObjects({
3968
+ plan: telemetry,
3969
+ names,
3970
+ target: this.targetTypes,
3971
+ endpoint: required(this.plan.http[telemetryClient]),
3972
+ network: `${required(this.networkName)}.network`,
3973
+ build: buildPlaceholder,
3974
+ types: this.typeMap
3975
+ }));
3976
+ }
3977
+ emitDebugGlobal() {
3978
+ const manifest = this.manifest();
3979
+ const hash = createHash("sha256");
3980
+ for (const object of this.objects)
3981
+ hash.update(`${object.name}
3982
+ ${object.declaration}
3983
+ ${object.implementation ?? ""}
3984
+ `);
3985
+ hash.update(JSON.stringify(manifest));
3986
+ const id = hash.digest("hex").slice(0, 16);
3987
+ const send = this.objects.find((object) => object.id === "tsplc:telemetryWriter:Send");
3988
+ if (send)
3989
+ send.implementation = send.implementation.replace(buildPlaceholder, id);
3990
+ const fields = [`buildId : STRING(16) := '${id}'`];
3991
+ for (const [task, field] of this.rings)
3992
+ fields.push(`${field} : ${required(this.telemetryNames).writer} := (task := '${task}')`);
3993
+ const settings = this.plan.project.debug;
3994
+ if (settings) {
3995
+ if (this.debug.decisions.size)
3996
+ fields.push(`${this.debugSlots.decisions} : ARRAY[0..${this.debug.decisions.size - 1}] OF DINT`);
3997
+ if (settings.writers && this.debug.outputs.length)
3998
+ fields.push(`${this.debugSlots.writers} : ARRAY[0..${this.debug.outputs.length - 1}] OF UINT`);
3999
+ for (const raw of [...this.devices.values()].flatMap((device) => Object.values(device)))
4000
+ fields.push(`${raw.field} AT ${raw.address} : ARRAY[0..${raw.bytes - 1}] OF BYTE`);
4001
+ }
4002
+ this.objects.push({
4003
+ id: "debug",
4004
+ kind: "globalList",
4005
+ name: this.debugGlobal,
4006
+ declaration: `{attribute 'linkalways'}
4007
+ {attribute 'qualified_only'}
4008
+ VAR_GLOBAL
4009
+ ${fields.map((field) => ` ${field};
4010
+ `).join("")}END_VAR
4011
+ `
4012
+ });
4013
+ return { ...manifest, build: { ...manifest.build, id } };
4014
+ }
4015
+ instancePath(path) {
4016
+ let text = "", holder;
4017
+ for (const { variable, index } of path) {
4018
+ text += holder ? `.${required(required(this.blockFields.get(holder)).get(variable.id))}` : required(this.references.get(variable.id));
4019
+ if (index !== undefined)
4020
+ text += `[${index}]`;
4021
+ holder = required(instancedBlock6(variable.type, this.typeMap)).block;
4022
+ }
4023
+ return text;
4024
+ }
4025
+ requests(id, prefix, job) {
4026
+ const block = required(this.blocks.get(id));
4027
+ return block.state.flatMap((child) => {
4028
+ const instance = instancedBlock6(child.type, this.typeMap);
4029
+ if (!instance)
4030
+ return [];
4031
+ const caller = this.jobIds.get(child.id) ?? job;
4032
+ const type = required(this.typeMap.get(child.type));
4033
+ const field = `${prefix}.${required(required(this.blockFields.get(id)).get(child.id))}`;
4034
+ const targets = type.kind === "array" ? Array.from({ length: type.length }, (_, index) => `${field}[${type.lowerBound + index}]`) : [field];
4035
+ const sequence = this.debugFields.get(instance.block)?.sequence;
4036
+ const path = this.plan.http[instance.block]?.path;
4037
+ return targets.flatMap((target) => sequence && path ? [
4038
+ {
4039
+ service: serviceOfPath(path) ?? path,
4040
+ target,
4041
+ sequence: `${target}.${sequence}`,
4042
+ ...caller !== undefined && { job: caller }
4043
+ }
4044
+ ] : this.requests(instance.block, target, caller));
4045
+ });
4046
+ }
4047
+ reads(body, sources) {
4048
+ const reads = new Map;
4049
+ const path = (items = []) => {
4050
+ for (const segment of items)
4051
+ if (segment.kind === "index")
4052
+ expression(segment.value);
4053
+ };
4054
+ const expression = (value) => {
4055
+ if (value.kind === "unary" || value.kind === "convert")
4056
+ expression(value.operand);
4057
+ if (value.kind === "binary") {
4058
+ expression(value.left);
4059
+ expression(value.right);
4060
+ }
4061
+ if (value.kind !== "load")
4062
+ return;
4063
+ path(value.path);
4064
+ const read = storagePath(required(this.debug.variables.get(value.root)), value.path);
4065
+ const range = read && sources.range(value.span);
4066
+ if (range)
4067
+ reads.set(`${JSON.stringify(range)}${read}`, { range, path: read });
4068
+ };
4069
+ const statements = (items) => {
4070
+ for (const item of items) {
4071
+ if (item.kind === "assign") {
4072
+ path(item.path);
4073
+ expression(item.value);
4074
+ }
4075
+ if (item.kind === "if") {
4076
+ expression(item.condition);
4077
+ statements(item.then);
4078
+ statements(item.else);
4079
+ }
4080
+ if (item.kind === "switch") {
4081
+ expression(item.value);
4082
+ for (const branch of item.cases)
4083
+ statements(branch.body);
4084
+ statements(item.fallback);
4085
+ }
4086
+ if (item.kind === "for") {
4087
+ if (item.dynamic) {
4088
+ expression(item.dynamic.start);
4089
+ expression(item.dynamic.limit);
4090
+ }
4091
+ statements(item.body);
4092
+ }
4093
+ if (item.kind === "return" && item.value)
4094
+ expression(item.value);
4095
+ if (item.kind === "telemetry")
4096
+ telemetryOperands3(item).forEach(expression);
4097
+ if (item.kind === "invoke") {
4098
+ if (item.index)
4099
+ expression(item.index);
4100
+ item.arguments.forEach(expression);
4101
+ }
4102
+ if (item.kind === "blockUpdate") {
4103
+ if (item.index)
4104
+ expression(item.index);
4105
+ Object.values(item.inputs).forEach(expression);
4106
+ }
4107
+ }
4108
+ };
4109
+ statements(body);
4110
+ return [...reads.values()];
4111
+ }
4112
+ ioTarget(key) {
4113
+ const { core } = this.plan;
4114
+ const logical = core.variables.find((variable) => (variable.storage === "input" || variable.storage === "output") && variable.name === key);
4115
+ if (logical)
4116
+ return { target: required(this.references.get(logical.id)), type: logical.type };
4117
+ if (!isStoragePath(key))
4118
+ return;
4119
+ const resolved = resolveStoragePath(core, key);
4120
+ return "error" in resolved ? undefined : { target: this.bindingTarget(resolved), type: resolved.type.id };
4121
+ }
4122
+ manifest() {
4123
+ const { core, project, deployment, options } = this.plan;
4124
+ const settings = project.debug;
4125
+ const sources = new Sources(project.root);
4126
+ const global = (field) => `${this.debugGlobal}.${field}`;
4127
+ const functionIds = new Map;
4128
+ const functions = [
4129
+ ...core.functions,
4130
+ ...core.blocks.filter((block) => !block.standard && !block.runtime)
4131
+ ].flatMap((routine) => {
4132
+ const block = "inputs" in routine ? routine : undefined;
4133
+ const fn = "parameters" in routine ? routine : undefined;
4134
+ const declaration = sources.range(block?.job?.span ?? routine.span);
4135
+ if (!declaration)
4136
+ return [];
4137
+ const id = functionIds.size;
4138
+ functionIds.set(routine.id, id);
4139
+ const task = this.debug.tasks.get(routine.id);
4140
+ const origin = fn?.origin;
4141
+ const method = fn?.owner;
4142
+ return [
4143
+ {
4144
+ id,
4145
+ name: block?.job?.name ?? origin?.name ?? routine.name,
4146
+ declaration,
4147
+ ...origin?.instance && { instance: origin.instance },
4148
+ ...task && { task },
4149
+ target: block ? required(this.blockNames.get(block.id)) : method ? `${required(this.blockNames.get(method.block))}.${required(this.functionNames.get(routine.id))}` : required(this.functionNames.get(routine.id)),
4150
+ reads: this.reads(routine.body, sources)
4151
+ }
4152
+ ];
4153
+ });
4154
+ const declared = (routine) => {
4155
+ const id = routine === undefined ? undefined : functionIds.get(routine);
4156
+ return id === undefined ? undefined : { id, range: functions[id].declaration };
4157
+ };
4158
+ const events = this.debug.events.flatMap((site) => {
4159
+ const owner = declared(site.routine);
4160
+ const range = sources.range(site.span) ?? owner?.range;
4161
+ if (!range)
4162
+ return [];
4163
+ return [
4164
+ {
4165
+ id: site.id,
4166
+ kind: site.kind,
4167
+ ...site.job && {
4168
+ job: this.jobs.findIndex(({ block }) => block.id === site.job.block) + 1,
4169
+ phase: site.job.phase
4170
+ },
4171
+ path: site.path,
4172
+ ...owner && { function: owner.id },
4173
+ type: site.type,
4174
+ range,
4175
+ text: site.text ?? sources.text(site.span) ?? "",
4176
+ task: site.task,
4177
+ operands: site.operands.map((operand) => ({
4178
+ text: sources.text(operand.span) ?? "",
4179
+ range: sources.range(operand.span) ?? range,
4180
+ type: operand.capture.type,
4181
+ ...operand.path && { path: operand.path },
4182
+ stable: operand.stable
4183
+ }))
4184
+ }
4185
+ ];
4186
+ });
4187
+ const jobs = this.jobs.flatMap(({ block, path }, index) => {
4188
+ const job = required(block.job);
4189
+ const declaration = sources.range(job.span);
4190
+ if (!declaration)
4191
+ return [];
4192
+ const target = this.instancePath(path);
4193
+ const startedAt = this.debugFields.get(block.id)?.startedAt;
4194
+ return [
4195
+ {
4196
+ id: index + 1,
4197
+ name: job.name,
4198
+ declaration,
4199
+ ...job.instance && { instance: job.instance },
4200
+ target,
4201
+ steps: job.steps.map((step) => ({
4202
+ step: step.step,
4203
+ kind: step.kind,
4204
+ range: sources.range(step.span) ?? declaration,
4205
+ text: step.text
4206
+ })),
4207
+ ...startedAt && { startedAt: `${target}.${startedAt}` },
4208
+ requests: this.requests(block.id, target),
4209
+ ...generated(job.name) && { generated: true }
4210
+ }
4211
+ ];
4212
+ });
4213
+ const writers = settings?.writers ? this.debug.outputs.map((output, index) => ({
4214
+ output: output.key,
4215
+ target: global(`${this.debugSlots.writers}[${index}]`),
4216
+ sites: required(this.debug.writers[index]).flatMap((site) => {
4217
+ const owner = declared(site.routine);
4218
+ return owner ? [
4219
+ {
4220
+ id: site.id,
4221
+ range: sources.range(site.span) ?? owner.range,
4222
+ function: owner.id
4223
+ }
4224
+ ] : [];
4225
+ })
4226
+ })) : [];
4227
+ const roots = core.variables.filter((variable) => ["module", "instance", "input", "output"].includes(variable.storage)).map((variable) => {
4228
+ const declaration = sources.range(variable.span);
4229
+ return {
4230
+ path: required(storagePath(variable)),
4231
+ target: required(this.references.get(variable.id)),
4232
+ type: variable.type,
4233
+ ...declaration && { declaration },
4234
+ readable: true,
4235
+ ...variable.name.startsWith("tsplc") && { generated: true }
4236
+ };
4237
+ });
4238
+ const types = debugTypes(core.types, this.targetTypes, this.blocks, (block, variable) => required(required(this.blockFields.get(block)).get(variable)), (block) => {
4239
+ const fields = this.debugFields.get(block);
4240
+ return [
4241
+ [fields?.busy, "BOOL"],
4242
+ [fields?.step, "UINT"],
4243
+ [fields?.startedAt, "UDINT"],
4244
+ [fields?.job, "UDINT"],
4245
+ [fields?.sequence, "UDINT"]
4246
+ ].flatMap(([name, type]) => name ? [{ name, target: name, type }] : []);
4247
+ }, sources);
4248
+ const hardware = debugHardware(project.hardware ?? {
4249
+ catalog: { descriptors: [], devices: [] },
4250
+ config: { devices: {}, io: options.io },
4251
+ tree: false
4252
+ }, (key) => this.ioTarget(key), (id) => Object.fromEntries(Object.entries(this.devices.get(id) ?? {}).map(([direction, raw]) => [
4253
+ direction,
4254
+ global(raw.field)
4255
+ ])));
4256
+ const constants = debugConstants(core.folded ?? [], sources);
4257
+ return {
4258
+ kind: "tsplc-debug",
4259
+ version: 1,
4260
+ build: { id: "", target: global("buildId"), compiler: `@tsplc/compiler ${version}` },
4261
+ sources: sources.files,
4262
+ types,
4263
+ roots,
4264
+ constants,
4265
+ ...hardware,
4266
+ functions,
4267
+ jobs,
4268
+ events,
4269
+ writers,
4270
+ tasks: deployment.tasks.map((task) => ({
4271
+ name: task.name,
4272
+ intervalMs: Number(task.intervalNanoseconds) / 1e6,
4273
+ priority: task.priority
4274
+ })),
4275
+ errors: jobErrors2
4276
+ };
4277
+ }
2562
4278
  }
2563
4279
  // packages/compiler/backends/codesys/vendor.ts
2564
4280
  import { CodesysCompilerError } from "@tsplc/build";
@@ -2635,5 +4351,5 @@ export {
2635
4351
  publicationSelectors
2636
4352
  };
2637
4353
 
2638
- //# debugId=C98587762BFC22D464756E2164756E21
4354
+ //# debugId=ABD6B7B7AE0FA7A764756E2164756E21
2639
4355
  //# sourceMappingURL=codesys.js.map