@tsplc/compiler 0.5.7 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/codesys.js CHANGED
@@ -139,14 +139,23 @@ function codesys(options) {
139
139
  function direct(address) {
140
140
  return { kind: "direct", address };
141
141
  }
142
- // packages/compiler/src/codesys/global-lists.ts
142
+ // packages/compiler/src/codesys/emit.ts
143
+ import { createHash as createHash2 } from "node:crypto";
144
+
145
+ // packages/compiler/src/codesys/explain.ts
143
146
  import {
144
- defaultValue,
145
- instancedBlock as instancedBlock4
147
+ instancedBlock as instancedBlock7,
148
+ nestedBodies as nestedBodies6,
149
+ pathConditions,
150
+ projectReconstruction,
151
+ standardBlocks as standardBlocks4
146
152
  } from "@tsplc/compiler/ir";
153
+ import { createExplainer } from "@tsplc/debug/explain";
154
+ import { createPaths } from "@tsplc/debug/paths";
155
+ import { serviceOfPath as serviceOfPath2 } from "@tsplc/server";
147
156
 
148
- // packages/compiler/src/codesys/io-paths.ts
149
- import { ioLayout } from "@tsplc/typegen/hardware";
157
+ // packages/compiler/src/codesys/debug.ts
158
+ import { directWrites, instancedBlock as instancedBlock3, nestedBodies as nestedBodies2 } from "@tsplc/compiler/ir";
150
159
 
151
160
  // packages/compiler/src/codesys/storage.ts
152
161
  import { basename } from "node:path";
@@ -227,1069 +236,1528 @@ function storageLayout(core) {
227
236
  };
228
237
  }
229
238
 
230
- // packages/compiler/src/codesys/io-paths.ts
231
- var pathPattern = /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
232
- var isStoragePath = (key) => key.includes(".") || key.includes("[");
233
- function resolveStoragePath(core, key) {
234
- const match = pathPattern.exec(key);
235
- if (!match) {
236
- return {
237
- error: `${key}: expected Module.variable followed by .field or [index].`
238
- };
239
- }
240
- const [, module, name, rest] = match;
241
- const roots = core.variables.filter((item) => item.storage === "module" && item.name === name && moduleName(item) === module);
242
- const [root] = roots;
243
- if (!root || roots.length !== 1) {
244
- return {
245
- error: root ? `${key}: ${module}.${name} is declared by more than one module named ${module}.` : `${key}: no mutable module variable ${module}.${name}.`
246
- };
247
- }
239
+ // packages/compiler/src/codesys/task-access.ts
240
+ import {
241
+ instancedBlock as instancedBlock2,
242
+ nanosecondsPerMillisecond,
243
+ nestedBodies,
244
+ statementExpressions,
245
+ subexpressions
246
+ } from "@tsplc/compiler/ir";
247
+ var variablesById = (core) => new Map([
248
+ ...core.variables,
249
+ ...core.functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
250
+ ...core.blocks.flatMap((block) => [
251
+ ...block.inputs,
252
+ ...block.outputs,
253
+ ...block.state,
254
+ ...block.locals
255
+ ])
256
+ ].map((variable) => [variable.id, variable]));
257
+ function routineTasks(core, deployment) {
258
+ const tasks = new Map;
248
259
  const types = new Map(core.types.map((type) => [type.id, type]));
249
- let type = types.get(root.type);
250
- const segments = [];
251
- for (const [, field, index] of rest.matchAll(/\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g)) {
252
- if (field !== undefined) {
253
- const member = type.kind === "record" ? type.fields.find((f) => f.name === field) : undefined;
254
- if (!member) {
255
- return { error: `${key}: no field ${field}.` };
256
- }
257
- segments.push({ kind: "field", record: type.id, name: field });
258
- type = types.get(member.type);
259
- } else {
260
- const value = Number(index);
261
- if (type.kind !== "array") {
262
- return { error: `${key}: ${index} indexes a non-array value.` };
263
- }
264
- if (value < type.lowerBound || value >= type.lowerBound + type.length) {
265
- return {
266
- error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`
260
+ const routines = new Map([...core.functions, ...core.blocks].map((routine) => [routine.id, routine]));
261
+ const variables = variablesById(core);
262
+ const programs = new Map(core.programs.map((program) => [program.name, program]));
263
+ for (const task of deployment.tasks) {
264
+ for (const name of task.programs) {
265
+ const seen = new Set;
266
+ const visit = (id) => {
267
+ if (seen.has(id)) {
268
+ return;
269
+ }
270
+ seen.add(id);
271
+ tasks.set(id, tasks.has(id) && tasks.get(id) !== task.name ? undefined : task.name);
272
+ const inspect = (items) => {
273
+ for (const item of items) {
274
+ if (item.kind === "invoke") {
275
+ visit(item.function);
276
+ }
277
+ if (item.kind === "blockUpdate") {
278
+ const block = instancedBlock2(variables.get(item.instance).type, types);
279
+ if (block) {
280
+ visit(block.block);
281
+ }
282
+ }
283
+ for (const body of nestedBodies(item)) {
284
+ inspect(body);
285
+ }
286
+ }
267
287
  };
268
- }
269
- segments.push({ kind: "index", value });
270
- type = types.get(type.element);
288
+ inspect(routines.get(id)?.body ?? []);
289
+ };
290
+ visit(programs.get(name).entry);
271
291
  }
272
292
  }
273
- return { key, root, segments, type };
293
+ return tasks;
274
294
  }
275
- function iecSpelling(type, types) {
276
- if (type.kind === "bool" || type.kind === "integer" || type.kind === "bits" || type.kind === "float" || type.kind === "duration" || type.kind === "calendar") {
277
- return type.id;
278
- }
279
- if (type.kind !== "array") {
280
- return;
295
+ function schedulePrograms(core, tasks, report) {
296
+ const background = new Map;
297
+ for (const program of core.programs) {
298
+ if (!program.background) {
299
+ continue;
300
+ }
301
+ const { priority, intervalNanoseconds } = program.background;
302
+ const name = `TsplcBackground_${priority}_${BigInt(intervalNanoseconds) / nanosecondsPerMillisecond}`;
303
+ const existing = background.get(name);
304
+ if (existing) {
305
+ existing.programs.push(program.name);
306
+ continue;
307
+ }
308
+ background.set(name, {
309
+ name,
310
+ priority,
311
+ intervalNanoseconds,
312
+ programs: [program.name]
313
+ });
281
314
  }
282
- const element = iecSpelling(types.get(type.element), types);
283
- const upper = type.lowerBound + type.length - 1;
284
- return element && !element.startsWith("ARRAY") ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}` : undefined;
315
+ return appendContinuations(core, [...tasks, ...background.values()], report);
285
316
  }
286
- function ioTargets(core) {
287
- const types = new Map(core.types.map((type) => [type.id, type]));
288
- const targets = [];
289
- const add = (key, type) => {
290
- const layout = ioLayout(iecSpelling(type, types) ?? "");
291
- if (layout) {
292
- targets.push({ key, layout });
317
+ function taskStorageOwnership(core, report) {
318
+ const owners = new Map;
319
+ const globals = new Map(core.variables.map((item) => [item.id, item]));
320
+ const functions = new Map(core.functions.map((item) => [item.id, item]));
321
+ const blocks = new Map(core.blocks.map((block) => [block.id, block.runtime?.kind]));
322
+ const runtimes = new Map(core.types.flatMap((type) => type.kind === "block" ? [[type.id, blocks.get(type.block)]] : []));
323
+ return (task, program) => {
324
+ const fn = functions.get(program.entry);
325
+ if (!fn) {
326
+ throw new Error("Verified core has a missing entry.");
293
327
  }
294
- };
295
- const visit = (key, type) => {
296
- add(key, type);
297
- if (type.kind === "record") {
298
- for (const field of type.fields) {
299
- visit(`${key}.${field.name}`, types.get(field.type));
328
+ const worker = program.background?.worker;
329
+ const host = worker && core.variables.find((item) => item.name === worker && item.span.file === fn.span.file && runtimes.get(item.type) === "backgroundHost");
330
+ for (const id of accessedStorage(fn, core, host ? host.id : undefined)) {
331
+ const item = globals.get(id);
332
+ if (!item || item.storage === "constant" || runtimes.get(item.type) === "mailbox") {
333
+ continue;
334
+ }
335
+ const ownsWorker = worker === item.name && item.span.file === fn.span.file;
336
+ if (program.background && (!ownsWorker || host && item.id === host.id)) {
337
+ report(`Background task ${program.name} accesses scan-owned storage ${item.name}; pass value snapshots through the mailbox.`, item.span);
338
+ }
339
+ const owner = owners.get(id);
340
+ if (owner && owner !== task) {
341
+ report(`Storage ${item.name} is shared across cyclic tasks ${owner} and ${task}.`, item.span);
300
342
  }
343
+ owners.set(id, task);
301
344
  }
302
- if (type.kind === "array") {
303
- visit(`${key}[\${number}]`, types.get(type.element));
345
+ };
346
+ }
347
+ var buildModuleTables = (core) => ({
348
+ functions: new Map(core.functions.map((item) => [item.id, item])),
349
+ blocks: new Map(core.blocks.map((item) => [item.id, item])),
350
+ types: new Map(core.types.map((item) => [item.id, item])),
351
+ variables: variablesById(core)
352
+ });
353
+ var builtTables = new WeakMap;
354
+ var moduleTables = (core) => {
355
+ const known = builtTables.get(core);
356
+ if (known) {
357
+ return known;
358
+ }
359
+ const tables = buildModuleTables(core);
360
+ builtTables.set(core, tables);
361
+ return tables;
362
+ };
363
+ function accessedStorage(fn, core, scheduledHost) {
364
+ const scheduledCall = fn.body.find((item) => item.kind === "invoke" && item.instance === scheduledHost);
365
+ const result = new Set;
366
+ const seen = new Set;
367
+ const { functions, blocks, types, variables } = moduleTables(core);
368
+ const expression = (value) => {
369
+ if (value.kind === "load") {
370
+ result.add(value.root);
371
+ }
372
+ if (value.kind === "borrow") {
373
+ result.add(value.place.root);
304
374
  }
375
+ subexpressions(value).forEach(expression);
305
376
  };
306
- for (const variable of core.variables) {
307
- if (variable.storage === "input" || variable.storage === "output") {
308
- add(variable.name, types.get(variable.type));
309
- } else if (variable.storage === "module") {
310
- visit(`${moduleName(variable)}.${variable.name}`, types.get(variable.type));
377
+ const body = (items) => {
378
+ for (const item of items) {
379
+ if (item.kind === "assign") {
380
+ result.add(item.root);
381
+ }
382
+ if (item.kind === "invoke" && item.instance && item !== scheduledCall) {
383
+ result.add(item.instance);
384
+ }
385
+ if (item.kind === "blockUpdate") {
386
+ result.add(item.instance);
387
+ }
388
+ statementExpressions(item).forEach(expression);
389
+ if (item.kind === "for") {
390
+ result.add(item.counter);
391
+ }
392
+ if (item.kind === "invoke") {
393
+ if (item.destination) {
394
+ result.add(item.destination);
395
+ }
396
+ const called = functions.get(item.function);
397
+ if (called && !seen.has(called.id)) {
398
+ seen.add(called.id);
399
+ body(called.body);
400
+ }
401
+ }
402
+ if (item.kind === "blockUpdate") {
403
+ const variable = variables.get(item.instance);
404
+ if (!variable) {
405
+ throw new Error("Missing verified instance during task planning.");
406
+ }
407
+ const type = instancedBlock2(variable.type, types);
408
+ const block = type && blocks.get(type.block);
409
+ if (block && !seen.has(block.id)) {
410
+ seen.add(block.id);
411
+ body(block.body);
412
+ }
413
+ }
414
+ nestedBodies(item).forEach(body);
311
415
  }
312
- }
313
- return targets;
416
+ };
417
+ seen.add(fn.id);
418
+ body(fn.body);
419
+ return result;
314
420
  }
315
-
316
- // packages/compiler/src/codesys/symbols.ts
317
- import {
318
- standardBlocks as standardBlocks2
319
- } from "@tsplc/compiler/ir";
320
-
321
- // packages/compiler/src/codesys/global-names.ts
322
- import { standardBlocks } from "@tsplc/compiler/ir";
323
-
324
- // packages/compiler/src/codesys/types.ts
325
- import { instancedBlock as instancedBlock2, nanosecondsPerMillisecond } from "@tsplc/compiler/ir";
326
- import { escapeString } from "@tsplc/iec/st";
327
-
328
- // packages/compiler/src/codesys/numeric.ts
329
- import {
330
- floatMaximum,
331
- integerRange,
332
- integerType,
333
- isElementary,
334
- nestedBodies,
335
- pathIndexes,
336
- statementExpressions,
337
- subexpressions
338
- } from "@tsplc/compiler/ir";
339
- var elementaryNames = {
340
- sqrt: "SQRT",
341
- ln: "LN",
342
- log10: "LOG",
343
- exp: "EXP",
344
- sin: "SIN",
345
- cos: "COS",
346
- tan: "TAN",
347
- asin: "ASIN",
348
- acos: "ACOS",
349
- atan: "ATAN"
421
+ function appendContinuations(core, tasks, report) {
422
+ const continuations = core.programs.flatMap((program) => program.continuation ? [{ name: program.name, scope: program.continuation }] : []);
423
+ if (!continuations.length) {
424
+ return tasks;
425
+ }
426
+ const programs = new Map(core.programs.map((program) => [program.name, program]));
427
+ const functions = new Map(core.functions.map((routine) => [routine.id, routine]));
428
+ const placements = tasks.map((task) => {
429
+ const roots = new Set;
430
+ for (const name of task.programs) {
431
+ const program = programs.get(name);
432
+ if (!program || program.background) {
433
+ continue;
434
+ }
435
+ const entry = functions.get(program.entry);
436
+ if (entry) {
437
+ for (const id of accessedStorage(entry, core)) {
438
+ roots.add(id);
439
+ }
440
+ }
441
+ }
442
+ return { task, roots, additions: [] };
443
+ });
444
+ for (const { name, scope } of continuations) {
445
+ const root = core.variables.find((variable) => variable.name === scope.instance && variable.span.file === scope.file);
446
+ if (!root) {
447
+ report(`Missing continuation owner ${scope.instance}.`);
448
+ continue;
449
+ }
450
+ const owners = placements.filter(({ roots }) => roots.has(root.id));
451
+ const [owner] = owners;
452
+ if (!owner || owners.length !== 1) {
453
+ report(`Continuation owner ${scope.instance} must belong to exactly one caller task.`, root.span);
454
+ continue;
455
+ }
456
+ owner.additions.push(name);
457
+ }
458
+ return placements.map(({ task, additions }) => ({
459
+ ...task,
460
+ programs: task.programs.concat(additions)
461
+ }));
462
+ }
463
+
464
+ // packages/compiler/src/codesys/debug.ts
465
+ var temporary = (id) => id.includes(":temporary:");
466
+ var constantIndex = (value) => value.kind === "constant" && value.value.kind === "integer" ? Number(value.value.value) : undefined;
467
+ var writtenPlace = (item) => {
468
+ if (item.kind === "assign") {
469
+ return { root: item.root, path: item.path ?? [] };
470
+ }
471
+ return item.kind === "invoke" && item.destination ? { root: item.destination, path: [] } : undefined;
350
472
  };
351
- var operatorTokens = {
352
- add: "+",
353
- subtract: "-",
354
- multiply: "*",
355
- divide: "/",
356
- remainder: "MOD",
357
- equal: "=",
358
- notEqual: "<>",
359
- less: "<",
360
- lessEqual: "<=",
361
- greater: ">",
362
- greaterEqual: ">=",
363
- bitAnd: "AND",
364
- bitOr: "OR",
365
- bitXor: "XOR"
473
+ var wholeTarget = (item) => {
474
+ if (item.kind === "assign" && !item.path?.length) {
475
+ return item.root;
476
+ }
477
+ return item.kind === "invoke" ? item.destination : undefined;
366
478
  };
367
- function scalarLiteral(value, type) {
368
- if (value.kind === "bool") {
369
- return value.value ? "TRUE" : "FALSE";
479
+ function blockInstances(core) {
480
+ const types = new Map(core.types.map((type) => [type.id, type]));
481
+ const blocks = new Map(core.blocks.map((block) => [block.id, block]));
482
+ const instances = new Map(core.blocks.map((block) => [block.id, []]));
483
+ const visit = (variable, block, path) => {
484
+ const type = types.get(variable.type);
485
+ const declared = type?.kind === "array" ? Array.from({ length: type.length }, (_, offset) => [
486
+ ...path,
487
+ { variable, index: type.lowerBound + offset }
488
+ ]) : [[...path, { variable }]];
489
+ for (const instance of declared) {
490
+ instances.get(block).push(instance);
491
+ for (const child of blocks.get(block).state) {
492
+ const instanced = instancedBlock3(child.type, types);
493
+ if (instanced) {
494
+ visit(child, instanced.block, instance);
495
+ }
496
+ }
497
+ }
498
+ };
499
+ for (const variable of core.variables) {
500
+ const instanced = instancedBlock3(variable.type, types);
501
+ if (instanced) {
502
+ visit(variable, instanced.block, []);
503
+ }
370
504
  }
371
- if (value.kind === "integer") {
372
- return `${type}#${value.value}`;
505
+ return instances;
506
+ }
507
+ function storagePath(root, path = []) {
508
+ const logical = root.storage === "input" || root.storage === "output";
509
+ if (!logical && root.storage !== "module" && root.storage !== "instance") {
510
+ return;
373
511
  }
374
- if (value.kind === "float") {
375
- const text = Object.is(value.value, -0) ? "-0.0" : String(value.value).replace(/e/i, "E");
376
- return `${type}#${text}`;
512
+ let text = logical ? root.name : `${moduleName(root)}.${root.name}`;
513
+ for (const segment of path) {
514
+ if (segment.kind === "field") {
515
+ text += `.${segment.name}`;
516
+ continue;
517
+ }
518
+ const index = constantIndex(segment.value);
519
+ if (index === undefined) {
520
+ return;
521
+ }
522
+ text += `[${index}]`;
377
523
  }
378
- throw new Error("Expected verified scalar constant");
524
+ return text;
379
525
  }
380
526
 
381
- class NumericLowering {
527
+ class DebugAnalysis {
528
+ core;
529
+ outputs;
530
+ tasks;
531
+ instances;
532
+ probes = new Map;
533
+ events = [];
534
+ writers;
535
+ jobSites = new Map;
536
+ decisions = new Map;
537
+ callSites = new Map;
538
+ carriers = new Set;
539
+ variables;
382
540
  types;
383
- allocate;
384
- objects = [];
385
- helpers = new Map;
386
- constructor(types, allocate) {
387
- this.types = types;
388
- this.allocate = allocate;
389
- }
390
- prepare(value) {
391
- for (const operand of subexpressions(value)) {
392
- this.prepare(operand);
541
+ routines;
542
+ blocks;
543
+ routineWrites = new Map;
544
+ temporaries = new Map;
545
+ writerSites = 0;
546
+ constructor(core, deployment, settings, outputs) {
547
+ this.core = core;
548
+ this.outputs = outputs;
549
+ this.types = new Map(core.types.map((type) => [type.id, type]));
550
+ this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
551
+ this.routines = new Map([...core.functions, ...core.blocks].map((routine) => [
552
+ routine.id,
553
+ routine
554
+ ]));
555
+ this.variables = variablesById(core);
556
+ this.writers = outputs.map(() => []);
557
+ this.tasks = routineTasks(core, deployment);
558
+ this.instances = blockInstances(core);
559
+ this.findCarriers();
560
+ if (!settings) {
561
+ return;
393
562
  }
394
- if (value.kind === "binary" && value.policy) {
395
- this.arithmetic(value.type, value.operator, value.policy);
563
+ const routines = [
564
+ ...core.functions,
565
+ ...core.blocks.filter((block) => !block.standard)
566
+ ];
567
+ for (const routine of routines) {
568
+ this.countCalls(routine.body, 1);
396
569
  }
397
- if (value.kind === "convert" && value.policy === "saturate") {
398
- this.saturation(value.operand.type, value.type);
570
+ for (const routine of routines) {
571
+ this.walk(settings, routine, routine.body, [], []);
399
572
  }
400
- if (value.kind === "unary" && value.operator === "truncate") {
401
- this.truncation(value.type);
573
+ if (settings.trace) {
574
+ for (const block of core.blocks) {
575
+ const { job } = block;
576
+ const task = this.tasks.get(block.id);
577
+ if (!job || !task || this.instances.get(block.id)?.length !== 1) {
578
+ continue;
579
+ }
580
+ const site = (type, phase) => this.site({
581
+ kind: "job",
582
+ job: { block: block.id, phase },
583
+ path: job.name,
584
+ type,
585
+ span: job.span,
586
+ text: `${job.name}: ${phase}`,
587
+ task
588
+ });
589
+ this.jobSites.set(block.id, {
590
+ start: site("UINT", "started"),
591
+ completion: site("DINT", "finished")
592
+ });
593
+ }
402
594
  }
403
595
  }
404
- prepareStatements(items) {
405
- for (const item of items) {
406
- const values = item.kind === "assign" ? [item.value, ...pathIndexes(item.path)] : statementExpressions(item);
407
- for (const value of values) {
408
- this.prepare(value);
596
+ owningPath(variable) {
597
+ const type = this.types.get(variable.type);
598
+ const block = type?.kind === "block" ? this.blocks.get(type.block) : undefined;
599
+ if (!block?.job) {
600
+ return;
601
+ }
602
+ const paths = this.instances.get(block.id).filter((path) => path.at(-1).variable.id === variable.id);
603
+ return paths.length === 1 ? paths[0] : undefined;
604
+ }
605
+ site(site) {
606
+ const id = this.events.length + 1;
607
+ this.events.push({ ...site, id, operands: site.operands ?? [] });
608
+ return id;
609
+ }
610
+ findCarriers() {
611
+ const carries = (id) => {
612
+ const block = this.blocks.get(id);
613
+ if (block.runtime?.kind === "http") {
614
+ return true;
409
615
  }
410
- for (const body of nestedBodies(item)) {
411
- this.prepareStatements(body);
616
+ return block.state.some((child) => {
617
+ const type = instancedBlock3(child.type, this.types);
618
+ return type !== undefined && carries(type.block);
619
+ });
620
+ };
621
+ for (const block of this.core.blocks) {
622
+ if (carries(block.id)) {
623
+ this.carriers.add(block.id);
412
624
  }
413
625
  }
414
626
  }
415
- render(value, operands) {
416
- if (value.kind === "convert") {
417
- return value.policy === "saturate" ? `${this.saturation(value.operand.type, value.type)}(${operands[0]})` : `TO_${value.type}(${operands[0]})`;
627
+ placeType(root, path = []) {
628
+ let type = this.types.get(root.type);
629
+ for (const segment of path) {
630
+ if (segment.kind === "field" && type?.kind === "record") {
631
+ type = this.types.get(type.fields.find((field) => field.name === segment.name).type);
632
+ } else if (segment.kind === "index" && type?.kind === "array") {
633
+ type = this.types.get(type.element);
634
+ } else {
635
+ return;
636
+ }
418
637
  }
419
- if (value.kind === "unary") {
420
- if (value.operator === "timeToMilliseconds") {
421
- return `TIME_TO_UDINT(${operands[0]})`;
422
- }
423
- if (value.operator === "clock") {
424
- return "TO_DINT(TIME_TO_UDINT(TIME()))";
425
- }
426
- if (isElementary(value.operator)) {
427
- return `${elementaryNames[value.operator]}(${operands[0]})`;
638
+ return type;
639
+ }
640
+ countCalls(items, weight) {
641
+ for (const item of items) {
642
+ if (item.kind === "invoke") {
643
+ this.callSites.set(item.function, (this.callSites.get(item.function) ?? 0) + weight);
428
644
  }
429
- if (value.operator === "truncate") {
430
- return `${this.truncation(value.type)}(${operands[0]})`;
645
+ for (const body of nestedBodies2(item)) {
646
+ this.countCalls(body, item.kind === "for" ? 2 : weight);
431
647
  }
432
- return value.operator === "not" ? `(NOT ${operands[0]})` : `TO_${value.type}(${value.operator === "negate" ? "-" : "NOT "}${operands[0]})`;
433
- }
434
- if (value.kind !== "binary") {
435
- throw new Error("Expected numeric operation");
436
- }
437
- if (value.policy) {
438
- return `${this.arithmetic(value.type, value.operator, value.policy)}(${operands.join(", ")})`;
439
- }
440
- if (value.operator === "power") {
441
- return `EXPT(${operands.join(", ")})`;
442
648
  }
443
- if (value.operator === "shiftLeft" || value.operator === "shiftRight") {
444
- const shift = value.operator === "shiftLeft" ? "SHL" : "SHR";
445
- return `TO_${value.type}(${shift}(${operands.join(", ")}))`;
649
+ }
650
+ writes(id) {
651
+ const cached = this.routineWrites.get(id);
652
+ if (cached) {
653
+ return cached;
446
654
  }
447
- const token = operatorTokens[value.operator];
448
- if (!token) {
449
- throw new Error("Boolean short-circuit operation was not normalized");
655
+ const result = new Set;
656
+ this.routineWrites.set(id, result);
657
+ for (const root of this.statementWrites(this.routines.get(id)?.body ?? [])) {
658
+ result.add(root);
450
659
  }
451
- const text = value.operator === "remainder" ? `(${operands[0]} - (${operands[0]} / ${operands[1]}) * ${operands[1]})` : `(${operands[0]} ${token} ${operands[1]})`;
452
- return value.type === "BOOL" ? text : `TO_${value.type}(${text})`;
660
+ return result;
453
661
  }
454
- helper(key, type, inputs, body, locals = "") {
455
- const existing = this.helpers.get(key);
456
- if (existing) {
457
- return existing;
662
+ statementWrites(items) {
663
+ const result = new Set;
664
+ for (const item of items) {
665
+ for (const root of directWrites(item)) {
666
+ result.add(root);
667
+ }
668
+ if (item.kind === "invoke") {
669
+ for (const root of this.writes(item.function)) {
670
+ result.add(root);
671
+ }
672
+ }
673
+ if (item.kind === "blockUpdate") {
674
+ const block = instancedBlock3(this.variables.get(item.instance).type, this.types);
675
+ if (block) {
676
+ for (const root of this.writes(block.block)) {
677
+ result.add(root);
678
+ }
679
+ }
680
+ }
681
+ for (const body of nestedBodies2(item)) {
682
+ for (const root of this.statementWrites(body)) {
683
+ result.add(root);
684
+ }
685
+ }
458
686
  }
459
- const name = this.allocate(`numeric_${key}`);
460
- this.helpers.set(key, name);
461
- const parameters = inputs.map(([input, inputType]) => ` ${input} : ${inputType};`).join(`
462
- `);
463
- const variables = locals ? `VAR
464
- ${locals}
465
- END_VAR
466
- ` : "";
467
- const declaration = `FUNCTION ${name} : ${type}
468
- VAR_INPUT
469
- ${parameters}
470
- END_VAR
471
- ${variables}`;
472
- this.objects.push({
473
- id: `numeric:${key}`,
474
- kind: "function",
475
- name,
476
- declaration,
477
- implementation: body(name)
478
- });
479
- return name;
687
+ return result;
480
688
  }
481
- add64() {
482
- return this.helper("add64", "LWORD", [
483
- ["a", "LWORD"],
484
- ["b", "LWORD"]
485
- ], (name) => `x := a;
486
- y := b;
487
- FOR i := 1 TO 64 DO
488
- carry := SHL(x AND y, 1);
489
- x := x XOR y;
490
- y := carry;
491
- END_FOR;
492
- ${name} := x;
493
- `, ` x, y, carry : LWORD;
494
- i : UINT;`);
689
+ walk(settings, routine, items, prefixes, guards) {
690
+ for (const [index, item] of items.entries()) {
691
+ const here = [...prefixes, items.slice(0, index)];
692
+ this.probe(settings, routine, item, here, guards);
693
+ const guard = (conditions) => [
694
+ ...guards,
695
+ { conditions, depth: here.length }
696
+ ];
697
+ if (item.kind === "if") {
698
+ this.walk(settings, routine, item.then, here, guard([item.condition]));
699
+ this.walk(settings, routine, item.else, here, guard([item.condition]));
700
+ }
701
+ if (item.kind === "switch") {
702
+ for (const body of nestedBodies2(item)) {
703
+ this.walk(settings, routine, body, here, guard([item.value]));
704
+ }
705
+ }
706
+ if (item.kind === "for") {
707
+ this.walk(settings, routine, item.body, here, guards);
708
+ }
709
+ }
495
710
  }
496
- wrap64(operator) {
497
- const add = this.add64();
498
- if (operator === "add") {
499
- return add;
711
+ probe(settings, routine, item, prefixes, guards) {
712
+ const task = this.tasks.get(routine.id);
713
+ const probes = [];
714
+ const written = writtenPlace(item);
715
+ if (written && settings.writers) {
716
+ let site;
717
+ this.outputs.forEach((output, index) => {
718
+ const when = this.reaches(written.root, written.path, output);
719
+ if (!when) {
720
+ return;
721
+ }
722
+ site ??= ++this.writerSites;
723
+ this.writers[index].push({
724
+ id: site,
725
+ routine: routine.id,
726
+ span: item.span,
727
+ statement: item
728
+ });
729
+ probes.push({ kind: "writer", site, output: index, when });
730
+ });
500
731
  }
501
- if (operator === "subtract") {
502
- return this.helper("subtract64", "LWORD", [
503
- ["a", "LWORD"],
504
- ["b", "LWORD"]
505
- ], (name) => `${name} := ${add}(a, ${add}(NOT b, LWORD#1));
506
- `);
732
+ if (settings.trace && task) {
733
+ if (item.kind === "assign") {
734
+ const root = this.variables.get(item.root);
735
+ const type = this.placeType(root, item.path);
736
+ const path = root.storage === "module" ? storagePath(root, item.path) : undefined;
737
+ if (type?.kind === "enum" && path) {
738
+ const operands = this.operands(routine, prefixes, guards, settings.trace);
739
+ const site = this.site({
740
+ kind: "state",
741
+ path,
742
+ routine: routine.id,
743
+ type: type.id,
744
+ span: item.span,
745
+ task,
746
+ operands
747
+ });
748
+ probes.push({ kind: "state", value: item.value, site, operands });
749
+ }
750
+ }
751
+ if (item.kind === "return" && item.value && "parameters" in routine && routine.result && this.callSites.get(routine.id) === 1) {
752
+ const type = this.types.get(routine.result);
753
+ if (type?.kind === "enum") {
754
+ const slot = this.decisions.get(routine.id) ?? this.decisions.size;
755
+ this.decisions.set(routine.id, slot);
756
+ const path = routine.origin?.instance ? `${routine.origin.instance}.${routine.origin.name.split(".").at(-1)}` : routine.origin?.name ?? routine.name;
757
+ const operands = this.operands(routine, prefixes, guards, settings.trace);
758
+ const site = this.site({
759
+ kind: "decision",
760
+ path,
761
+ routine: routine.id,
762
+ type: type.id,
763
+ span: item.span,
764
+ task,
765
+ operands
766
+ });
767
+ probes.push({
768
+ kind: "decision",
769
+ value: item.value,
770
+ site,
771
+ slot,
772
+ operands
773
+ });
774
+ }
775
+ }
507
776
  }
508
- if (operator !== "multiply") {
509
- throw new Error("Unsupported verified wrapping operation");
777
+ if (probes.length) {
778
+ this.probes.set(item, probes);
510
779
  }
511
- return this.helper("multiply64", "LWORD", [
512
- ["a", "LWORD"],
513
- ["b", "LWORD"]
514
- ], (name) => `x := a;
515
- y := b;
516
- result := LWORD#0;
517
- FOR i := 1 TO 64 DO
518
- IF (y AND LWORD#1) <> LWORD#0 THEN
519
- result := ${add}(result, x);
520
- END_IF;
521
- x := SHL(x, 1);
522
- y := SHR(y, 1);
523
- END_FOR;
524
- ${name} := result;
525
- `, ` x, y, result : LWORD;
526
- i : UINT;`);
527
780
  }
528
- arithmetic(typeId, operator, policy) {
529
- const type = this.types.get(typeId);
530
- if (type?.kind !== "integer") {
531
- throw new Error("Expected verified integer arithmetic");
532
- }
533
- const token = operatorTokens[operator];
534
- if (!token) {
535
- throw new Error("Expected verified integer arithmetic");
781
+ reaches(root, path, output) {
782
+ if (root !== output.root.id) {
783
+ return;
536
784
  }
537
- const key = `${policy}_${operator}_${typeId}`;
538
- if (policy === "wrap") {
539
- if (type.bits === 64) {
540
- const operation = this.wrap64(operator);
541
- return this.helper(key, typeId, [
542
- ["a", typeId],
543
- ["b", typeId]
544
- ], (name) => `${name} := LWORD_TO_${typeId}(${operation}(${typeId}_TO_LWORD(a), ${typeId}_TO_LWORD(b)));
545
- `);
785
+ const when = [];
786
+ for (const [index, written] of path.entries()) {
787
+ const bound = output.segments[index];
788
+ if (!bound) {
789
+ break;
546
790
  }
547
- const wide = !type.signed && operator !== "subtract" ? "ULINT" : "LINT";
548
- return this.helper(key, typeId, [
549
- ["a", typeId],
550
- ["b", typeId]
551
- ], (name) => `${name} := ${wide}_TO_${typeId}(${typeId}_TO_${wide}(a) ${token} ${typeId}_TO_${wide}(b));
552
- `);
553
- }
554
- const [minimum, maximum] = integerRange(type);
555
- const min = `${typeId}#${minimum}`;
556
- const max = `${typeId}#${maximum}`;
557
- const zero = `${typeId}#0`;
558
- return this.helper(key, typeId, [
559
- ["a", typeId],
560
- ["b", typeId]
561
- ], (name) => {
562
- const clamp = (condition, endpoint, depth = "") => `${depth}IF ${condition} THEN
563
- ${depth} ${name} := ${endpoint};
564
- ${depth} RETURN;
565
- ${depth}END_IF;
566
- `;
567
- const guard = () => {
568
- if (!type.signed) {
569
- if (operator === "add") {
570
- return clamp(`a > ${max} - b`, max);
791
+ if (written.kind === "field") {
792
+ if (bound.kind !== "field" || bound.name !== written.name) {
793
+ return;
794
+ }
795
+ continue;
796
+ }
797
+ if (bound.kind !== "index") {
798
+ return;
799
+ }
800
+ const value = constantIndex(written.value);
801
+ if (value === undefined) {
802
+ when.push({ index: written.value, value: bound.value });
803
+ } else if (value !== bound.value) {
804
+ return;
805
+ }
806
+ }
807
+ return when;
808
+ }
809
+ definitions(routine) {
810
+ const cached = this.temporaries.get(routine.id);
811
+ if (cached) {
812
+ return cached;
813
+ }
814
+ const definitions = new Map;
815
+ const define = (items) => {
816
+ for (const item of items) {
817
+ const target = wholeTarget(item);
818
+ if (target && temporary(target)) {
819
+ definitions.set(target, [...definitions.get(target) ?? [], item]);
820
+ }
821
+ for (const body of nestedBodies2(item)) {
822
+ define(body);
823
+ }
824
+ }
825
+ };
826
+ define(routine.body);
827
+ this.temporaries.set(routine.id, definitions);
828
+ return definitions;
829
+ }
830
+ operands(routine, prefixes, guards, trace) {
831
+ const definitions = this.definitions(routine);
832
+ const result = [];
833
+ const seen = new Set;
834
+ for (const guard of [...guards].reverse()) {
835
+ const executed = new Set(prefixes.slice(0, guard.depth).flat());
836
+ const between = this.statementWrites(prefixes.slice(guard.depth).flat());
837
+ const add = (span, capture, read) => {
838
+ const kind = this.types.get(capture.type)?.kind;
839
+ const key = `${span.file}:${span.start}:${span.end}`;
840
+ if (seen.has(key) || !["bool", "enum", "integer", "bits"].includes(kind ?? "")) {
841
+ return;
842
+ }
843
+ seen.add(key);
844
+ const path = read && storagePath(this.variables.get(read.root), read.path);
845
+ result.push({
846
+ capture,
847
+ span,
848
+ ...path && { path },
849
+ stable: !read || !between.has(read.root)
850
+ });
851
+ };
852
+ const direct = (value) => (value.path ?? []).every((segment) => segment.kind === "field" || constantIndex(segment.value) !== undefined);
853
+ const visit = (value, evaluated) => {
854
+ if (value.kind === "unary" || value.kind === "convert") {
855
+ visit(value.operand, evaluated);
856
+ }
857
+ if (value.kind === "binary") {
858
+ visit(value.left, evaluated);
859
+ visit(value.right, evaluated);
860
+ }
861
+ if (value.kind !== "load") {
862
+ return;
863
+ }
864
+ if (!temporary(value.root)) {
865
+ if (evaluated || direct(value)) {
866
+ add(value.span, value, value);
571
867
  }
572
- if (operator === "subtract") {
573
- return clamp("a < b", zero);
868
+ return;
869
+ }
870
+ const defined = definitions.get(value.root) ?? [];
871
+ const [item] = defined;
872
+ if (!item || defined.length !== 1) {
873
+ for (const definition of defined) {
874
+ if (definition.kind === "assign") {
875
+ visit(definition.value, evaluated && executed.has(definition));
876
+ }
574
877
  }
575
- return `IF b <> ${zero} THEN
576
- ${clamp(`a > ${max} / b`, max, " ")}END_IF;
577
- `;
878
+ return;
578
879
  }
579
- if (operator === "add") {
580
- return `IF b > ${zero} THEN
581
- ${clamp(`a > ${max} - b`, max, " ")}ELSIF b < ${zero} THEN
582
- ${clamp(`a < ${min} - b`, min, " ")}END_IF;
583
- `;
880
+ const reached = evaluated && executed.has(item);
881
+ if (item.kind === "invoke") {
882
+ if (reached) {
883
+ add(item.span, value);
884
+ }
885
+ return;
584
886
  }
585
- if (operator === "subtract") {
586
- return `IF b < ${zero} THEN
587
- ${clamp(`a > ${max} + b`, max, " ")}ELSIF b > ${zero} THEN
588
- ${clamp(`a < ${min} + b`, min, " ")}END_IF;
589
- `;
887
+ if (item.kind !== "assign") {
888
+ return;
590
889
  }
591
- return clamp(`a = ${zero}`, zero) + clamp(`b = ${zero}`, zero) + `IF a > ${zero} THEN
592
- IF b > ${zero} THEN
593
- ${clamp(`a > ${max} / b`, max, " ")} ELSE
594
- ${clamp(`b < ${min} / a`, min, " ")} END_IF;
595
- ELSE
596
- IF b > ${zero} THEN
597
- ${clamp(`a < ${min} / b`, min, " ")} ELSE
598
- ${clamp(`a < ${max} / b`, max, " ")} END_IF;
599
- END_IF;
600
- `;
890
+ const source = item.value;
891
+ if (source.kind === "load" && !temporary(source.root)) {
892
+ const read = {
893
+ ...source,
894
+ type: value.type,
895
+ path: [...source.path ?? [], ...value.path ?? []]
896
+ };
897
+ if (reached) {
898
+ add(source.span, value, read);
899
+ } else if (direct(read)) {
900
+ add(source.span, read, read);
901
+ }
902
+ return;
903
+ }
904
+ visit(source, reached);
601
905
  };
602
- return `${guard()}${name} := a ${token} b;
603
- `;
604
- });
605
- }
606
- truncation(typeId) {
607
- const type = this.types.get(typeId);
608
- if (type?.kind !== "float") {
609
- throw new Error("Expected verified float truncation");
610
- }
611
- const whole = scalarLiteral({ kind: "float", value: 2 ** (type.bits === 32 ? 23 : 52) }, typeId);
612
- return this.helper(`truncate_${typeId}`, typeId, [["value", typeId]], (name) => `IF ABS(value) >= ${whole} THEN
613
- ${name} := value;
614
- RETURN;
615
- END_IF;
616
- nearest := TO_LINT(value);
617
- IF value >= 0 AND TO_${typeId}(nearest) > value THEN
618
- nearest := nearest - 1;
619
- ELSIF value < 0 AND TO_${typeId}(nearest) < value THEN
620
- nearest := nearest + 1;
621
- END_IF;
622
- ${name} := TO_${typeId}(nearest);
623
- `, " nearest : LINT;");
624
- }
625
- saturation(sourceId, targetId) {
626
- const source = this.types.get(sourceId);
627
- const target = this.types.get(targetId);
628
- if (source?.kind === "float" && target?.kind === "float") {
629
- if (source.bits <= target.bits) {
630
- return `TO_${targetId}`;
906
+ for (const condition of guard.conditions) {
907
+ visit(condition, true);
631
908
  }
632
- const maximum = floatMaximum(target);
633
- const literal = (value, type) => scalarLiteral({ kind: "float", value }, type);
634
- return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => `IF value < ${literal(-maximum, sourceId)} THEN
635
- ${name} := ${literal(-maximum, targetId)};
636
- RETURN;
637
- END_IF;
638
- IF value > ${literal(maximum, sourceId)} THEN
639
- ${name} := ${literal(maximum, targetId)};
640
- RETURN;
641
- END_IF;
642
- ${name} := TO_${targetId}(value);
643
- `);
644
- }
645
- if (!source || !target || !integerType(source) || !integerType(target)) {
646
- throw new Error("Expected verified integer saturation");
647
909
  }
648
- const [fromMin, fromMax] = integerRange(source);
649
- const [toMin, toMax] = integerRange(target);
650
- return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => {
651
- let body = "";
652
- if (fromMin < toMin) {
653
- body += `IF value < ${sourceId}#${toMin} THEN
654
- ${name} := ${targetId}#${toMin};
655
- RETURN;
656
- END_IF;
657
- `;
658
- }
659
- if (fromMax > toMax) {
660
- body += `IF value > ${sourceId}#${toMax} THEN
661
- ${name} := ${targetId}#${toMax};
662
- RETURN;
663
- END_IF;
664
- `;
665
- }
666
- return `${body}${name} := TO_${targetId}(value);
667
- `;
668
- });
910
+ return result.slice(0, trace.operands);
669
911
  }
670
912
  }
671
913
 
672
- // packages/compiler/src/codesys/types.ts
673
- var sourceTypeName = (id) => id.slice(id.lastIndexOf(":") + 1);
674
- var stringTypeName = (type) => type.encoding === "utf8" ? "STRING" : "WSTRING";
675
- var stEscapes = new Map([
676
- ["$", "$$"],
677
- ["'", "$'"],
678
- ["\r", "$R"],
679
- [`
680
- `, "$N"]
681
- ]);
682
- var stStringLiteral = (text) => `'${[...text].map((character) => stEscapes.get(character) ?? character).join("")}'`;
683
- var anonymousRecordId = /:\d+:record(<.*>)?$/;
684
- var required = (value) => {
685
- if (value === undefined) {
686
- throw new Error("Missing verified type name");
687
- }
688
- return value;
689
- };
914
+ // packages/compiler/src/codesys/global-lists.ts
915
+ import {
916
+ defaultValue,
917
+ instancedBlock as instancedBlock5
918
+ } from "@tsplc/compiler/ir";
690
919
 
691
- class CodesysTypes {
692
- types;
693
- objects = [];
694
- names = new Map;
695
- fields = new Map;
696
- aliases = new Set;
697
- shapes = new Map;
698
- constructor(types, names, blockNames) {
699
- this.types = types;
700
- const anonymous = new Map;
701
- for (const type of types.values()) {
702
- const shape = this.anonymousShape(type);
703
- const shared = shape === null ? undefined : anonymous.get(shape);
704
- if (shared !== undefined) {
705
- this.names.set(type.id, required(this.names.get(shared)));
706
- this.fields.set(type.id, required(this.fields.get(shared)));
707
- this.aliases.add(type.id);
708
- continue;
709
- }
710
- if (shape !== null) {
711
- anonymous.set(shape, type.id);
712
- }
713
- if (type.kind === "block") {
714
- const name = blockNames.get(type.block);
715
- if (!name) {
716
- throw new Error("Missing verified block name");
717
- }
718
- this.names.set(type.id, name);
719
- }
720
- if (["record", "array", "enum", "string"].includes(type.kind)) {
721
- const label = sourceTypeName(type.id);
722
- if (type.kind === "record" || type.kind === "enum") {
723
- const prefix = type.kind === "record" ? "ST" : "E";
724
- this.names.set(type.id, names.allocateObject(prefix, label));
725
- } else {
726
- this.names.set(type.id, names.allocate(`T_${label}`));
727
- }
728
- }
729
- if (type.kind === "record" || type.kind === "enum") {
730
- const names = new Names;
731
- const fields = new Map;
732
- for (const member of type.kind === "record" ? type.fields : type.members) {
733
- fields.set(member.name, names.allocate(member.name));
734
- }
735
- this.fields.set(type.id, fields);
736
- }
737
- }
738
- for (const type of types.values()) {
739
- if (type.kind === "array" && instancedBlock2(type.id, types)) {
740
- this.names.set(type.id, `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`);
741
- }
742
- }
743
- const emitted = new Set;
744
- const emit = (type) => {
745
- if (instancedBlock2(type.id, types) || !this.names.has(type.id) || this.aliases.has(type.id) || emitted.has(type.id)) {
746
- return;
920
+ // packages/compiler/src/codesys/io-paths.ts
921
+ import { ioLayout } from "@tsplc/typegen/hardware";
922
+ var pathPattern = /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
923
+ var isStoragePath = (key) => key.includes(".") || key.includes("[");
924
+ function resolveStoragePath(core, key) {
925
+ const match = pathPattern.exec(key);
926
+ if (!match) {
927
+ return {
928
+ error: `${key}: expected Module.variable followed by .field or [index].`
929
+ };
930
+ }
931
+ const [, module, name, rest] = match;
932
+ const roots = core.variables.filter((item) => item.storage === "module" && item.name === name && moduleName(item) === module);
933
+ const [root] = roots;
934
+ if (!root || roots.length !== 1) {
935
+ return {
936
+ error: root ? `${key}: ${module}.${name} is declared by more than one module named ${module}.` : `${key}: no mutable module variable ${module}.${name}.`
937
+ };
938
+ }
939
+ const types = new Map(core.types.map((type) => [type.id, type]));
940
+ let type = types.get(root.type);
941
+ const segments = [];
942
+ for (const [, field, index] of rest.matchAll(/\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g)) {
943
+ if (field !== undefined) {
944
+ const member = type.kind === "record" ? type.fields.find((f) => f.name === field) : undefined;
945
+ if (!member) {
946
+ return { error: `${key}: no field ${field}.` };
747
947
  }
748
- if (type.kind === "array") {
749
- emit(this.type(type.element));
948
+ segments.push({ kind: "field", record: type.id, name: field });
949
+ type = types.get(member.type);
950
+ } else {
951
+ const value = Number(index);
952
+ if (type.kind !== "array") {
953
+ return { error: `${key}: ${index} indexes a non-array value.` };
750
954
  }
751
- if (type.kind === "record") {
752
- for (const field of type.fields) {
753
- emit(this.type(field.type));
754
- }
955
+ if (value < type.lowerBound || value >= type.lowerBound + type.length) {
956
+ return {
957
+ error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`
958
+ };
755
959
  }
756
- emitted.add(type.id);
757
- const name = this.name(type.id);
758
- const declaration = this.dutDeclaration(type, name);
759
- this.objects.push({ id: type.id, kind: "dataType", name, declaration });
760
- };
761
- for (const type of types.values()) {
762
- emit(type);
960
+ segments.push({ kind: "index", value });
961
+ type = types.get(type.element);
763
962
  }
764
963
  }
765
- anonymousShape(type) {
766
- if (type.kind !== "record" || !anonymousRecordId.test(type.id)) {
767
- return null;
768
- }
769
- const known = this.shapes.get(type.id);
770
- if (known !== undefined) {
771
- return known;
772
- }
773
- const shape = JSON.stringify(type.fields.map((field) => [
774
- field.name,
775
- this.anonymousShape(this.type(field.type)) ?? field.type
776
- ]));
777
- this.shapes.set(type.id, shape);
778
- return shape;
964
+ return { key, root, segments, type };
965
+ }
966
+ function iecSpelling(type, types) {
967
+ if (type.kind === "bool" || type.kind === "integer" || type.kind === "bits" || type.kind === "float" || type.kind === "duration" || type.kind === "calendar") {
968
+ return type.id;
779
969
  }
780
- dutDeclaration(type, name) {
970
+ if (type.kind !== "array") {
971
+ return;
972
+ }
973
+ const element = iecSpelling(types.get(type.element), types);
974
+ const upper = type.lowerBound + type.length - 1;
975
+ return element && !element.startsWith("ARRAY") ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}` : undefined;
976
+ }
977
+ function ioTargets(core) {
978
+ const types = new Map(core.types.map((type) => [type.id, type]));
979
+ const targets = [];
980
+ const add = (key, type) => {
981
+ const layout = ioLayout(iecSpelling(type, types) ?? "");
982
+ if (layout) {
983
+ targets.push({ key, layout });
984
+ }
985
+ };
986
+ const visit = (key, type) => {
987
+ add(key, type);
781
988
  if (type.kind === "record") {
782
- const fields = type.fields.map((field) => ` ${this.field(type.id, field.name)} : ${this.name(field.type)};`).join(`
783
- `);
784
- return `TYPE ${name} :
785
- STRUCT
786
- ${fields}
787
- END_STRUCT
788
- END_TYPE
789
- `;
989
+ for (const field of type.fields) {
990
+ visit(`${key}.${field.name}`, types.get(field.type));
991
+ }
790
992
  }
791
993
  if (type.kind === "array") {
792
- return `${type.index ? `{attribute 'tsplc_keyed'}
793
- ` : ""}TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
794
- END_TYPE
795
- `;
796
- }
797
- if (type.kind === "string") {
798
- return `TYPE ${name} : ${stringTypeName(type)}(${type.capacity});
799
- END_TYPE
800
- `;
994
+ visit(`${key}[\${number}]`, types.get(type.element));
801
995
  }
802
- if (type.kind === "enum") {
803
- const members = type.members.map((member) => ` ${this.field(type.id, member.name)} := ${member.value}`).join(`,
804
- `);
805
- return `{attribute 'qualified_only'}
806
- {attribute 'strict'}
807
- TYPE ${name} : (
808
- ${members}
809
- ) DINT;
810
- END_TYPE
811
- `;
996
+ };
997
+ for (const variable of core.variables) {
998
+ if (variable.storage === "input" || variable.storage === "output") {
999
+ add(variable.name, types.get(variable.type));
1000
+ } else if (variable.storage === "module") {
1001
+ visit(`${moduleName(variable)}.${variable.name}`, types.get(variable.type));
812
1002
  }
813
- throw new Error("Unsupported verified data type");
814
1003
  }
815
- type(id) {
816
- const type = this.types.get(id);
817
- if (!type) {
818
- throw new Error("Missing verified type");
819
- }
820
- return type;
1004
+ return targets;
1005
+ }
1006
+
1007
+ // packages/compiler/src/codesys/symbols.ts
1008
+ import {
1009
+ standardBlocks as standardBlocks2
1010
+ } from "@tsplc/compiler/ir";
1011
+
1012
+ // packages/compiler/src/codesys/global-names.ts
1013
+ import { standardBlocks } from "@tsplc/compiler/ir";
1014
+
1015
+ // packages/compiler/src/codesys/types.ts
1016
+ import { instancedBlock as instancedBlock4, nanosecondsPerMillisecond as nanosecondsPerMillisecond2 } from "@tsplc/compiler/ir";
1017
+ import { escapeString } from "@tsplc/iec/st";
1018
+
1019
+ // packages/compiler/src/codesys/numeric.ts
1020
+ import {
1021
+ integerRange,
1022
+ integerType,
1023
+ nestedBodies as nestedBodies3,
1024
+ pathIndexes,
1025
+ statementExpressions as statementExpressions2,
1026
+ subexpressions as subexpressions2
1027
+ } from "@tsplc/compiler/ir";
1028
+ import {
1029
+ floatMaximum,
1030
+ isElementary
1031
+ } from "@tsplc/iec/arithmetic";
1032
+ var elementaryNames = {
1033
+ sqrt: "SQRT",
1034
+ ln: "LN",
1035
+ log10: "LOG",
1036
+ exp: "EXP",
1037
+ sin: "SIN",
1038
+ cos: "COS",
1039
+ tan: "TAN",
1040
+ asin: "ASIN",
1041
+ acos: "ACOS",
1042
+ atan: "ATAN"
1043
+ };
1044
+ var operatorTokens = {
1045
+ add: "+",
1046
+ subtract: "-",
1047
+ multiply: "*",
1048
+ divide: "/",
1049
+ remainder: "MOD",
1050
+ equal: "=",
1051
+ notEqual: "<>",
1052
+ less: "<",
1053
+ lessEqual: "<=",
1054
+ greater: ">",
1055
+ greaterEqual: ">=",
1056
+ bitAnd: "AND",
1057
+ bitOr: "OR",
1058
+ bitXor: "XOR"
1059
+ };
1060
+ function scalarLiteral(value, type) {
1061
+ if (value.kind === "bool") {
1062
+ return value.value ? "TRUE" : "FALSE";
821
1063
  }
822
- name(id) {
823
- return this.names.get(id) ?? id;
1064
+ if (value.kind === "integer") {
1065
+ return `${type}#${value.value}`;
824
1066
  }
825
- field(id, name) {
826
- const field = this.fields.get(id)?.get(name);
827
- if (!field) {
828
- throw new Error("Missing verified field");
829
- }
830
- return field;
1067
+ if (value.kind === "float") {
1068
+ const text = Object.is(value.value, -0) ? "-0.0" : String(value.value).replace(/e/i, "E");
1069
+ return `${type}#${text}`;
831
1070
  }
832
- declarationInitializer(value, id) {
833
- const type = this.type(id);
834
- if ((type.kind === "record" || type.kind === "array") && this.isZero(value)) {
835
- return "";
836
- }
837
- return ` := ${this.initializer(value, id)}`;
1071
+ throw new Error("Expected verified scalar constant");
1072
+ }
1073
+
1074
+ class NumericLowering {
1075
+ types;
1076
+ allocate;
1077
+ objects = [];
1078
+ helpers = new Map;
1079
+ constructor(types, allocate) {
1080
+ this.types = types;
1081
+ this.allocate = allocate;
838
1082
  }
839
- initializer(value, id) {
840
- const type = this.type(id);
841
- if (type.kind === "array" && value.kind === "array") {
842
- return `[${value.items.map((item) => this.initializer(item, type.element)).join(", ")}]`;
1083
+ prepare(value) {
1084
+ for (const operand of subexpressions2(value)) {
1085
+ this.prepare(operand);
843
1086
  }
844
- if (type.kind !== "record" || value.kind !== "record") {
845
- return this.literal(value, id);
846
- }
847
- const fields = type.fields.flatMap((field) => {
848
- const initial = value.fields[field.name];
849
- if (!initial) {
850
- throw new Error("Missing verified record initializer");
851
- }
852
- return this.type(field.type).kind !== "enum" && this.isZero(initial) ? [] : [
853
- `${this.field(id, field.name)} := ${this.initializer(initial, field.type)}`
854
- ];
855
- });
856
- return fields.length ? `(${fields.join(", ")})` : this.literal(value, id);
857
- }
858
- isZero(value) {
859
- if (value.kind === "bool") {
860
- return !value.value;
861
- }
862
- if (value.kind === "integer") {
863
- return value.value === "0";
864
- }
865
- if (value.kind === "float") {
866
- return Object.is(value.value, 0);
867
- }
868
- if (value.kind === "string") {
869
- return value.value === "";
1087
+ if (value.kind === "binary" && value.policy) {
1088
+ this.arithmetic(value.type, value.operator, value.policy);
870
1089
  }
871
- if (value.kind === "array") {
872
- return value.items.every((item) => this.isZero(item));
1090
+ if (value.kind === "convert" && value.policy === "saturate") {
1091
+ this.saturation(value.operand.type, value.type);
873
1092
  }
874
- if (value.kind === "record") {
875
- return Object.values(value.fields).every((item) => this.isZero(item));
1093
+ if (value.kind === "unary" && value.operator === "truncate") {
1094
+ this.truncation(value.type);
876
1095
  }
877
- return false;
878
1096
  }
879
- literal(value, id) {
880
- const type = this.type(id);
881
- if (type.kind === "enum" && value.kind === "integer") {
882
- const member = type.members.find((member) => member.value === value.value);
883
- if (!member) {
884
- throw new Error("Missing verified enum member");
1097
+ prepareStatements(items) {
1098
+ for (const item of items) {
1099
+ const values = item.kind === "assign" ? [item.value, ...pathIndexes(item.path)] : statementExpressions2(item);
1100
+ for (const value of values) {
1101
+ this.prepare(value);
1102
+ }
1103
+ for (const body of nestedBodies3(item)) {
1104
+ this.prepareStatements(body);
885
1105
  }
886
- return `${this.name(id)}.${this.field(id, member.name)}`;
887
1106
  }
888
- if (type.kind === "string" && value.kind === "string") {
889
- const delimiter = type.encoding === "utf16" ? '"' : "'";
890
- return `${delimiter}${escapeString(value.value, delimiter)}${delimiter}`;
1107
+ }
1108
+ render(value, operands) {
1109
+ if (value.kind === "convert") {
1110
+ return value.policy === "saturate" ? `${this.saturation(value.operand.type, value.type)}(${operands[0]})` : `TO_${value.type}(${operands[0]})`;
891
1111
  }
892
- if (type.kind === "array" && value.kind === "array") {
893
- return `[${value.items.map((item) => this.literal(item, type.element)).join(", ")}]`;
1112
+ if (value.kind === "unary") {
1113
+ if (value.operator === "timeToMilliseconds") {
1114
+ return `TIME_TO_UDINT(${operands[0]})`;
1115
+ }
1116
+ if (value.operator === "clock") {
1117
+ return "TO_DINT(TIME_TO_UDINT(TIME()))";
1118
+ }
1119
+ if (isElementary(value.operator)) {
1120
+ return `${elementaryNames[value.operator]}(${operands[0]})`;
1121
+ }
1122
+ if (value.operator === "truncate") {
1123
+ return `${this.truncation(value.type)}(${operands[0]})`;
1124
+ }
1125
+ return value.operator === "not" ? `(NOT ${operands[0]})` : `TO_${value.type}(${value.operator === "negate" ? "-" : "NOT "}${operands[0]})`;
894
1126
  }
895
- if (type.kind === "record" && value.kind === "record") {
896
- const fields = type.fields.map((field) => {
897
- const initial = value.fields[field.name];
898
- if (!initial) {
899
- throw new Error("Missing verified record initializer");
900
- }
901
- return `${this.field(id, field.name)} := ${this.literal(initial, field.type)}`;
902
- });
903
- return `(${fields.join(", ")})`;
1127
+ if (value.kind !== "binary") {
1128
+ throw new Error("Expected numeric operation");
904
1129
  }
905
- if (type.kind === "duration" && value.kind === "duration") {
906
- return `T#${BigInt(value.nanoseconds) / nanosecondsPerMillisecond}ms`;
1130
+ if (value.policy) {
1131
+ return `${this.arithmetic(value.type, value.operator, value.policy)}(${operands.join(", ")})`;
907
1132
  }
908
- if (type.kind === "calendar" && value.kind === "calendar") {
909
- if (type.domain === "date") {
910
- return `D#${value.value}`;
911
- }
912
- if (type.domain === "timeOfDay") {
913
- return `TOD#${value.value}`;
914
- }
915
- return `DT#${value.value.replace("T", "-")}`;
1133
+ if (value.operator === "power") {
1134
+ return `EXPT(${operands.join(", ")})`;
916
1135
  }
917
- return scalarLiteral(value, id);
918
- }
919
- }
920
-
921
- // packages/compiler/src/codesys/global-names.ts
922
- var planGlobalNames = (core, programNames = {}) => {
923
- const names = new Names;
924
- for (const name of Object.values(programNames)) {
925
- names.reserve(name);
926
- }
927
- const typeMap = new Map(core.types.map((type) => [type.id, type]));
928
- const blockNames = new Map(core.blocks.map((block) => [
929
- block.id,
930
- block.standard ? standardBlocks[block.standard].native : names.allocateObject("FB", block.name)
931
- ]));
932
- for (const name of blockNames.values()) {
933
- names.reserve(name);
934
- }
935
- const targetTypes = new CodesysTypes(typeMap, names, blockNames);
936
- const { globalLists, retainedVariables } = storageLayout(core);
937
- const hasExports = (group) => group.variables.some((variable) => variable.exported && !variable.exposure);
938
- const globals = globalLists.map((group) => {
939
- const splitByStorage = globalLists.some((other) => other.module === group.module && other.kind !== group.kind && hasExports(other));
940
- const name = hasExports(group) ? names.allocate(pascalCase(splitByStorage ? `${group.module}-${group.kind}` : group.module)) : names.allocateObject("GVL", `${group.module}_${group.kind}`);
941
- const fields = new Names;
942
- for (const name of blockNames.values()) {
943
- fields.reserve(name);
1136
+ if (value.operator === "shiftLeft" || value.operator === "shiftRight") {
1137
+ const shift = value.operator === "shiftLeft" ? "SHL" : "SHR";
1138
+ return `TO_${value.type}(${shift}(${operands.join(", ")}))`;
944
1139
  }
945
- return {
946
- ...group,
947
- name,
948
- fields: new Map(group.variables.map((item) => [item.id, fields.allocate(item.name)]))
949
- };
950
- });
951
- return {
952
- names,
953
- typeMap,
954
- blockNames,
955
- targetTypes,
956
- globals,
957
- retainedVariables
958
- };
959
- };
960
-
961
- // packages/compiler/src/codesys/task-access.ts
962
- import {
963
- instancedBlock as instancedBlock3,
964
- nanosecondsPerMillisecond as nanosecondsPerMillisecond2,
965
- nestedBodies as nestedBodies2,
966
- statementExpressions as statementExpressions2,
967
- subexpressions as subexpressions2
968
- } from "@tsplc/compiler/ir";
969
- var variablesById = (core) => new Map([
970
- ...core.variables,
971
- ...core.functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
972
- ...core.blocks.flatMap((block) => [
973
- ...block.inputs,
974
- ...block.outputs,
975
- ...block.state,
976
- ...block.locals
977
- ])
978
- ].map((variable) => [variable.id, variable]));
979
- function routineTasks(core, deployment) {
980
- const tasks = new Map;
981
- const types = new Map(core.types.map((type) => [type.id, type]));
982
- const routines = new Map([...core.functions, ...core.blocks].map((routine) => [routine.id, routine]));
983
- const variables = variablesById(core);
984
- const programs = new Map(core.programs.map((program) => [program.name, program]));
985
- for (const task of deployment.tasks) {
986
- for (const name of task.programs) {
987
- const seen = new Set;
988
- const visit = (id) => {
989
- if (seen.has(id)) {
990
- return;
991
- }
992
- seen.add(id);
993
- tasks.set(id, tasks.has(id) && tasks.get(id) !== task.name ? undefined : task.name);
994
- const inspect = (items) => {
995
- for (const item of items) {
996
- if (item.kind === "invoke") {
997
- visit(item.function);
998
- }
999
- if (item.kind === "blockUpdate") {
1000
- const block = instancedBlock3(variables.get(item.instance).type, types);
1001
- if (block) {
1002
- visit(block.block);
1003
- }
1004
- }
1005
- for (const body of nestedBodies2(item)) {
1006
- inspect(body);
1007
- }
1008
- }
1009
- };
1010
- inspect(routines.get(id)?.body ?? []);
1011
- };
1012
- visit(programs.get(name).entry);
1140
+ const token = operatorTokens[value.operator];
1141
+ if (!token) {
1142
+ throw new Error("Boolean short-circuit operation was not normalized");
1013
1143
  }
1144
+ const text = value.operator === "remainder" ? `(${operands[0]} - (${operands[0]} / ${operands[1]}) * ${operands[1]})` : `(${operands[0]} ${token} ${operands[1]})`;
1145
+ return value.type === "BOOL" ? text : `TO_${value.type}(${text})`;
1014
1146
  }
1015
- return tasks;
1016
- }
1017
- function schedulePrograms(core, tasks, report) {
1018
- const background = new Map;
1019
- for (const program of core.programs) {
1020
- if (!program.background) {
1021
- continue;
1022
- }
1023
- const { priority, intervalNanoseconds } = program.background;
1024
- const name = `TsplcBackground_${priority}_${BigInt(intervalNanoseconds) / nanosecondsPerMillisecond2}`;
1025
- const existing = background.get(name);
1147
+ helper(key, type, inputs, body, locals = "") {
1148
+ const existing = this.helpers.get(key);
1026
1149
  if (existing) {
1027
- existing.programs.push(program.name);
1028
- continue;
1150
+ return existing;
1029
1151
  }
1030
- background.set(name, {
1152
+ const name = this.allocate(`numeric_${key}`);
1153
+ this.helpers.set(key, name);
1154
+ const parameters = inputs.map(([input, inputType]) => ` ${input} : ${inputType};`).join(`
1155
+ `);
1156
+ const variables = locals ? `VAR
1157
+ ${locals}
1158
+ END_VAR
1159
+ ` : "";
1160
+ const declaration = `FUNCTION ${name} : ${type}
1161
+ VAR_INPUT
1162
+ ${parameters}
1163
+ END_VAR
1164
+ ${variables}`;
1165
+ this.objects.push({
1166
+ id: `numeric:${key}`,
1167
+ kind: "function",
1031
1168
  name,
1032
- priority,
1033
- intervalNanoseconds,
1034
- programs: [program.name]
1169
+ declaration,
1170
+ implementation: body(name)
1035
1171
  });
1172
+ return name;
1036
1173
  }
1037
- return appendContinuations(core, [...tasks, ...background.values()], report);
1038
- }
1039
- function taskStorageOwnership(core, report) {
1040
- const owners = new Map;
1041
- const globals = new Map(core.variables.map((item) => [item.id, item]));
1042
- const functions = new Map(core.functions.map((item) => [item.id, item]));
1043
- const blocks = new Map(core.blocks.map((block) => [block.id, block.runtime?.kind]));
1044
- const runtimes = new Map(core.types.flatMap((type) => type.kind === "block" ? [[type.id, blocks.get(type.block)]] : []));
1045
- return (task, program) => {
1046
- const fn = functions.get(program.entry);
1047
- if (!fn) {
1048
- throw new Error("Verified core has a missing entry.");
1049
- }
1050
- const worker = program.background?.worker;
1051
- const host = worker && core.variables.find((item) => item.name === worker && item.span.file === fn.span.file && runtimes.get(item.type) === "backgroundHost");
1052
- for (const id of accessedStorage(fn, core, host ? host.id : undefined)) {
1053
- const item = globals.get(id);
1054
- if (!item || item.storage === "constant" || runtimes.get(item.type) === "mailbox") {
1055
- continue;
1056
- }
1057
- const ownsWorker = worker === item.name && item.span.file === fn.span.file;
1058
- if (program.background && (!ownsWorker || host && item.id === host.id)) {
1059
- report(`Background task ${program.name} accesses scan-owned storage ${item.name}; pass value snapshots through the mailbox.`, item.span);
1060
- }
1061
- const owner = owners.get(id);
1062
- if (owner && owner !== task) {
1063
- report(`Storage ${item.name} is shared across cyclic tasks ${owner} and ${task}.`, item.span);
1064
- }
1065
- owners.set(id, task);
1174
+ add64() {
1175
+ return this.helper("add64", "LWORD", [
1176
+ ["a", "LWORD"],
1177
+ ["b", "LWORD"]
1178
+ ], (name) => `x := a;
1179
+ y := b;
1180
+ FOR i := 1 TO 64 DO
1181
+ carry := SHL(x AND y, 1);
1182
+ x := x XOR y;
1183
+ y := carry;
1184
+ END_FOR;
1185
+ ${name} := x;
1186
+ `, ` x, y, carry : LWORD;
1187
+ i : UINT;`);
1188
+ }
1189
+ wrap64(operator) {
1190
+ const add = this.add64();
1191
+ if (operator === "add") {
1192
+ return add;
1066
1193
  }
1067
- };
1068
- }
1069
- var buildModuleTables = (core) => ({
1070
- functions: new Map(core.functions.map((item) => [item.id, item])),
1071
- blocks: new Map(core.blocks.map((item) => [item.id, item])),
1072
- types: new Map(core.types.map((item) => [item.id, item])),
1073
- variables: variablesById(core)
1074
- });
1075
- var builtTables = new WeakMap;
1076
- var moduleTables = (core) => {
1077
- const known = builtTables.get(core);
1078
- if (known) {
1079
- return known;
1194
+ if (operator === "subtract") {
1195
+ return this.helper("subtract64", "LWORD", [
1196
+ ["a", "LWORD"],
1197
+ ["b", "LWORD"]
1198
+ ], (name) => `${name} := ${add}(a, ${add}(NOT b, LWORD#1));
1199
+ `);
1200
+ }
1201
+ if (operator !== "multiply") {
1202
+ throw new Error("Unsupported verified wrapping operation");
1203
+ }
1204
+ return this.helper("multiply64", "LWORD", [
1205
+ ["a", "LWORD"],
1206
+ ["b", "LWORD"]
1207
+ ], (name) => `x := a;
1208
+ y := b;
1209
+ result := LWORD#0;
1210
+ FOR i := 1 TO 64 DO
1211
+ IF (y AND LWORD#1) <> LWORD#0 THEN
1212
+ result := ${add}(result, x);
1213
+ END_IF;
1214
+ x := SHL(x, 1);
1215
+ y := SHR(y, 1);
1216
+ END_FOR;
1217
+ ${name} := result;
1218
+ `, ` x, y, result : LWORD;
1219
+ i : UINT;`);
1080
1220
  }
1081
- const tables = buildModuleTables(core);
1082
- builtTables.set(core, tables);
1083
- return tables;
1084
- };
1085
- function accessedStorage(fn, core, scheduledHost) {
1086
- const scheduledCall = fn.body.find((item) => item.kind === "invoke" && item.instance === scheduledHost);
1087
- const result = new Set;
1088
- const seen = new Set;
1089
- const { functions, blocks, types, variables } = moduleTables(core);
1090
- const expression = (value) => {
1091
- if (value.kind === "load") {
1092
- result.add(value.root);
1221
+ arithmetic(typeId, operator, policy) {
1222
+ const type = this.types.get(typeId);
1223
+ if (type?.kind !== "integer") {
1224
+ throw new Error("Expected verified integer arithmetic");
1093
1225
  }
1094
- if (value.kind === "borrow") {
1095
- result.add(value.place.root);
1226
+ const token = operatorTokens[operator];
1227
+ if (!token) {
1228
+ throw new Error("Expected verified integer arithmetic");
1096
1229
  }
1097
- subexpressions2(value).forEach(expression);
1098
- };
1099
- const body = (items) => {
1100
- for (const item of items) {
1101
- if (item.kind === "assign") {
1102
- result.add(item.root);
1103
- }
1104
- if (item.kind === "invoke" && item.instance && item !== scheduledCall) {
1105
- result.add(item.instance);
1106
- }
1107
- if (item.kind === "blockUpdate") {
1108
- result.add(item.instance);
1109
- }
1110
- statementExpressions2(item).forEach(expression);
1111
- if (item.kind === "for") {
1112
- result.add(item.counter);
1230
+ const key = `${policy}_${operator}_${typeId}`;
1231
+ if (policy === "wrap") {
1232
+ if (type.bits === 64) {
1233
+ const operation = this.wrap64(operator);
1234
+ return this.helper(key, typeId, [
1235
+ ["a", typeId],
1236
+ ["b", typeId]
1237
+ ], (name) => `${name} := LWORD_TO_${typeId}(${operation}(${typeId}_TO_LWORD(a), ${typeId}_TO_LWORD(b)));
1238
+ `);
1113
1239
  }
1114
- if (item.kind === "invoke") {
1115
- if (item.destination) {
1116
- result.add(item.destination);
1117
- }
1118
- const called = functions.get(item.function);
1119
- if (called && !seen.has(called.id)) {
1120
- seen.add(called.id);
1121
- body(called.body);
1240
+ const wide = !type.signed && operator !== "subtract" ? "ULINT" : "LINT";
1241
+ return this.helper(key, typeId, [
1242
+ ["a", typeId],
1243
+ ["b", typeId]
1244
+ ], (name) => `${name} := ${wide}_TO_${typeId}(${typeId}_TO_${wide}(a) ${token} ${typeId}_TO_${wide}(b));
1245
+ `);
1246
+ }
1247
+ const [minimum, maximum] = integerRange(type);
1248
+ const min = `${typeId}#${minimum}`;
1249
+ const max = `${typeId}#${maximum}`;
1250
+ const zero = `${typeId}#0`;
1251
+ return this.helper(key, typeId, [
1252
+ ["a", typeId],
1253
+ ["b", typeId]
1254
+ ], (name) => {
1255
+ const clamp = (condition, endpoint, depth = "") => `${depth}IF ${condition} THEN
1256
+ ${depth} ${name} := ${endpoint};
1257
+ ${depth} RETURN;
1258
+ ${depth}END_IF;
1259
+ `;
1260
+ const guard = () => {
1261
+ if (!type.signed) {
1262
+ if (operator === "add") {
1263
+ return clamp(`a > ${max} - b`, max);
1264
+ }
1265
+ if (operator === "subtract") {
1266
+ return clamp("a < b", zero);
1267
+ }
1268
+ return `IF b <> ${zero} THEN
1269
+ ${clamp(`a > ${max} / b`, max, " ")}END_IF;
1270
+ `;
1122
1271
  }
1123
- }
1124
- if (item.kind === "blockUpdate") {
1125
- const variable = variables.get(item.instance);
1126
- if (!variable) {
1127
- throw new Error("Missing verified instance during task planning.");
1272
+ if (operator === "add") {
1273
+ return `IF b > ${zero} THEN
1274
+ ${clamp(`a > ${max} - b`, max, " ")}ELSIF b < ${zero} THEN
1275
+ ${clamp(`a < ${min} - b`, min, " ")}END_IF;
1276
+ `;
1128
1277
  }
1129
- const type = instancedBlock3(variable.type, types);
1130
- const block = type && blocks.get(type.block);
1131
- if (block && !seen.has(block.id)) {
1132
- seen.add(block.id);
1133
- body(block.body);
1278
+ if (operator === "subtract") {
1279
+ return `IF b < ${zero} THEN
1280
+ ${clamp(`a > ${max} + b`, max, " ")}ELSIF b > ${zero} THEN
1281
+ ${clamp(`a < ${min} + b`, min, " ")}END_IF;
1282
+ `;
1134
1283
  }
1135
- }
1136
- nestedBodies2(item).forEach(body);
1284
+ return clamp(`a = ${zero}`, zero) + clamp(`b = ${zero}`, zero) + `IF a > ${zero} THEN
1285
+ IF b > ${zero} THEN
1286
+ ${clamp(`a > ${max} / b`, max, " ")} ELSE
1287
+ ${clamp(`b < ${min} / a`, min, " ")} END_IF;
1288
+ ELSE
1289
+ IF b > ${zero} THEN
1290
+ ${clamp(`a < ${min} / b`, min, " ")} ELSE
1291
+ ${clamp(`a < ${max} / b`, max, " ")} END_IF;
1292
+ END_IF;
1293
+ `;
1294
+ };
1295
+ return `${guard()}${name} := a ${token} b;
1296
+ `;
1297
+ });
1298
+ }
1299
+ truncation(typeId) {
1300
+ const type = this.types.get(typeId);
1301
+ if (type?.kind !== "float") {
1302
+ throw new Error("Expected verified float truncation");
1137
1303
  }
1138
- };
1139
- seen.add(fn.id);
1140
- body(fn.body);
1141
- return result;
1142
- }
1143
- function appendContinuations(core, tasks, report) {
1144
- const continuations = core.programs.flatMap((program) => program.continuation ? [{ name: program.name, scope: program.continuation }] : []);
1145
- if (!continuations.length) {
1146
- return tasks;
1304
+ const whole = scalarLiteral({ kind: "float", value: 2 ** (type.bits === 32 ? 23 : 52) }, typeId);
1305
+ return this.helper(`truncate_${typeId}`, typeId, [["value", typeId]], (name) => `IF ABS(value) >= ${whole} THEN
1306
+ ${name} := value;
1307
+ RETURN;
1308
+ END_IF;
1309
+ nearest := TO_LINT(value);
1310
+ IF value >= 0 AND TO_${typeId}(nearest) > value THEN
1311
+ nearest := nearest - 1;
1312
+ ELSIF value < 0 AND TO_${typeId}(nearest) < value THEN
1313
+ nearest := nearest + 1;
1314
+ END_IF;
1315
+ ${name} := TO_${typeId}(nearest);
1316
+ `, " nearest : LINT;");
1147
1317
  }
1148
- const programs = new Map(core.programs.map((program) => [program.name, program]));
1149
- const functions = new Map(core.functions.map((routine) => [routine.id, routine]));
1150
- const placements = tasks.map((task) => {
1151
- const roots = new Set;
1152
- for (const name of task.programs) {
1153
- const program = programs.get(name);
1154
- if (!program || program.background) {
1155
- continue;
1156
- }
1157
- const entry = functions.get(program.entry);
1158
- if (entry) {
1159
- for (const id of accessedStorage(entry, core)) {
1160
- roots.add(id);
1161
- }
1318
+ saturation(sourceId, targetId) {
1319
+ const source = this.types.get(sourceId);
1320
+ const target = this.types.get(targetId);
1321
+ if (source?.kind === "float" && target?.kind === "float") {
1322
+ if (source.bits <= target.bits) {
1323
+ return `TO_${targetId}`;
1162
1324
  }
1325
+ const maximum = floatMaximum(target);
1326
+ const literal = (value, type) => scalarLiteral({ kind: "float", value }, type);
1327
+ return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => `IF value < ${literal(-maximum, sourceId)} THEN
1328
+ ${name} := ${literal(-maximum, targetId)};
1329
+ RETURN;
1330
+ END_IF;
1331
+ IF value > ${literal(maximum, sourceId)} THEN
1332
+ ${name} := ${literal(maximum, targetId)};
1333
+ RETURN;
1334
+ END_IF;
1335
+ ${name} := TO_${targetId}(value);
1336
+ `);
1163
1337
  }
1164
- return { task, roots, additions: [] };
1165
- });
1166
- for (const { name, scope } of continuations) {
1167
- const root = core.variables.find((variable) => variable.name === scope.instance && variable.span.file === scope.file);
1168
- if (!root) {
1169
- report(`Missing continuation owner ${scope.instance}.`);
1170
- continue;
1171
- }
1172
- const owners = placements.filter(({ roots }) => roots.has(root.id));
1173
- const [owner] = owners;
1174
- if (!owner || owners.length !== 1) {
1175
- report(`Continuation owner ${scope.instance} must belong to exactly one caller task.`, root.span);
1176
- continue;
1338
+ if (!source || !target || !integerType(source) || !integerType(target)) {
1339
+ throw new Error("Expected verified integer saturation");
1177
1340
  }
1178
- owner.additions.push(name);
1341
+ const [fromMin, fromMax] = integerRange(source);
1342
+ const [toMin, toMax] = integerRange(target);
1343
+ return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => {
1344
+ let body = "";
1345
+ if (fromMin < toMin) {
1346
+ body += `IF value < ${sourceId}#${toMin} THEN
1347
+ ${name} := ${targetId}#${toMin};
1348
+ RETURN;
1349
+ END_IF;
1350
+ `;
1351
+ }
1352
+ if (fromMax > toMax) {
1353
+ body += `IF value > ${sourceId}#${toMax} THEN
1354
+ ${name} := ${targetId}#${toMax};
1355
+ RETURN;
1356
+ END_IF;
1357
+ `;
1358
+ }
1359
+ return `${body}${name} := TO_${targetId}(value);
1360
+ `;
1361
+ });
1179
1362
  }
1180
- return placements.map(({ task, additions }) => ({
1181
- ...task,
1182
- programs: task.programs.concat(additions)
1183
- }));
1184
1363
  }
1185
1364
 
1186
- // packages/compiler/src/codesys/symbols.ts
1187
- function required2(value) {
1365
+ // packages/compiler/src/codesys/types.ts
1366
+ var sourceTypeName = (id) => id.slice(id.lastIndexOf(":") + 1);
1367
+ var stringTypeName = (type) => type.encoding === "utf8" ? "STRING" : "WSTRING";
1368
+ var stEscapes = new Map([
1369
+ ["$", "$$"],
1370
+ ["'", "$'"],
1371
+ ["\r", "$R"],
1372
+ [`
1373
+ `, "$N"]
1374
+ ]);
1375
+ var stStringLiteral = (text) => `'${[...text].map((character) => stEscapes.get(character) ?? character).join("")}'`;
1376
+ var anonymousRecordId = /:\d+:record(<.*>)?$/;
1377
+ var required = (value) => {
1188
1378
  if (value === undefined) {
1189
- throw new Error("Missing verified CODESYS symbol.");
1379
+ throw new Error("Missing verified type name");
1190
1380
  }
1191
1381
  return value;
1192
- }
1193
- function createSymbols({ core, options }) {
1194
- const persistent = new Set(core.variables.filter((item) => item.storage !== "constant").map((item) => item.id));
1195
- const programRoutines = new Set;
1196
- for (const fn of core.functions) {
1197
- if (!fn.owner && [...accessedStorage(fn, core)].some((id) => persistent.has(id))) {
1198
- programRoutines.add(fn.id);
1382
+ };
1383
+
1384
+ class CodesysTypes {
1385
+ types;
1386
+ objects = [];
1387
+ names = new Map;
1388
+ fields = new Map;
1389
+ aliases = new Set;
1390
+ shapes = new Map;
1391
+ constructor(types, names, blockNames) {
1392
+ this.types = types;
1393
+ const anonymous = new Map;
1394
+ for (const type of types.values()) {
1395
+ const shape = this.anonymousShape(type);
1396
+ const shared = shape === null ? undefined : anonymous.get(shape);
1397
+ if (shared !== undefined) {
1398
+ this.names.set(type.id, required(this.names.get(shared)));
1399
+ this.fields.set(type.id, required(this.fields.get(shared)));
1400
+ this.aliases.add(type.id);
1401
+ continue;
1402
+ }
1403
+ if (shape !== null) {
1404
+ anonymous.set(shape, type.id);
1405
+ }
1406
+ if (type.kind === "block") {
1407
+ const name = blockNames.get(type.block);
1408
+ if (!name) {
1409
+ throw new Error("Missing verified block name");
1410
+ }
1411
+ this.names.set(type.id, name);
1412
+ }
1413
+ if (["record", "array", "enum", "string"].includes(type.kind)) {
1414
+ const label = sourceTypeName(type.id);
1415
+ if (type.kind === "record" || type.kind === "enum") {
1416
+ const prefix = type.kind === "record" ? "ST" : "E";
1417
+ this.names.set(type.id, names.allocateObject(prefix, label));
1418
+ } else {
1419
+ this.names.set(type.id, names.allocate(`T_${label}`));
1420
+ }
1421
+ }
1422
+ if (type.kind === "record" || type.kind === "enum") {
1423
+ const names = new Names;
1424
+ const fields = new Map;
1425
+ for (const member of type.kind === "record" ? type.fields : type.members) {
1426
+ fields.set(member.name, names.allocate(member.name));
1427
+ }
1428
+ this.fields.set(type.id, fields);
1429
+ }
1430
+ }
1431
+ for (const type of types.values()) {
1432
+ if (type.kind === "array" && instancedBlock4(type.id, types)) {
1433
+ this.names.set(type.id, `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`);
1434
+ }
1435
+ }
1436
+ const emitted = new Set;
1437
+ const emit = (type) => {
1438
+ if (instancedBlock4(type.id, types) || !this.names.has(type.id) || this.aliases.has(type.id) || emitted.has(type.id)) {
1439
+ return;
1440
+ }
1441
+ if (type.kind === "array") {
1442
+ emit(this.type(type.element));
1443
+ }
1444
+ if (type.kind === "record") {
1445
+ for (const field of type.fields) {
1446
+ emit(this.type(field.type));
1447
+ }
1448
+ }
1449
+ emitted.add(type.id);
1450
+ const name = this.name(type.id);
1451
+ const declaration = this.dutDeclaration(type, name);
1452
+ this.objects.push({ id: type.id, kind: "dataType", name, declaration });
1453
+ };
1454
+ for (const type of types.values()) {
1455
+ emit(type);
1199
1456
  }
1200
1457
  }
1201
- const globalNames = planGlobalNames(core, options.programNames);
1202
- return {
1203
- ...globalNames,
1204
- blocks: new Map(core.blocks.map((block) => [block.id, block])),
1205
- numeric: new NumericLowering(globalNames.typeMap, (label) => globalNames.names.allocate(label)),
1206
- programRoutines,
1207
- references: new Map,
1208
- functionNames: new Map,
1209
- programResults: new Map,
1210
- mailboxLocks: new Map,
1211
- blockFields: new Map,
1212
- routineScopes: new Map
1213
- };
1214
- }
1215
- function allocateFunctionNames(symbols, { core }) {
1216
- const entries = new Set(core.programs.map((program) => program.entry));
1217
- for (const fn of core.functions.filter((fn) => !fn.owner)) {
1218
- const program = symbols.programRoutines.has(fn.id);
1219
- const label = program && entries.has(fn.id) ? `${fn.name}_body` : fn.name;
1220
- symbols.functionNames.set(fn.id, symbols.names.allocateObject(program ? "PRG" : "F", label));
1221
- }
1222
- }
1223
- var instrumentationFieldTypes = {
1224
- busy: "BOOL",
1225
- step: "UINT",
1226
- startedAt: "UDINT",
1227
- job: "UDINT",
1228
- sequence: "UDINT"
1229
- };
1230
- function allocateBlockFields(symbols, instrumentation, plan, objects) {
1231
- const { core } = plan;
1232
- const { functionNames, blockNames, blockFields } = symbols;
1233
- for (const block of core.blocks) {
1234
- const fields = new Names;
1235
- const mapped = new Map;
1236
- for (const object of objects) {
1237
- fields.reserve(object.name);
1458
+ anonymousShape(type) {
1459
+ if (type.kind !== "record" || !anonymousRecordId.test(type.id)) {
1460
+ return null;
1238
1461
  }
1239
- fields.reserve(instrumentation.global);
1240
- for (const objectName of [
1241
- ...core.functions.filter((fn) => !fn.owner).map((fn) => required2(functionNames.get(fn.id))),
1242
- ...blockNames.values()
1243
- ]) {
1244
- fields.reserve(objectName);
1462
+ const known = this.shapes.get(type.id);
1463
+ if (known !== undefined) {
1464
+ return known;
1245
1465
  }
1246
- for (const method of core.functions.filter((fn) => fn.owner?.block === block.id)) {
1247
- functionNames.set(method.id, fields.allocate(method.name));
1466
+ const shape = JSON.stringify(type.fields.map((field) => [
1467
+ field.name,
1468
+ this.anonymousShape(this.type(field.type)) ?? field.type
1469
+ ]));
1470
+ this.shapes.set(type.id, shape);
1471
+ return shape;
1472
+ }
1473
+ dutDeclaration(type, name) {
1474
+ if (type.kind === "record") {
1475
+ const fields = type.fields.map((field) => ` ${this.field(type.id, field.name)} : ${this.name(field.type)};`).join(`
1476
+ `);
1477
+ return `TYPE ${name} :
1478
+ STRUCT
1479
+ ${fields}
1480
+ END_STRUCT
1481
+ END_TYPE
1482
+ `;
1248
1483
  }
1249
- const native = block.standard && standardBlocks2[block.standard];
1250
- for (const item of [...block.inputs, ...block.outputs, ...block.state]) {
1251
- mapped.set(item.id, native ? required2([...native.inputs, ...native.outputs].find(([name]) => name === item.name))[1] : fields.allocate(item.name));
1484
+ if (type.kind === "array") {
1485
+ return `${type.index ? `{attribute 'tsplc_keyed'}
1486
+ ` : ""}TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
1487
+ END_TYPE
1488
+ `;
1252
1489
  }
1253
- if (block.runtime?.kind === "mailbox") {
1254
- symbols.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
1490
+ if (type.kind === "string") {
1491
+ return `TYPE ${name} : ${stringTypeName(type)}(${type.capacity});
1492
+ END_TYPE
1493
+ `;
1255
1494
  }
1256
- blockFields.set(block.id, mapped);
1257
- const settings = plan.project.debug;
1258
- const stepped = instrumentation.analysis.jobSites.has(block.id) || plan.telemetry?.failures.has(block.id);
1259
- const tracked = Boolean(block.job && (settings?.jobs || stepped));
1260
- const carries = settings?.jobs && instrumentation.analysis.carriers.has(block.id);
1261
- if (tracked || carries) {
1262
- instrumentation.fields.set(block.id, {
1263
- ...tracked && {
1264
- busy: fields.allocate("tsplcBusy"),
1265
- track: fields.allocate("TsplcTrack")
1266
- },
1267
- ...tracked && settings?.jobs && { startedAt: fields.allocate("startedAt") },
1268
- ...stepped && { step: fields.allocate("tsplcStep") },
1269
- ...carries && { job: fields.allocate("requestJob") },
1270
- ...carries && block.runtime?.kind === "http" && {
1271
- sequence: fields.allocate("sequence")
1272
- }
1273
- });
1495
+ if (type.kind === "enum") {
1496
+ const members = type.members.map((member) => ` ${this.field(type.id, member.name)} := ${member.value}`).join(`,
1497
+ `);
1498
+ return `{attribute 'qualified_only'}
1499
+ {attribute 'strict'}
1500
+ TYPE ${name} : (
1501
+ ${members}
1502
+ ) DINT;
1503
+ END_TYPE
1504
+ `;
1274
1505
  }
1506
+ throw new Error("Unsupported verified data type");
1275
1507
  }
1276
- }
1277
- function allocateRoutineScope(symbols, instrumentation, objects, fn) {
1278
- const block = "inputs" in fn ? fn : undefined;
1279
- const owner = block ?? ("owner" in fn && fn.owner ? symbols.blocks.get(fn.owner.block) : undefined);
1280
- const names = new Names;
1281
- const references = new Map;
1282
- for (const object of objects) {
1283
- names.reserve(object.name);
1508
+ type(id) {
1509
+ const type = this.types.get(id);
1510
+ if (!type) {
1511
+ throw new Error("Missing verified type");
1512
+ }
1513
+ return type;
1284
1514
  }
1285
- names.reserve(instrumentation.global);
1286
- for (const name of [
1287
- ...symbols.functionNames.values(),
1288
- ...symbols.blockNames.values()
1289
- ]) {
1290
- names.reserve(name);
1515
+ name(id) {
1516
+ return this.names.get(id) ?? id;
1291
1517
  }
1292
- if (symbols.programRoutines.has(fn.id) && "parameters" in fn && fn.result) {
1518
+ field(id, name) {
1519
+ const field = this.fields.get(id)?.get(name);
1520
+ if (!field) {
1521
+ throw new Error("Missing verified field");
1522
+ }
1523
+ return field;
1524
+ }
1525
+ declarationInitializer(value, id) {
1526
+ const type = this.type(id);
1527
+ if ((type.kind === "record" || type.kind === "array") && this.isZero(value)) {
1528
+ return "";
1529
+ }
1530
+ return ` := ${this.initializer(value, id)}`;
1531
+ }
1532
+ initializer(value, id) {
1533
+ const type = this.type(id);
1534
+ if (type.kind === "array" && value.kind === "array") {
1535
+ return `[${value.items.map((item) => this.initializer(item, type.element)).join(", ")}]`;
1536
+ }
1537
+ if (type.kind !== "record" || value.kind !== "record") {
1538
+ return this.literal(value, id);
1539
+ }
1540
+ const fields = type.fields.flatMap((field) => {
1541
+ const initial = value.fields[field.name];
1542
+ if (!initial) {
1543
+ throw new Error("Missing verified record initializer");
1544
+ }
1545
+ return this.type(field.type).kind !== "enum" && this.isZero(initial) ? [] : [
1546
+ `${this.field(id, field.name)} := ${this.initializer(initial, field.type)}`
1547
+ ];
1548
+ });
1549
+ return fields.length ? `(${fields.join(", ")})` : this.literal(value, id);
1550
+ }
1551
+ isZero(value) {
1552
+ if (value.kind === "bool") {
1553
+ return !value.value;
1554
+ }
1555
+ if (value.kind === "integer") {
1556
+ return value.value === "0";
1557
+ }
1558
+ if (value.kind === "float") {
1559
+ return Object.is(value.value, 0);
1560
+ }
1561
+ if (value.kind === "string") {
1562
+ return value.value === "";
1563
+ }
1564
+ if (value.kind === "array") {
1565
+ return value.items.every((item) => this.isZero(item));
1566
+ }
1567
+ if (value.kind === "record") {
1568
+ return Object.values(value.fields).every((item) => this.isZero(item));
1569
+ }
1570
+ return false;
1571
+ }
1572
+ literal(value, id) {
1573
+ const type = this.type(id);
1574
+ if (type.kind === "enum" && value.kind === "integer") {
1575
+ const member = type.members.find((member) => member.value === value.value);
1576
+ if (!member) {
1577
+ throw new Error("Missing verified enum member");
1578
+ }
1579
+ return `${this.name(id)}.${this.field(id, member.name)}`;
1580
+ }
1581
+ if (type.kind === "string" && value.kind === "string") {
1582
+ const delimiter = type.encoding === "utf16" ? '"' : "'";
1583
+ return `${delimiter}${escapeString(value.value, delimiter)}${delimiter}`;
1584
+ }
1585
+ if (type.kind === "array" && value.kind === "array") {
1586
+ return `[${value.items.map((item) => this.literal(item, type.element)).join(", ")}]`;
1587
+ }
1588
+ if (type.kind === "record" && value.kind === "record") {
1589
+ const fields = type.fields.map((field) => {
1590
+ const initial = value.fields[field.name];
1591
+ if (!initial) {
1592
+ throw new Error("Missing verified record initializer");
1593
+ }
1594
+ return `${this.field(id, field.name)} := ${this.literal(initial, field.type)}`;
1595
+ });
1596
+ return `(${fields.join(", ")})`;
1597
+ }
1598
+ if (type.kind === "duration" && value.kind === "duration") {
1599
+ return `T#${BigInt(value.nanoseconds) / nanosecondsPerMillisecond2}ms`;
1600
+ }
1601
+ if (type.kind === "calendar" && value.kind === "calendar") {
1602
+ if (type.domain === "date") {
1603
+ return `D#${value.value}`;
1604
+ }
1605
+ if (type.domain === "timeOfDay") {
1606
+ return `TOD#${value.value}`;
1607
+ }
1608
+ return `DT#${value.value.replace("T", "-")}`;
1609
+ }
1610
+ return scalarLiteral(value, id);
1611
+ }
1612
+ }
1613
+
1614
+ // packages/compiler/src/codesys/global-names.ts
1615
+ var planGlobalNames = (core, programNames = {}) => {
1616
+ const names = new Names;
1617
+ for (const name of Object.values(programNames)) {
1618
+ names.reserve(name);
1619
+ }
1620
+ const typeMap = new Map(core.types.map((type) => [type.id, type]));
1621
+ const blockNames = new Map(core.blocks.map((block) => [
1622
+ block.id,
1623
+ block.standard ? standardBlocks[block.standard].native : names.allocateObject("FB", block.name)
1624
+ ]));
1625
+ for (const name of blockNames.values()) {
1626
+ names.reserve(name);
1627
+ }
1628
+ const targetTypes = new CodesysTypes(typeMap, names, blockNames);
1629
+ const { globalLists, retainedVariables } = storageLayout(core);
1630
+ const hasExports = (group) => group.variables.some((variable) => variable.exported && !variable.exposure);
1631
+ const globals = globalLists.map((group) => {
1632
+ const splitByStorage = globalLists.some((other) => other.module === group.module && other.kind !== group.kind && hasExports(other));
1633
+ const name = hasExports(group) ? names.allocate(pascalCase(splitByStorage ? `${group.module}-${group.kind}` : group.module)) : names.allocateObject("GVL", `${group.module}_${group.kind}`);
1634
+ const fields = new Names;
1635
+ for (const name of blockNames.values()) {
1636
+ fields.reserve(name);
1637
+ }
1638
+ return {
1639
+ ...group,
1640
+ name,
1641
+ fields: new Map(group.variables.map((item) => [item.id, fields.allocate(item.name)]))
1642
+ };
1643
+ });
1644
+ return {
1645
+ names,
1646
+ typeMap,
1647
+ blockNames,
1648
+ targetTypes,
1649
+ globals,
1650
+ retainedVariables
1651
+ };
1652
+ };
1653
+
1654
+ // packages/compiler/src/codesys/symbols.ts
1655
+ function required2(value) {
1656
+ if (value === undefined) {
1657
+ throw new Error("Missing verified CODESYS symbol.");
1658
+ }
1659
+ return value;
1660
+ }
1661
+ function createSymbols({ core, options }) {
1662
+ const persistent = new Set(core.variables.filter((item) => item.storage !== "constant").map((item) => item.id));
1663
+ const programRoutines = new Set;
1664
+ for (const fn of core.functions) {
1665
+ if (!fn.owner && [...accessedStorage(fn, core)].some((id) => persistent.has(id))) {
1666
+ programRoutines.add(fn.id);
1667
+ }
1668
+ }
1669
+ const globalNames = planGlobalNames(core, options.programNames);
1670
+ return {
1671
+ ...globalNames,
1672
+ blocks: new Map(core.blocks.map((block) => [block.id, block])),
1673
+ numeric: new NumericLowering(globalNames.typeMap, (label) => globalNames.names.allocate(label)),
1674
+ programRoutines,
1675
+ references: new Map,
1676
+ functionNames: new Map,
1677
+ programResults: new Map,
1678
+ mailboxLocks: new Map,
1679
+ blockFields: new Map,
1680
+ routineScopes: new Map
1681
+ };
1682
+ }
1683
+ function allocateFunctionNames(symbols, { core }) {
1684
+ const entries = new Set(core.programs.map((program) => program.entry));
1685
+ for (const fn of core.functions.filter((fn) => !fn.owner)) {
1686
+ const program = symbols.programRoutines.has(fn.id);
1687
+ const label = program && entries.has(fn.id) ? `${fn.name}_body` : fn.name;
1688
+ symbols.functionNames.set(fn.id, symbols.names.allocateObject(program ? "PRG" : "F", label));
1689
+ }
1690
+ }
1691
+ var instrumentationFieldTypes = {
1692
+ busy: "BOOL",
1693
+ step: "UINT",
1694
+ startedAt: "UDINT",
1695
+ job: "UDINT",
1696
+ sequence: "UDINT"
1697
+ };
1698
+ function allocateBlockFields(symbols, instrumentation, plan, objects) {
1699
+ const { core } = plan;
1700
+ const { functionNames, blockNames, blockFields } = symbols;
1701
+ for (const block of core.blocks) {
1702
+ const fields = new Names;
1703
+ const mapped = new Map;
1704
+ for (const object of objects) {
1705
+ fields.reserve(object.name);
1706
+ }
1707
+ fields.reserve(instrumentation.global);
1708
+ for (const objectName of [
1709
+ ...core.functions.filter((fn) => !fn.owner).map((fn) => required2(functionNames.get(fn.id))),
1710
+ ...blockNames.values()
1711
+ ]) {
1712
+ fields.reserve(objectName);
1713
+ }
1714
+ for (const method of core.functions.filter((fn) => fn.owner?.block === block.id)) {
1715
+ functionNames.set(method.id, fields.allocate(method.name));
1716
+ }
1717
+ const native = block.standard && standardBlocks2[block.standard];
1718
+ for (const item of [...block.inputs, ...block.outputs, ...block.state]) {
1719
+ mapped.set(item.id, native ? required2([...native.inputs, ...native.outputs].find(([name]) => name === item.name))[1] : fields.allocate(item.name));
1720
+ }
1721
+ if (block.runtime?.kind === "mailbox") {
1722
+ symbols.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
1723
+ }
1724
+ blockFields.set(block.id, mapped);
1725
+ const settings = plan.project.debug;
1726
+ const stepped = instrumentation.analysis.jobSites.has(block.id) || plan.telemetry?.failures.has(block.id);
1727
+ const tracked = Boolean(block.job && (settings?.jobs || stepped));
1728
+ const carries = settings?.jobs && instrumentation.analysis.carriers.has(block.id);
1729
+ if (tracked || carries) {
1730
+ instrumentation.fields.set(block.id, {
1731
+ ...tracked && {
1732
+ busy: fields.allocate("tsplcBusy"),
1733
+ track: fields.allocate("TsplcTrack")
1734
+ },
1735
+ ...tracked && settings?.jobs && { startedAt: fields.allocate("startedAt") },
1736
+ ...stepped && { step: fields.allocate("tsplcStep") },
1737
+ ...carries && { job: fields.allocate("requestJob") },
1738
+ ...carries && block.runtime?.kind === "http" && {
1739
+ sequence: fields.allocate("sequence")
1740
+ }
1741
+ });
1742
+ }
1743
+ }
1744
+ }
1745
+ function allocateRoutineScope(symbols, instrumentation, objects, fn) {
1746
+ const block = "inputs" in fn ? fn : undefined;
1747
+ const owner = block ?? ("owner" in fn && fn.owner ? symbols.blocks.get(fn.owner.block) : undefined);
1748
+ const names = new Names;
1749
+ const references = new Map;
1750
+ for (const object of objects) {
1751
+ names.reserve(object.name);
1752
+ }
1753
+ names.reserve(instrumentation.global);
1754
+ for (const name of [
1755
+ ...symbols.functionNames.values(),
1756
+ ...symbols.blockNames.values()
1757
+ ]) {
1758
+ names.reserve(name);
1759
+ }
1760
+ if (symbols.programRoutines.has(fn.id) && "parameters" in fn && fn.result) {
1293
1761
  symbols.programResults.set(fn.id, names.allocate("plc_result"));
1294
1762
  }
1295
1763
  if (owner) {
@@ -1317,21 +1785,29 @@ var globalSections = {
1317
1785
  state: "VAR_GLOBAL"
1318
1786
  };
1319
1787
  var globalInitializer = ({ typeMap, targetTypes }, storage, item) => {
1320
- if (instancedBlock4(item.type, typeMap)) {
1788
+ if (instancedBlock5(item.type, typeMap)) {
1321
1789
  return "";
1322
1790
  }
1323
1791
  const value = item.initial ?? defaultValue(item.type, typeMap);
1324
1792
  return storage === "constants" ? ` := ${targetTypes.literal(value, item.type)}` : targetTypes.declarationInitializer(value, item.type);
1325
1793
  };
1794
+ var publishedAccess = (plan) => {
1795
+ const published = new Set(plan.publication[plan.options.buildTarget]);
1796
+ return (variable) => {
1797
+ if (!published.has(variable.id)) {
1798
+ return;
1799
+ }
1800
+ return variable.exposure ? "read" : "readwrite";
1801
+ };
1802
+ };
1326
1803
  function emitGlobalLists(plan, symbols) {
1327
- const { options } = plan;
1328
1804
  const { globals, references, targetTypes } = symbols;
1329
1805
  const objects = [];
1330
1806
  const mappings = [];
1807
+ const access = publishedAccess(plan);
1331
1808
  for (const group of globals) {
1332
1809
  const { name, fields } = group;
1333
- const published = new Set(plan.publication[options.buildTarget]);
1334
- const publish = group.variables.some((variable) => published.has(variable.id));
1810
+ const publish = group.variables.some((variable) => access(variable));
1335
1811
  const lines = [
1336
1812
  ...publish ? ["{attribute 'linkalways'}"] : [],
1337
1813
  "{attribute 'qualified_only'}"
@@ -1341,8 +1817,9 @@ function emitGlobalLists(plan, symbols) {
1341
1817
  for (const item of section.variables) {
1342
1818
  const field = required2(fields.get(item.id));
1343
1819
  references.set(item.id, `${name}.${field}`);
1344
- if (published.has(item.id)) {
1345
- lines.push(` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`);
1820
+ const symbol = access(item);
1821
+ if (symbol) {
1822
+ lines.push(` {attribute 'symbol' := '${symbol}'}`);
1346
1823
  }
1347
1824
  mappings.push({
1348
1825
  path: `${name}.st`,
@@ -2102,6 +2579,7 @@ END_WHILE;
2102
2579
  IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberValue;END_IF;`)
2103
2580
  ].filter((item) => transport === "http" || !["AppendWire", "FindHeaders", "ReadHeaders"].includes(item.name));
2104
2581
  };
2582
+ var serviceBlock = (block) => block.runtime?.kind === "http" || block.runtime?.kind === "rpc";
2105
2583
  function emitServiceBlock({ plan, symbols, instrumentation }, networkName, fn) {
2106
2584
  const endpoint = required2(plan.http[fn.id]);
2107
2585
  const name = required2(symbols.blockNames.get(fn.id));
@@ -2144,525 +2622,18 @@ function httpNetwork(plan, symbols) {
2144
2622
  if (!Object.values(plan.http).some((endpoint) => endpoint.transport !== "opcua")) {
2145
2623
  return;
2146
2624
  }
2147
- return {
2148
- id: "runtime:httpNetwork",
2149
- kind: "globalList",
2150
- name: symbols.names.allocateObject("GVL", "TsplcNetwork"),
2151
- declaration: `{attribute 'qualified_only'}
2152
- {attribute 'global_init_slot' := '40000'}
2153
- VAR_GLOBAL
2154
- network:NBS.AsyncProperty := (usiTaskPrio:=15,udiTaskInterval:=1000,tnTaskName:='tsPLC HTTP');
2155
- END_VAR
2156
- `
2157
- };
2158
- }
2159
-
2160
- // packages/compiler/src/codesys/instrumentation.ts
2161
- import { createHash } from "node:crypto";
2162
- import { elementaryType as elementaryType2, integerRange as integerRange3 } from "@tsplc/iec";
2163
-
2164
- // packages/compiler/src/codesys/debug.ts
2165
- import { directWrites, instancedBlock as instancedBlock5, nestedBodies as nestedBodies3 } from "@tsplc/compiler/ir";
2166
- var temporary = (id) => id.includes(":temporary:");
2167
- var constantIndex = (value) => value.kind === "constant" && value.value.kind === "integer" ? Number(value.value.value) : undefined;
2168
- var wholeTarget = (item) => {
2169
- if (item.kind === "assign" && !item.path?.length) {
2170
- return item.root;
2171
- }
2172
- return item.kind === "invoke" ? item.destination : undefined;
2173
- };
2174
- function blockInstances(core) {
2175
- const types = new Map(core.types.map((type) => [type.id, type]));
2176
- const blocks = new Map(core.blocks.map((block) => [block.id, block]));
2177
- const instances = new Map(core.blocks.map((block) => [block.id, []]));
2178
- const visit = (variable, block, path) => {
2179
- const type = types.get(variable.type);
2180
- const declared = type?.kind === "array" ? Array.from({ length: type.length }, (_, offset) => [
2181
- ...path,
2182
- { variable, index: type.lowerBound + offset }
2183
- ]) : [[...path, { variable }]];
2184
- for (const instance of declared) {
2185
- instances.get(block).push(instance);
2186
- for (const child of blocks.get(block).state) {
2187
- const instanced = instancedBlock5(child.type, types);
2188
- if (instanced) {
2189
- visit(child, instanced.block, instance);
2190
- }
2191
- }
2192
- }
2193
- };
2194
- for (const variable of core.variables) {
2195
- const instanced = instancedBlock5(variable.type, types);
2196
- if (instanced) {
2197
- visit(variable, instanced.block, []);
2198
- }
2199
- }
2200
- return instances;
2201
- }
2202
- function storagePath(root, path = []) {
2203
- const logical = root.storage === "input" || root.storage === "output";
2204
- if (!logical && root.storage !== "module" && root.storage !== "instance") {
2205
- return;
2206
- }
2207
- let text = logical ? root.name : `${moduleName(root)}.${root.name}`;
2208
- for (const segment of path) {
2209
- if (segment.kind === "field") {
2210
- text += `.${segment.name}`;
2211
- continue;
2212
- }
2213
- const index = constantIndex(segment.value);
2214
- if (index === undefined) {
2215
- return;
2216
- }
2217
- text += `[${index}]`;
2218
- }
2219
- return text;
2220
- }
2221
-
2222
- class DebugAnalysis {
2223
- core;
2224
- outputs;
2225
- tasks;
2226
- instances;
2227
- probes = new Map;
2228
- events = [];
2229
- writers;
2230
- jobSites = new Map;
2231
- decisions = new Map;
2232
- callSites = new Map;
2233
- carriers = new Set;
2234
- variables;
2235
- types;
2236
- routines;
2237
- blocks;
2238
- routineWrites = new Map;
2239
- temporaries = new Map;
2240
- writerSites = 0;
2241
- constructor(core, deployment, settings, outputs) {
2242
- this.core = core;
2243
- this.outputs = outputs;
2244
- this.types = new Map(core.types.map((type) => [type.id, type]));
2245
- this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
2246
- this.routines = new Map([...core.functions, ...core.blocks].map((routine) => [
2247
- routine.id,
2248
- routine
2249
- ]));
2250
- this.variables = variablesById(core);
2251
- this.writers = outputs.map(() => []);
2252
- this.tasks = routineTasks(core, deployment);
2253
- this.instances = blockInstances(core);
2254
- this.findCarriers();
2255
- if (!settings) {
2256
- return;
2257
- }
2258
- const routines = [
2259
- ...core.functions,
2260
- ...core.blocks.filter((block) => !block.standard)
2261
- ];
2262
- for (const routine of routines) {
2263
- this.countCalls(routine.body, 1);
2264
- }
2265
- for (const routine of routines) {
2266
- this.walk(settings, routine, routine.body, [], []);
2267
- }
2268
- if (settings.trace) {
2269
- for (const block of core.blocks) {
2270
- const { job } = block;
2271
- const task = this.tasks.get(block.id);
2272
- if (!job || !task || this.instances.get(block.id)?.length !== 1) {
2273
- continue;
2274
- }
2275
- const site = (type, phase) => this.site({
2276
- kind: "job",
2277
- job: { block: block.id, phase },
2278
- path: job.name,
2279
- type,
2280
- span: job.span,
2281
- text: `${job.name}: ${phase}`,
2282
- task
2283
- });
2284
- this.jobSites.set(block.id, {
2285
- start: site("UINT", "started"),
2286
- completion: site("DINT", "finished")
2287
- });
2288
- }
2289
- }
2290
- }
2291
- owningPath(variable) {
2292
- const type = this.types.get(variable.type);
2293
- const block = type?.kind === "block" ? this.blocks.get(type.block) : undefined;
2294
- if (!block?.job) {
2295
- return;
2296
- }
2297
- const paths = this.instances.get(block.id).filter((path) => path.at(-1).variable.id === variable.id);
2298
- return paths.length === 1 ? paths[0] : undefined;
2299
- }
2300
- site(site) {
2301
- const id = this.events.length + 1;
2302
- this.events.push({ ...site, id, operands: site.operands ?? [] });
2303
- return id;
2304
- }
2305
- findCarriers() {
2306
- const carries = (id) => {
2307
- const block = this.blocks.get(id);
2308
- if (block.runtime?.kind === "http") {
2309
- return true;
2310
- }
2311
- return block.state.some((child) => {
2312
- const type = instancedBlock5(child.type, this.types);
2313
- return type !== undefined && carries(type.block);
2314
- });
2315
- };
2316
- for (const block of this.core.blocks) {
2317
- if (carries(block.id)) {
2318
- this.carriers.add(block.id);
2319
- }
2320
- }
2321
- }
2322
- placeType(root, path = []) {
2323
- let type = this.types.get(root.type);
2324
- for (const segment of path) {
2325
- if (segment.kind === "field" && type?.kind === "record") {
2326
- type = this.types.get(type.fields.find((field) => field.name === segment.name).type);
2327
- } else if (segment.kind === "index" && type?.kind === "array") {
2328
- type = this.types.get(type.element);
2329
- } else {
2330
- return;
2331
- }
2332
- }
2333
- return type;
2334
- }
2335
- countCalls(items, weight) {
2336
- for (const item of items) {
2337
- if (item.kind === "invoke") {
2338
- this.callSites.set(item.function, (this.callSites.get(item.function) ?? 0) + weight);
2339
- }
2340
- for (const body of nestedBodies3(item)) {
2341
- this.countCalls(body, item.kind === "for" ? 2 : weight);
2342
- }
2343
- }
2344
- }
2345
- writes(id) {
2346
- const cached = this.routineWrites.get(id);
2347
- if (cached) {
2348
- return cached;
2349
- }
2350
- const result = new Set;
2351
- this.routineWrites.set(id, result);
2352
- for (const root of this.statementWrites(this.routines.get(id)?.body ?? [])) {
2353
- result.add(root);
2354
- }
2355
- return result;
2356
- }
2357
- statementWrites(items) {
2358
- const result = new Set;
2359
- for (const item of items) {
2360
- for (const root of directWrites(item)) {
2361
- result.add(root);
2362
- }
2363
- if (item.kind === "invoke") {
2364
- for (const root of this.writes(item.function)) {
2365
- result.add(root);
2366
- }
2367
- }
2368
- if (item.kind === "blockUpdate") {
2369
- const block = instancedBlock5(this.variables.get(item.instance).type, this.types);
2370
- if (block) {
2371
- for (const root of this.writes(block.block)) {
2372
- result.add(root);
2373
- }
2374
- }
2375
- }
2376
- for (const body of nestedBodies3(item)) {
2377
- for (const root of this.statementWrites(body)) {
2378
- result.add(root);
2379
- }
2380
- }
2381
- }
2382
- return result;
2383
- }
2384
- walk(settings, routine, items, prefixes, guards) {
2385
- for (const [index, item] of items.entries()) {
2386
- const here = [...prefixes, items.slice(0, index)];
2387
- this.probe(settings, routine, item, here, guards);
2388
- const guard = (conditions) => [
2389
- ...guards,
2390
- { conditions, depth: here.length }
2391
- ];
2392
- if (item.kind === "if") {
2393
- this.walk(settings, routine, item.then, here, guard([item.condition]));
2394
- this.walk(settings, routine, item.else, here, guard([item.condition]));
2395
- }
2396
- if (item.kind === "switch") {
2397
- for (const body of nestedBodies3(item)) {
2398
- this.walk(settings, routine, body, here, guard([item.value]));
2399
- }
2400
- }
2401
- if (item.kind === "for") {
2402
- this.walk(settings, routine, item.body, here, guards);
2403
- }
2404
- }
2405
- }
2406
- probe(settings, routine, item, prefixes, guards) {
2407
- const task = this.tasks.get(routine.id);
2408
- const probes = [];
2409
- if (item.kind === "assign" && settings.writers) {
2410
- let site;
2411
- this.outputs.forEach((output, index) => {
2412
- const when = this.reaches(item.root, item.path ?? [], output);
2413
- if (!when) {
2414
- return;
2415
- }
2416
- site ??= ++this.writerSites;
2417
- this.writers[index].push({
2418
- id: site,
2419
- routine: routine.id,
2420
- span: item.span
2421
- });
2422
- probes.push({ kind: "writer", site, output: index, when });
2423
- });
2424
- }
2425
- if (settings.trace && task) {
2426
- if (item.kind === "assign") {
2427
- const root = this.variables.get(item.root);
2428
- const type = this.placeType(root, item.path);
2429
- const path = root.storage === "module" ? storagePath(root, item.path) : undefined;
2430
- if (type?.kind === "enum" && path) {
2431
- const operands = this.operands(routine, prefixes, guards, settings.trace);
2432
- const site = this.site({
2433
- kind: "state",
2434
- path,
2435
- routine: routine.id,
2436
- type: type.id,
2437
- span: item.span,
2438
- task,
2439
- operands
2440
- });
2441
- probes.push({ kind: "state", value: item.value, site, operands });
2442
- }
2443
- }
2444
- if (item.kind === "return" && item.value && "parameters" in routine && routine.result && this.callSites.get(routine.id) === 1) {
2445
- const type = this.types.get(routine.result);
2446
- if (type?.kind === "enum") {
2447
- const slot = this.decisions.get(routine.id) ?? this.decisions.size;
2448
- this.decisions.set(routine.id, slot);
2449
- const path = routine.origin?.instance ? `${routine.origin.instance}.${routine.origin.name.split(".").at(-1)}` : routine.origin?.name ?? routine.name;
2450
- const operands = this.operands(routine, prefixes, guards, settings.trace);
2451
- const site = this.site({
2452
- kind: "decision",
2453
- path,
2454
- routine: routine.id,
2455
- type: type.id,
2456
- span: item.span,
2457
- task,
2458
- operands
2459
- });
2460
- probes.push({
2461
- kind: "decision",
2462
- value: item.value,
2463
- site,
2464
- slot,
2465
- operands
2466
- });
2467
- }
2468
- }
2469
- }
2470
- if (probes.length) {
2471
- this.probes.set(item, probes);
2472
- }
2473
- }
2474
- reaches(root, path, output) {
2475
- if (root !== output.root.id) {
2476
- return;
2477
- }
2478
- const when = [];
2479
- for (const [index, written] of path.entries()) {
2480
- const bound = output.segments[index];
2481
- if (!bound) {
2482
- break;
2483
- }
2484
- if (written.kind === "field") {
2485
- if (bound.kind !== "field" || bound.name !== written.name) {
2486
- return;
2487
- }
2488
- continue;
2489
- }
2490
- if (bound.kind !== "index") {
2491
- return;
2492
- }
2493
- const value = constantIndex(written.value);
2494
- if (value === undefined) {
2495
- when.push({ index: written.value, value: bound.value });
2496
- } else if (value !== bound.value) {
2497
- return;
2498
- }
2499
- }
2500
- return when;
2501
- }
2502
- definitions(routine) {
2503
- const cached = this.temporaries.get(routine.id);
2504
- if (cached) {
2505
- return cached;
2506
- }
2507
- const definitions = new Map;
2508
- const define = (items) => {
2509
- for (const item of items) {
2510
- const target = wholeTarget(item);
2511
- if (target && temporary(target)) {
2512
- definitions.set(target, [...definitions.get(target) ?? [], item]);
2513
- }
2514
- for (const body of nestedBodies3(item)) {
2515
- define(body);
2516
- }
2517
- }
2518
- };
2519
- define(routine.body);
2520
- this.temporaries.set(routine.id, definitions);
2521
- return definitions;
2522
- }
2523
- operands(routine, prefixes, guards, trace) {
2524
- const definitions = this.definitions(routine);
2525
- const result = [];
2526
- const seen = new Set;
2527
- for (const guard of [...guards].reverse()) {
2528
- const executed = new Set(prefixes.slice(0, guard.depth).flat());
2529
- const between = this.statementWrites(prefixes.slice(guard.depth).flat());
2530
- const add = (span, capture, read) => {
2531
- const kind = this.types.get(capture.type)?.kind;
2532
- const key = `${span.file}:${span.start}:${span.end}`;
2533
- if (seen.has(key) || !["bool", "enum", "integer", "bits"].includes(kind ?? "")) {
2534
- return;
2535
- }
2536
- seen.add(key);
2537
- const path = read && storagePath(this.variables.get(read.root), read.path);
2538
- result.push({
2539
- capture,
2540
- span,
2541
- ...path && { path },
2542
- stable: !read || !between.has(read.root)
2543
- });
2544
- };
2545
- const direct = (value) => (value.path ?? []).every((segment) => segment.kind === "field" || constantIndex(segment.value) !== undefined);
2546
- const visit = (value, evaluated) => {
2547
- if (value.kind === "unary" || value.kind === "convert") {
2548
- visit(value.operand, evaluated);
2549
- }
2550
- if (value.kind === "binary") {
2551
- visit(value.left, evaluated);
2552
- visit(value.right, evaluated);
2553
- }
2554
- if (value.kind !== "load") {
2555
- return;
2556
- }
2557
- if (!temporary(value.root)) {
2558
- if (evaluated || direct(value)) {
2559
- add(value.span, value, value);
2560
- }
2561
- return;
2562
- }
2563
- const defined = definitions.get(value.root) ?? [];
2564
- const [item] = defined;
2565
- if (!item || defined.length !== 1) {
2566
- for (const definition of defined) {
2567
- if (definition.kind === "assign") {
2568
- visit(definition.value, evaluated && executed.has(definition));
2569
- }
2570
- }
2571
- return;
2572
- }
2573
- const reached = evaluated && executed.has(item);
2574
- if (item.kind === "invoke") {
2575
- if (reached) {
2576
- add(item.span, value);
2577
- }
2578
- return;
2579
- }
2580
- if (item.kind !== "assign") {
2581
- return;
2582
- }
2583
- const source = item.value;
2584
- if (source.kind === "load" && !temporary(source.root)) {
2585
- const read = {
2586
- ...source,
2587
- type: value.type,
2588
- path: [...source.path ?? [], ...value.path ?? []]
2589
- };
2590
- if (reached) {
2591
- add(source.span, value, read);
2592
- } else if (direct(read)) {
2593
- add(source.span, read, read);
2594
- }
2595
- return;
2596
- }
2597
- visit(source, reached);
2598
- };
2599
- for (const condition of guard.conditions) {
2600
- visit(condition, true);
2601
- }
2602
- }
2603
- return result.slice(0, trace.operands);
2604
- }
2605
- }
2606
-
2607
- // packages/compiler/src/codesys/expressions.ts
2608
- var storageName = ({ names }, id) => {
2609
- const value = names.get(id);
2610
- if (!value) {
2611
- throw new Error(`Missing verified storage ${id}.`);
2612
- }
2613
- return value;
2614
- };
2615
- var placeText = (scope, id, path = []) => {
2616
- const { typeMap, blocks, blockFields, targetTypes } = scope.symbols;
2617
- let text = storageName(scope, id);
2618
- let typeId = required2(scope.types.get(id));
2619
- let outputBlock;
2620
- for (const segment of path) {
2621
- const type = required2(typeMap.get(typeId));
2622
- if (segment.kind === "field" && type.kind === "block" && segment.name === "out") {
2623
- outputBlock = type.block;
2624
- typeId = required2(type.output);
2625
- continue;
2626
- }
2627
- if (segment.kind === "field" && outputBlock) {
2628
- const output = required2(required2(blocks.get(outputBlock)).outputs.find((field) => field.name === segment.name));
2629
- text += `.${required2(required2(blockFields.get(outputBlock)).get(output.id))}`;
2630
- typeId = output.type;
2631
- outputBlock = undefined;
2632
- } else if (segment.kind === "field" && type.kind === "record") {
2633
- text += `.${targetTypes.field(typeId, segment.name)}`;
2634
- typeId = required2(type.fields.find((field) => field.name === segment.name)).type;
2635
- } else if (segment.kind === "index" && type.kind === "array") {
2636
- text += typeMap.get(segment.value.type)?.kind === "enum" ? `[TO_DINT(${expressionText(scope, segment.value)})]` : `[${expressionText(scope, segment.value)}]`;
2637
- typeId = type.element;
2638
- } else {
2639
- throw new Error("Invalid verified place");
2640
- }
2641
- }
2642
- return text;
2643
- };
2644
- var expressionText = (scope, value) => {
2645
- const { typeMap, targetTypes, numeric } = scope.symbols;
2646
- if (value.kind === "constant") {
2647
- return targetTypes.literal(value.value, value.type);
2648
- }
2649
- if (value.kind === "load") {
2650
- return placeText(scope, value.root, value.path);
2651
- }
2652
- if (value.kind === "borrow") {
2653
- return placeText(scope, value.place.root, value.place.path);
2654
- }
2655
- if (value.kind === "convert" && typeMap.get(value.type)?.kind === "string") {
2656
- return expressionText(scope, value.operand);
2657
- }
2658
- if (value.kind === "unary" || value.kind === "convert") {
2659
- return numeric.render(value, [expressionText(scope, value.operand)]);
2660
- }
2661
- return numeric.render(value, [
2662
- expressionText(scope, value.left),
2663
- expressionText(scope, value.right)
2664
- ]);
2665
- };
2625
+ return {
2626
+ id: "runtime:httpNetwork",
2627
+ kind: "globalList",
2628
+ name: symbols.names.allocateObject("GVL", "TsplcNetwork"),
2629
+ declaration: `{attribute 'qualified_only'}
2630
+ {attribute 'global_init_slot' := '40000'}
2631
+ VAR_GLOBAL
2632
+ network:NBS.AsyncProperty := (usiTaskPrio:=15,udiTaskInterval:=1000,tnTaskName:='tsPLC HTTP');
2633
+ END_VAR
2634
+ `
2635
+ };
2636
+ }
2666
2637
 
2667
2638
  // packages/compiler/src/codesys/manifest.ts
2668
2639
  import {
@@ -2676,7 +2647,17 @@ import {
2676
2647
  } from "@tsplc/compiler/ir";
2677
2648
  import { serviceOfPath } from "@tsplc/server";
2678
2649
  // packages/compiler/package.json
2679
- var version = "0.5.7";
2650
+ var version = "0.5.8";
2651
+
2652
+ // packages/compiler/src/codesys/telemetry.ts
2653
+ import {
2654
+ errorName,
2655
+ httpErrors as httpErrors2,
2656
+ jobErrors,
2657
+ nestedBodies as nestedBodies4
2658
+ } from "@tsplc/compiler/ir";
2659
+ import { telemetrySchema } from "@tsplc/config";
2660
+ import { plcBufferBytes as plcBufferBytes2 } from "@tsplc/server/wire";
2680
2661
 
2681
2662
  // packages/compiler/src/codesys/sources.ts
2682
2663
  import { existsSync, readFileSync } from "node:fs";
@@ -2765,14 +2746,6 @@ class Sources {
2765
2746
  }
2766
2747
 
2767
2748
  // packages/compiler/src/codesys/telemetry.ts
2768
- import {
2769
- errorName,
2770
- httpErrors as httpErrors2,
2771
- jobErrors,
2772
- nestedBodies as nestedBodies4
2773
- } from "@tsplc/compiler/ir";
2774
- import { telemetrySchema } from "@tsplc/config";
2775
- import { plcBufferBytes as plcBufferBytes2 } from "@tsplc/server/wire";
2776
2749
  var telemetryClient = "tsplc:telemetry";
2777
2750
  var telemetryPath = "/tsplc/telemetry";
2778
2751
  var sendIntervalMs = 200;
@@ -3535,242 +3508,1384 @@ function debugHardware(hardware, io, raw) {
3535
3508
  })
3536
3509
  };
3537
3510
  }
3538
- function instancePath(symbols, path) {
3539
- let text = "";
3540
- let holder;
3541
- for (const { variable, index } of path) {
3542
- text += holder ? `.${required2(required2(symbols.blockFields.get(holder)).get(variable.id))}` : required2(symbols.references.get(variable.id));
3543
- if (index !== undefined) {
3544
- text += `[${index}]`;
3511
+ function instancePath(symbols, path) {
3512
+ let text = "";
3513
+ let holder;
3514
+ for (const { variable, index } of path) {
3515
+ text += holder ? `.${required2(required2(symbols.blockFields.get(holder)).get(variable.id))}` : required2(symbols.references.get(variable.id));
3516
+ if (index !== undefined) {
3517
+ text += `[${index}]`;
3518
+ }
3519
+ holder = required2(instancedBlock6(variable.type, symbols.typeMap)).block;
3520
+ }
3521
+ return text;
3522
+ }
3523
+ function requests(context, id, prefix, job) {
3524
+ const { plan, symbols, instrumentation } = context;
3525
+ const block = required2(symbols.blocks.get(id));
3526
+ return block.state.flatMap((child) => {
3527
+ const instance = instancedBlock6(child.type, symbols.typeMap);
3528
+ if (!instance) {
3529
+ return [];
3530
+ }
3531
+ const caller = instrumentation.jobIds.get(child.id) ?? job;
3532
+ const type = required2(symbols.typeMap.get(child.type));
3533
+ const field = `${prefix}.${required2(required2(symbols.blockFields.get(id)).get(child.id))}`;
3534
+ const targets = type.kind === "array" ? Array.from({ length: type.length }, (_, index) => `${field}[${type.lowerBound + index}]`) : [field];
3535
+ const sequence = instrumentation.fields.get(instance.block)?.sequence;
3536
+ const path = plan.http[instance.block]?.path;
3537
+ return targets.flatMap((target) => sequence && path ? [
3538
+ {
3539
+ service: serviceOfPath(path) ?? path,
3540
+ target,
3541
+ sequence: `${target}.${sequence}`,
3542
+ ...caller !== undefined && { job: caller }
3543
+ }
3544
+ ] : requests(context, instance.block, target, caller));
3545
+ });
3546
+ }
3547
+ function reads(variables, body, sources) {
3548
+ const reads = new Map;
3549
+ const expression = (value) => {
3550
+ if (value.kind === "borrow") {
3551
+ return;
3552
+ }
3553
+ subexpressions3(value).forEach(expression);
3554
+ if (value.kind !== "load") {
3555
+ return;
3556
+ }
3557
+ const read = storagePath(required2(variables.get(value.root)), value.path);
3558
+ const range = read && sources.range(value.span);
3559
+ if (range) {
3560
+ reads.set(`${JSON.stringify(range)}${read}`, { range, path: read });
3561
+ }
3562
+ };
3563
+ const statements = (items) => {
3564
+ for (const item of items) {
3565
+ statementExpressions3(item).forEach(expression);
3566
+ nestedBodies5(item).forEach(statements);
3567
+ }
3568
+ };
3569
+ statements(body);
3570
+ return [...reads.values()];
3571
+ }
3572
+ var routineTarget = (symbols, routine) => {
3573
+ if ("inputs" in routine) {
3574
+ return required2(symbols.blockNames.get(routine.id));
3575
+ }
3576
+ const name = required2(symbols.functionNames.get(routine.id));
3577
+ return routine.owner ? `${required2(symbols.blockNames.get(routine.owner.block))}.${name}` : name;
3578
+ };
3579
+ function debugManifest(context, ioTarget, sources, functionIds) {
3580
+ const { plan, symbols, instrumentation } = context;
3581
+ const { core, project, deployment, options } = plan;
3582
+ const settings = project.debug;
3583
+ const global = (field) => `${instrumentation.global}.${field}`;
3584
+ const declaredFunctions = new Map;
3585
+ const routines = new Map(core.functions.map((fn) => [fn.id, fn]));
3586
+ const emittedBlocks = new Map(core.blocks.map((block) => [block.id, block]));
3587
+ const variables = new Map([
3588
+ ...instrumentation.analysis.variables,
3589
+ ...plan.specialized.functions.flatMap((fn) => [...fn.parameters, ...fn.locals].map((variable) => [variable.id, variable])),
3590
+ ...plan.specialized.blocks.flatMap((block) => block.locals.map((variable) => [variable.id, variable]))
3591
+ ]);
3592
+ const functions = [
3593
+ ...plan.specialized.functions,
3594
+ ...plan.specialized.blocks.filter((block) => !block.standard && !block.runtime)
3595
+ ].flatMap((routine) => {
3596
+ const block = "inputs" in routine ? routine : undefined;
3597
+ const fn = "parameters" in routine ? routine : undefined;
3598
+ const declaration = sources.range(block?.job?.span ?? routine.span);
3599
+ if (!declaration) {
3600
+ return [];
3601
+ }
3602
+ const runs = fn ? routines.get(plan.sharedRoutines.get(fn.id) ?? fn.id) : emittedBlocks.get(routine.id);
3603
+ if (!runs) {
3604
+ return [];
3605
+ }
3606
+ const id = declaredFunctions.size;
3607
+ declaredFunctions.set(routine.id, { id, range: declaration });
3608
+ functionIds.set(routine.id, id);
3609
+ const task = instrumentation.analysis.tasks.get(runs.id);
3610
+ const origin = fn?.origin;
3611
+ return [
3612
+ {
3613
+ id,
3614
+ name: block?.job?.name ?? origin?.name ?? routine.name,
3615
+ declaration,
3616
+ ...origin?.instance && { instance: origin.instance },
3617
+ ...task && { task },
3618
+ target: routineTarget(symbols, runs),
3619
+ reads: reads(variables, routine.body, sources)
3620
+ }
3621
+ ];
3622
+ });
3623
+ const declared = (routine) => routine === undefined ? undefined : declaredFunctions.get(routine);
3624
+ const events = instrumentation.analysis.events.flatMap((site) => {
3625
+ const { job } = site;
3626
+ const owner = declared(site.routine);
3627
+ const range = sources.range(site.span) ?? owner?.range;
3628
+ if (!range) {
3629
+ return [];
3630
+ }
3631
+ return [
3632
+ {
3633
+ id: site.id,
3634
+ kind: site.kind,
3635
+ ...job && {
3636
+ job: instrumentation.jobs.findIndex(({ block }) => block.id === job.block) + 1,
3637
+ phase: job.phase
3638
+ },
3639
+ path: site.path,
3640
+ ...owner && { function: owner.id },
3641
+ type: site.type,
3642
+ range,
3643
+ text: site.text ?? sources.text(site.span) ?? "",
3644
+ task: site.task,
3645
+ operands: site.operands.map((operand) => ({
3646
+ text: sources.text(operand.span) ?? "",
3647
+ range: sources.range(operand.span) ?? range,
3648
+ type: operand.capture.type,
3649
+ ...operand.path && { path: operand.path },
3650
+ stable: operand.stable
3651
+ }))
3652
+ }
3653
+ ];
3654
+ });
3655
+ const jobs = instrumentation.jobs.flatMap(({ block, path }, index) => {
3656
+ const job = required2(block.job);
3657
+ const declaration = sources.range(job.span);
3658
+ if (!declaration) {
3659
+ return [];
3660
+ }
3661
+ const target = instancePath(symbols, path);
3662
+ const startedAt = instrumentation.fields.get(block.id)?.startedAt;
3663
+ return [
3664
+ {
3665
+ id: index + 1,
3666
+ name: job.name,
3667
+ declaration,
3668
+ ...job.instance && { instance: job.instance },
3669
+ target,
3670
+ steps: job.steps.map((step) => ({
3671
+ step: step.step,
3672
+ kind: step.kind,
3673
+ range: sources.range(step.span) ?? declaration,
3674
+ text: step.text
3675
+ })),
3676
+ ...startedAt && { startedAt: `${target}.${startedAt}` },
3677
+ requests: requests(context, block.id, target),
3678
+ ...generated(job.name) && { generated: true }
3679
+ }
3680
+ ];
3681
+ });
3682
+ const writers = settings?.writers ? instrumentation.analysis.outputs.map((output, index) => ({
3683
+ output: output.key,
3684
+ target: global(`${instrumentation.slots.writers}[${index}]`),
3685
+ sites: required2(instrumentation.analysis.writers[index]).flatMap((site) => {
3686
+ const owner = declared(site.routine);
3687
+ return owner ? [
3688
+ {
3689
+ id: site.id,
3690
+ range: sources.range(site.span) ?? owner.range,
3691
+ function: owner.id
3692
+ }
3693
+ ] : [];
3694
+ })
3695
+ })) : [];
3696
+ const roots = core.variables.filter((variable) => ["module", "instance", "input", "output"].includes(variable.storage)).map((variable) => {
3697
+ const declaration = sources.range(variable.span);
3698
+ return {
3699
+ path: required2(storagePath(variable)),
3700
+ target: required2(symbols.references.get(variable.id)),
3701
+ type: variable.type,
3702
+ ...declaration && { declaration },
3703
+ readable: true,
3704
+ ...variable.name.startsWith("tsplc") && {
3705
+ generated: true
3706
+ }
3707
+ };
3708
+ });
3709
+ const types = debugTypes(core.types, symbols.targetTypes, symbols.blocks, (block, variable) => required2(required2(symbols.blockFields.get(block)).get(variable)), (block) => {
3710
+ const fields = instrumentation.fields.get(block);
3711
+ return ["busy", "step", "startedAt", "job", "sequence"].flatMap((key) => {
3712
+ const name = fields?.[key];
3713
+ return name ? [{ name, target: name, type: instrumentationFieldTypes[key] }] : [];
3714
+ });
3715
+ }, sources);
3716
+ const hardware = debugHardware(project.hardware ?? {
3717
+ catalog: { descriptors: [], devices: [] },
3718
+ config: { devices: {}, io: options.io },
3719
+ tree: false
3720
+ }, (key) => ioTarget(key), (id) => Object.fromEntries(Object.entries(instrumentation.devices.get(id) ?? {}).map(([direction, raw]) => [direction, global(raw.field)])));
3721
+ const constants = debugConstants(core.folded ?? [], sources);
3722
+ return {
3723
+ kind: "tsplc-debug",
3724
+ version: 1,
3725
+ build: {
3726
+ id: "",
3727
+ target: global("buildId"),
3728
+ compiler: `@tsplc/compiler ${version}`
3729
+ },
3730
+ sources: sources.files,
3731
+ types,
3732
+ roots,
3733
+ constants,
3734
+ ...hardware,
3735
+ functions,
3736
+ jobs,
3737
+ events,
3738
+ writers,
3739
+ tasks: deployment.tasks.map((task) => {
3740
+ const ring = instrumentation.rings.get(task.name);
3741
+ const clock = ring ? global(`${ring}.now`) : instrumentation.scanClocks.get(task.name);
3742
+ return {
3743
+ name: task.name,
3744
+ intervalMs: Number(task.intervalNanoseconds) / 1e6,
3745
+ priority: task.priority,
3746
+ ...clock && { clock }
3747
+ };
3748
+ }),
3749
+ errors: jobErrors2
3750
+ };
3751
+ }
3752
+
3753
+ // packages/compiler/src/codesys/explain.ts
3754
+ class Slots {
3755
+ items = [];
3756
+ positions = new Map;
3757
+ of(global) {
3758
+ const known = this.positions.get(global);
3759
+ if (known !== undefined) {
3760
+ return known;
3545
3761
  }
3546
- holder = required2(instancedBlock6(variable.type, symbols.typeMap)).block;
3762
+ this.positions.set(global, this.items.length);
3763
+ this.items.push(global);
3764
+ return this.items.length - 1;
3547
3765
  }
3548
- return text;
3549
3766
  }
3550
- function requests(context, id, prefix, job) {
3551
- const { plan, symbols, instrumentation } = context;
3552
- const block = required2(symbols.blocks.get(id));
3553
- return block.state.flatMap((child) => {
3554
- const instance = instancedBlock6(child.type, symbols.typeMap);
3555
- if (!instance) {
3556
- return [];
3767
+ var aggregateKinds = new Set([
3768
+ "record",
3769
+ "array",
3770
+ "block"
3771
+ ]);
3772
+ var maxSnippetLines = 8;
3773
+ var staticNames = (path) => {
3774
+ const names = [];
3775
+ for (const segment of path) {
3776
+ if (segment.kind === "field") {
3777
+ names.push(segment.name);
3778
+ } else if (segment.value.kind === "constant" && segment.value.value.kind === "integer") {
3779
+ names.push(segment.value.value.value);
3780
+ } else {
3781
+ return;
3557
3782
  }
3558
- const caller = instrumentation.jobIds.get(child.id) ?? job;
3559
- const type = required2(symbols.typeMap.get(child.type));
3560
- const field = `${prefix}.${required2(required2(symbols.blockFields.get(id)).get(child.id))}`;
3561
- const targets = type.kind === "array" ? Array.from({ length: type.length }, (_, index) => `${field}[${type.lowerBound + index}]`) : [field];
3562
- const sequence = instrumentation.fields.get(instance.block)?.sequence;
3563
- const path = plan.http[instance.block]?.path;
3564
- return targets.flatMap((target) => sequence && path ? [
3565
- {
3566
- service: serviceOfPath(path) ?? path,
3567
- target,
3568
- sequence: `${target}.${sequence}`,
3569
- ...caller !== undefined && { job: caller }
3570
- }
3571
- ] : requests(context, instance.block, target, caller));
3572
- });
3783
+ }
3784
+ return names;
3785
+ };
3786
+ var constantAt = (value, names) => {
3787
+ const [name, ...rest] = names;
3788
+ if (name === undefined) {
3789
+ return value;
3790
+ }
3791
+ if (value.kind === "record") {
3792
+ const field = value.fields[name];
3793
+ return field && constantAt(field, rest);
3794
+ }
3795
+ return;
3796
+ };
3797
+ var anyIndex = (path) => path.replace(/\[-?\d+\]/g, "[*]");
3798
+
3799
+ class Table {
3800
+ items = [];
3801
+ keys = new Map;
3802
+ add(value) {
3803
+ const key = JSON.stringify(value);
3804
+ const known = this.keys.get(key);
3805
+ if (known !== undefined) {
3806
+ return known;
3807
+ }
3808
+ this.keys.set(key, this.items.length);
3809
+ this.items.push(value);
3810
+ return this.items.length - 1;
3811
+ }
3573
3812
  }
3574
- function reads(variables, body, sources) {
3575
- const reads = new Map;
3576
- const expression = (value) => {
3577
- if (value.kind === "borrow") {
3578
- return;
3813
+ function explanations(context, manifest, sources, functionIds) {
3814
+ const { plan, instrumentation } = context;
3815
+ const program = plan.specialized;
3816
+ const types = new Map(program.types.map((type) => [type.id, type]));
3817
+ const variables = variablesById(program);
3818
+ const blocks = new Map(program.blocks.map((block) => [block.id, block]));
3819
+ const functions = new Map(program.functions.map((fn) => [fn.id, fn]));
3820
+ const instances = blockInstances(program);
3821
+ const access = publishedAccess(plan);
3822
+ const paths = new Table;
3823
+ const texts = new Table;
3824
+ const expressions = new Table;
3825
+ const conditionTree = new Table;
3826
+ const conditionsIndex = (list) => list.reduce((parent, condition) => conditionTree.add({ parent, condition }), null);
3827
+ const sites = new Table;
3828
+ const rows = [];
3829
+ const routineRows = [];
3830
+ const loops = [];
3831
+ const assignments = [];
3832
+ const locals = [];
3833
+ const returns = [];
3834
+ const calls = [];
3835
+ const callIndexes = new Map;
3836
+ const recorded = new Map;
3837
+ const localIndexes = new Map;
3838
+ const loopBases = new Map;
3839
+ const referenceFields = new Set((program.references?.fields ?? []).map(anyIndex));
3840
+ const readers = new Map;
3841
+ const range = (span) => sources.range(span) ?? null;
3842
+ const text = (span) => {
3843
+ const source = sources.range(span) && sources.text(span);
3844
+ return source ? texts.add(source) : null;
3845
+ };
3846
+ const site = (span) => {
3847
+ const found = range(span);
3848
+ if (!found) {
3849
+ return null;
3579
3850
  }
3580
- subexpressions3(value).forEach(expression);
3581
- if (value.kind !== "load") {
3851
+ const snippet = found.endLine - found.line < maxSnippetLines ? text(span) : null;
3852
+ return sites.add({ range: found, text: snippet });
3853
+ };
3854
+ const instanceText = (path) => path.map(({ variable, index }, position) => {
3855
+ const name = position === 0 ? storagePath(variable) ?? variable.name : `.${variable.name}`;
3856
+ return index === undefined ? name : `${name}[${index}]`;
3857
+ }).join("");
3858
+ const jobInstances = instrumentation.jobs.map(({ block, path }) => ({
3859
+ block: block.id,
3860
+ instance: instanceText(path)
3861
+ }));
3862
+ const conditionsByRoutine = new Map;
3863
+ const conditionsOf = (routine) => {
3864
+ const known = conditionsByRoutine.get(routine.id);
3865
+ if (known) {
3866
+ return known;
3867
+ }
3868
+ const analysed = pathConditions(routine, variables);
3869
+ conditionsByRoutine.set(routine.id, analysed);
3870
+ return analysed;
3871
+ };
3872
+ const addRow = (routine, path) => {
3873
+ const block = "inputs" in routine ? routine : blocks.get(routine.owner?.block ?? "");
3874
+ const instance = path ? instanceText(path) : null;
3875
+ const job = jobInstances.findIndex((item) => item.block === routine.id && item.instance === instance);
3876
+ const row = {
3877
+ index: rows.length,
3878
+ routine,
3879
+ conditions: conditionsOf(routine),
3880
+ instance,
3881
+ fields: new Set(block ? [...block.inputs, ...block.outputs, ...block.state].map((variable) => variable.id) : []),
3882
+ job: job < 0 ? null : job + 1,
3883
+ slots: { paths: new Slots, locals: new Slots, calls: new Slots }
3884
+ };
3885
+ rows.push(row);
3886
+ const fn = "parameters" in routine ? routine : undefined;
3887
+ routineRows.push({
3888
+ key: routine.id,
3889
+ function: functionIds.get(routine.id) ?? null,
3890
+ instance: instance === null ? null : paths.add(instance),
3891
+ name: ("inputs" in routine ? routine.job?.name : undefined) ?? fn?.origin?.name ?? routine.name,
3892
+ declaration: range(("inputs" in routine ? routine.job?.span : undefined) ?? routine.span)
3893
+ });
3894
+ };
3895
+ for (const fn of program.functions) {
3896
+ const owner = fn.owner?.block;
3897
+ if (owner === undefined) {
3898
+ addRow(fn, null);
3899
+ continue;
3900
+ }
3901
+ for (const path of instances.get(owner) ?? []) {
3902
+ addRow(fn, path);
3903
+ }
3904
+ }
3905
+ for (const block of program.blocks) {
3906
+ if (block.standard || serviceBlock(block) || !block.body.length) {
3907
+ continue;
3908
+ }
3909
+ for (const path of instances.get(block.id) ?? []) {
3910
+ addRow(block, path);
3911
+ }
3912
+ }
3913
+ const spell = (row, root, path) => {
3914
+ const variable = variables.get(root);
3915
+ if (!variable) {
3582
3916
  return;
3583
3917
  }
3584
- const read = storagePath(required2(variables.get(value.root)), value.path);
3585
- const range = read && sources.range(value.span);
3586
- if (range) {
3587
- reads.set(`${JSON.stringify(range)}${read}`, { range, path: read });
3918
+ const base = () => {
3919
+ if (row.fields.has(root)) {
3920
+ return row.instance === null ? undefined : `${row.instance}.${variable.name}`;
3921
+ }
3922
+ if (variable.storage === "constant") {
3923
+ return `${moduleName(variable)}.${variable.name}`;
3924
+ }
3925
+ return storagePath(variable);
3926
+ };
3927
+ const start = base();
3928
+ return start === undefined ? undefined : extend(row, { text: start, indexes: [], type: types.get(variable.type) }, path);
3929
+ };
3930
+ const extend = (row, spelled, path) => {
3931
+ let { text: current, type } = spelled;
3932
+ const indexes = [...spelled.indexes];
3933
+ for (const segment of path) {
3934
+ if (segment.kind === "field") {
3935
+ if (type?.kind === "block") {
3936
+ if (segment.name === "out") {
3937
+ type = type.output ? types.get(type.output) : undefined;
3938
+ continue;
3939
+ }
3940
+ const block = blocks.get(type.block);
3941
+ const field = block ? [...block.inputs, ...block.outputs, ...block.state].find((variable) => variable.name === segment.name) : undefined;
3942
+ type = field ? types.get(field.type) : undefined;
3943
+ } else if (type?.kind === "record") {
3944
+ const field = type.fields.find((item) => item.name === segment.name);
3945
+ type = field ? types.get(field.type) : undefined;
3946
+ } else {
3947
+ type = undefined;
3948
+ }
3949
+ current += `.${segment.name}`;
3950
+ continue;
3951
+ }
3952
+ type = type?.kind === "array" ? types.get(type.element) : undefined;
3953
+ const value = segment.value;
3954
+ if (value.kind === "constant" && value.value.kind === "integer") {
3955
+ current += `[${value.value.value}]`;
3956
+ } else {
3957
+ current += "[*]";
3958
+ indexes.push(expression(row, value));
3959
+ }
3588
3960
  }
3961
+ return { text: current, indexes, type };
3589
3962
  };
3590
- const statements = (items) => {
3591
- for (const item of items) {
3592
- statementExpressions3(item).forEach(expression);
3593
- nestedBodies5(item).forEach(statements);
3963
+ const localIndex = (row, root) => {
3964
+ const key = `${row.index}:${root}`;
3965
+ const known = localIndexes.get(key);
3966
+ if (known !== undefined) {
3967
+ return known;
3594
3968
  }
3969
+ const variable = variables.get(root);
3970
+ localIndexes.set(key, locals.length);
3971
+ locals.push({
3972
+ routine: row.index,
3973
+ name: variable?.name ?? root,
3974
+ parameter: variable?.storage === "parameter",
3975
+ reference: false,
3976
+ definitions: []
3977
+ });
3978
+ return locals.length - 1;
3595
3979
  };
3596
- statements(body);
3597
- return [...reads.values()];
3598
- }
3599
- var routineTarget = (symbols, routine) => {
3600
- if ("inputs" in routine) {
3601
- return required2(symbols.blockNames.get(routine.id));
3602
- }
3603
- const name = required2(symbols.functionNames.get(routine.id));
3604
- return routine.owner ? `${required2(symbols.blockNames.get(routine.owner.block))}.${name}` : name;
3605
- };
3606
- function debugManifest(context, ioTarget) {
3607
- const { plan, symbols, instrumentation } = context;
3608
- const { core, project, deployment, options } = plan;
3609
- const settings = project.debug;
3610
- const sources = new Sources(project.root);
3611
- const global = (field) => `${instrumentation.global}.${field}`;
3612
- const declaredFunctions = new Map;
3613
- const routines = new Map(core.functions.map((fn) => [fn.id, fn]));
3614
- const variables = new Map([
3615
- ...instrumentation.analysis.variables,
3616
- ...plan.specialized.flatMap((fn) => [...fn.parameters, ...fn.locals].map((variable) => [variable.id, variable]))
3980
+ const opaque = (reason, type, reads = []) => expressions.add({
3981
+ kind: "opaque",
3982
+ text: texts.add(reason),
3983
+ reads: [...reads],
3984
+ type
3985
+ });
3986
+ const expression = (row, node) => {
3987
+ switch (node.kind) {
3988
+ case "read": {
3989
+ const table = variables.get(node.root);
3990
+ const names = staticNames(node.path);
3991
+ const fixed = table?.storage === "constant" && table.initial && names ? constantAt(table.initial, names) : undefined;
3992
+ if (fixed) {
3993
+ return expressions.add({
3994
+ kind: "constant",
3995
+ value: constantValue(fixed),
3996
+ type: node.type
3997
+ });
3998
+ }
3999
+ const spelled = spell(row, node.root, node.path);
4000
+ if (!spelled) {
4001
+ return opaque("not stored", node.type);
4002
+ }
4003
+ const path = row.slots.paths.of(paths.add(spelled.text));
4004
+ const readBy = readers.get(spelled.text) ?? new Set;
4005
+ readBy.add(row.index);
4006
+ readers.set(spelled.text, readBy);
4007
+ const read = expressions.add(spelled.indexes.length ? {
4008
+ kind: "pattern",
4009
+ path,
4010
+ indexes: [...spelled.indexes],
4011
+ capturedAt: node.capturedAt,
4012
+ ...node.interleaved && { interleaved: true },
4013
+ type: node.type
4014
+ } : {
4015
+ kind: "read",
4016
+ path,
4017
+ capturedAt: node.capturedAt,
4018
+ ...node.interleaved && { interleaved: true },
4019
+ type: node.type
4020
+ });
4021
+ return referenceFields.has(anyIndex(spelled.text)) ? expressions.add({ kind: "reference", operand: read }) : read;
4022
+ }
4023
+ case "local": {
4024
+ const names = staticNames(node.path);
4025
+ return names ? expressions.add({
4026
+ kind: "local",
4027
+ local: row.slots.locals.of(localIndex(row, node.root)),
4028
+ path: names,
4029
+ at: node.at,
4030
+ type: node.type
4031
+ }) : opaque("a local at a dynamic index", node.type);
4032
+ }
4033
+ case "parameter": {
4034
+ const names = staticNames(node.path);
4035
+ if (!names) {
4036
+ return opaque("a parameter at a dynamic index", node.type);
4037
+ }
4038
+ const written = writesThrough.has(`${row.routine.id}#${node.parameter}`);
4039
+ return expressions.add({
4040
+ kind: "parameter",
4041
+ parameter: node.parameter,
4042
+ path: names,
4043
+ at: node.at,
4044
+ local: written ? row.slots.locals.of(localIndex(row, node.root)) : null,
4045
+ type: node.type
4046
+ });
4047
+ }
4048
+ case "call": {
4049
+ const call = callIndexes.get(row)?.get(node.call);
4050
+ return call === undefined ? opaque("a call that isn't traced", node.type) : expressions.add({
4051
+ kind: "call",
4052
+ call: row.slots.calls.of(call),
4053
+ path: [...node.path],
4054
+ type: node.type
4055
+ });
4056
+ }
4057
+ case "constant":
4058
+ return expressions.add({
4059
+ kind: "constant",
4060
+ value: constantValue(node.value),
4061
+ type: node.type
4062
+ });
4063
+ case "clock":
4064
+ return expressions.add({ kind: "clock", type: node.type });
4065
+ case "unary":
4066
+ return expressions.add({
4067
+ kind: "unary",
4068
+ operator: node.operator,
4069
+ operand: expression(row, node.operand),
4070
+ type: node.type
4071
+ });
4072
+ case "binary":
4073
+ return expressions.add({
4074
+ kind: "binary",
4075
+ operator: node.operator,
4076
+ ...node.policy && { policy: node.policy },
4077
+ left: expression(row, node.left),
4078
+ right: expression(row, node.right),
4079
+ type: node.type
4080
+ });
4081
+ case "convert":
4082
+ return expressions.add({
4083
+ kind: "convert",
4084
+ policy: node.policy,
4085
+ operand: expression(row, node.operand),
4086
+ type: node.type
4087
+ });
4088
+ case "logical":
4089
+ return expressions.add({
4090
+ kind: "logical",
4091
+ operator: node.operator,
4092
+ left: expression(row, node.left),
4093
+ right: expression(row, node.right)
4094
+ });
4095
+ case "select":
4096
+ return expressions.add({
4097
+ kind: "select",
4098
+ condition: expression(row, node.condition),
4099
+ then: expression(row, node.then),
4100
+ else: expression(row, node.else),
4101
+ type: node.type
4102
+ });
4103
+ case "record":
4104
+ return expressions.add({
4105
+ kind: "record",
4106
+ fields: Object.fromEntries(Object.entries(node.fields).map(([name, value]) => [
4107
+ name,
4108
+ expression(row, value)
4109
+ ])),
4110
+ type: node.type
4111
+ });
4112
+ case "array":
4113
+ return expressions.add({
4114
+ kind: "array",
4115
+ lower: node.lower,
4116
+ items: node.items.map((item) => expression(row, item)),
4117
+ type: node.type
4118
+ });
4119
+ case "opaque":
4120
+ return opaque(node.reason, node.type, node.reads.map((read) => expression(row, read)));
4121
+ }
4122
+ };
4123
+ const condition = (row, item) => {
4124
+ switch (item.kind) {
4125
+ case "test":
4126
+ return {
4127
+ kind: "test",
4128
+ test: expression(row, item.test),
4129
+ holds: item.holds,
4130
+ at: item.at,
4131
+ text: text(item.span)
4132
+ };
4133
+ case "cases":
4134
+ return {
4135
+ kind: "cases",
4136
+ test: expression(row, item.test),
4137
+ values: item.values.map(constantValue),
4138
+ member: item.member,
4139
+ at: item.at,
4140
+ text: text(item.span)
4141
+ };
4142
+ case "exits":
4143
+ return {
4144
+ kind: "exits",
4145
+ any: item.any.map((all) => all.map((part) => condition(row, part)))
4146
+ };
4147
+ case "loop":
4148
+ case "loopReturns":
4149
+ return { kind: item.kind, loop: item.loop };
4150
+ case "job":
4151
+ return { kind: "job", step: item.step };
4152
+ case "jobBusy":
4153
+ return { kind: "jobBusy" };
4154
+ }
4155
+ };
4156
+ const parameterIndex = (routine, root) => ("parameters" in routine) ? routine.parameters.findIndex((parameter) => parameter.id === root) : -1;
4157
+ const calleeParameters = (item) => {
4158
+ if (item.kind === "invoke") {
4159
+ return { routine: item.function, arguments: item.arguments };
4160
+ }
4161
+ if (item.kind !== "blockUpdate") {
4162
+ return;
4163
+ }
4164
+ const block = instancedBlock7(variables.get(item.instance)?.type ?? "", types);
4165
+ const called = block && blocks.get(block.block);
4166
+ return called ? {
4167
+ routine: called.id,
4168
+ arguments: called.inputs.flatMap((input) => {
4169
+ const value = item.inputs[input.name];
4170
+ return value ? [value] : [];
4171
+ })
4172
+ } : undefined;
4173
+ };
4174
+ const statementsOf = (items) => items.flatMap((item) => [
4175
+ item,
4176
+ ...nestedBodies6(item).flatMap(statementsOf)
3617
4177
  ]);
3618
- const functions = [
3619
- ...plan.specialized,
3620
- ...core.blocks.filter((block) => !block.standard && !block.runtime)
3621
- ].flatMap((routine) => {
3622
- const block = "inputs" in routine ? routine : undefined;
3623
- const fn = "parameters" in routine ? routine : undefined;
3624
- const declaration = sources.range(block?.job?.span ?? routine.span);
3625
- if (!declaration) {
3626
- return [];
4178
+ const writesThrough = new Set;
4179
+ const allRoutines = [...program.functions, ...program.blocks];
4180
+ const propagate = () => {
4181
+ const added = allRoutines.flatMap((routine) => statementsOf(routine.body).flatMap((item) => {
4182
+ const passed = calleeParameters(item);
4183
+ const indexes = [
4184
+ ...item.kind === "assign" ? [parameterIndex(routine, item.root)] : [],
4185
+ ...(passed?.arguments ?? []).flatMap((argument, index) => argument.kind === "borrow" && writesThrough.has(`${passed?.routine}#${index}`) ? [parameterIndex(routine, argument.place.root)] : [])
4186
+ ];
4187
+ return indexes.filter((index) => index >= 0).map((index) => `${routine.id}#${index}`).filter((key) => !writesThrough.has(key));
4188
+ }));
4189
+ for (const key of added) {
4190
+ writesThrough.add(key);
3627
4191
  }
3628
- const runs = fn ? routines.get(plan.sharedRoutines.get(fn.id) ?? fn.id) : routine;
3629
- if (!runs) {
3630
- return [];
4192
+ return added.length > 0;
4193
+ };
4194
+ while (propagate()) {}
4195
+ const segments = (row, path, at) => path.map((segment) => segment.kind === "field" ? segment : {
4196
+ kind: "index",
4197
+ value: row.conditions.reconstruct(segment.value, at)
4198
+ });
4199
+ const written = (spelled) => spelled.indexes.length ? {
4200
+ kind: "pattern",
4201
+ path: paths.add(spelled.text),
4202
+ indexes: [...spelled.indexes]
4203
+ } : { kind: "path", path: paths.add(spelled.text) };
4204
+ const loopOf = (row, loop) => loop === null ? null : (loopBases.get(row) ?? 0) + loop;
4205
+ const typeIsAggregate = (spelled) => spelled.type !== undefined && aggregateKinds.has(spelled.type.kind);
4206
+ const receiver = (row, instance, index, at, callee) => {
4207
+ if (instance === undefined) {
4208
+ return functions.get(callee)?.owner && row.instance !== null ? { kind: "path", path: paths.add(row.instance) } : { kind: "none" };
4209
+ }
4210
+ const spelled = spell(row, instance, index ? [{ kind: "index", value: row.conditions.reconstruct(index, at) }] : []);
4211
+ if (!spelled) {
4212
+ return { kind: "none" };
4213
+ }
4214
+ return spelled.indexes.length ? {
4215
+ kind: "pattern",
4216
+ path: paths.add(spelled.text),
4217
+ indexes: [...spelled.indexes]
4218
+ } : { kind: "path", path: paths.add(spelled.text) };
4219
+ };
4220
+ for (const row of rows) {
4221
+ const indexes = new Map;
4222
+ for (const item of row.conditions.statements.keys()) {
4223
+ if (item.kind === "invoke" || item.kind === "blockUpdate") {
4224
+ indexes.set(item, indexes.size + calls.length);
4225
+ }
3631
4226
  }
3632
- const id = declaredFunctions.size;
3633
- declaredFunctions.set(routine.id, { id, range: declaration });
3634
- const task = instrumentation.analysis.tasks.get(runs.id);
3635
- const origin = fn?.origin;
3636
- return [
3637
- {
3638
- id,
3639
- name: block?.job?.name ?? origin?.name ?? routine.name,
3640
- declaration,
3641
- ...origin?.instance && { instance: origin.instance },
3642
- ...task && { task },
3643
- target: routineTarget(symbols, runs),
3644
- reads: reads(variables, routine.body, sources)
4227
+ callIndexes.set(row, indexes);
4228
+ for (const call of indexes.values()) {
4229
+ row.slots.calls.of(call);
4230
+ }
4231
+ calls.push(...[...indexes.keys()].map(() => ({
4232
+ routine: row.index,
4233
+ position: 0,
4234
+ conditions: null,
4235
+ site: null,
4236
+ callee: "",
4237
+ receiver: { kind: "none" },
4238
+ arguments: [],
4239
+ loop: null
4240
+ })));
4241
+ loopBases.set(row, loops.length);
4242
+ for (const loop of row.conditions.loops) {
4243
+ loops.push({
4244
+ routine: row.index,
4245
+ position: loop.position,
4246
+ counter: 0,
4247
+ first: 0,
4248
+ limit: 0,
4249
+ exclusive: loop.exclusive,
4250
+ step: 0,
4251
+ maxIterations: loop.maxIterations,
4252
+ breaks: [],
4253
+ parent: null,
4254
+ site: site(loop.statement.span)
4255
+ });
4256
+ }
4257
+ }
4258
+ for (const row of rows) {
4259
+ const { routine, conditions } = row;
4260
+ const base = loopBases.get(row) ?? 0;
4261
+ conditions.loops.forEach((loop, index) => {
4262
+ const counter = variables.get(loop.counter);
4263
+ const slot = loops[base + index];
4264
+ if (!slot) {
4265
+ return;
3645
4266
  }
3646
- ];
3647
- });
3648
- const declared = (routine) => routine === undefined ? undefined : declaredFunctions.get(routine);
3649
- const events = instrumentation.analysis.events.flatMap((site) => {
3650
- const { job } = site;
3651
- const owner = declared(site.routine);
3652
- const range = sources.range(site.span) ?? owner?.range;
3653
- if (!range) {
3654
- return [];
4267
+ loops[base + index] = {
4268
+ ...slot,
4269
+ counter: expression(row, conditions.reconstruct({
4270
+ kind: "load",
4271
+ root: loop.counter,
4272
+ type: counter?.type ?? "DINT",
4273
+ span: loop.statement.span
4274
+ }, loop.position)),
4275
+ first: expression(row, loop.first),
4276
+ limit: expression(row, loop.limit),
4277
+ step: expressions.add({
4278
+ kind: "constant",
4279
+ value: Number(loop.step),
4280
+ type: counter?.type ?? "DINT"
4281
+ }),
4282
+ breaks: loop.breaks.map((all) => all.map((part) => condition(row, part))),
4283
+ parent: loop.parent === null ? null : base + loop.parent
4284
+ };
4285
+ });
4286
+ const block = "inputs" in routine ? routine : undefined;
4287
+ for (const [item, flow] of conditions.statements) {
4288
+ const first = assignments.length;
4289
+ const at = flow.position;
4290
+ const record = {
4291
+ routine: row.index,
4292
+ position: at,
4293
+ conditions: conditionsIndex(flow.conditions.map((part) => condition(row, part))),
4294
+ site: site(item.span)
4295
+ };
4296
+ const loop = loopOf(row, flow.loop);
4297
+ const reconstruct = (value) => expression(row, conditions.reconstruct(value, at));
4298
+ const write = (root, path, kind, value) => {
4299
+ const variable = variables.get(root);
4300
+ const parameter = parameterIndex(routine, root);
4301
+ const local = variable?.storage === "local" && routine.locals.some((candidate) => candidate.id === root);
4302
+ const temporary = local && root.includes(":temporary:");
4303
+ if (temporary) {
4304
+ return;
4305
+ }
4306
+ if (local || parameter >= 0) {
4307
+ const names = staticNames(segments(row, path, at));
4308
+ const target = locals[localIndex(row, root)];
4309
+ target?.definitions.push({
4310
+ ...record,
4311
+ kind: kind === "counter" ? "counter" : "assign",
4312
+ path: names ?? [],
4313
+ value: names ? value : null,
4314
+ call: null,
4315
+ loop
4316
+ });
4317
+ return;
4318
+ }
4319
+ const spelled = spell(row, root, segments(row, path, at));
4320
+ if (!spelled) {
4321
+ return;
4322
+ }
4323
+ assignments.push({
4324
+ ...record,
4325
+ kind,
4326
+ writes: written(spelled),
4327
+ whole: typeIsAggregate(spelled),
4328
+ value,
4329
+ block: null,
4330
+ via: [],
4331
+ loop
4332
+ });
4333
+ };
4334
+ const borrowed = (call, argument, index, callee) => {
4335
+ if (argument.kind !== "borrow" || !writesThrough.has(`${callee}#${index}`)) {
4336
+ return;
4337
+ }
4338
+ const root = argument.place.root;
4339
+ const isLocal = routine.locals.some((candidate) => candidate.id === root) && !root.includes(":temporary:");
4340
+ if (!isLocal && parameterIndex(routine, root) < 0) {
4341
+ return;
4342
+ }
4343
+ const names = staticNames(segments(row, argument.place.path, at));
4344
+ locals[localIndex(row, root)]?.definitions.push({
4345
+ ...record,
4346
+ kind: "borrowed",
4347
+ path: names ?? [],
4348
+ value: null,
4349
+ call,
4350
+ loop
4351
+ });
4352
+ };
4353
+ switch (item.kind) {
4354
+ case "assign":
4355
+ write(item.root, item.path ?? [], "assign", reconstruct(item.value));
4356
+ break;
4357
+ case "invoke": {
4358
+ const call = callIndexes.get(row)?.get(item) ?? 0;
4359
+ calls[call] = {
4360
+ ...record,
4361
+ callee: item.function,
4362
+ receiver: receiver(row, item.instance, item.index, at, item.function),
4363
+ arguments: item.arguments.map((argument) => reconstruct(argument)),
4364
+ loop
4365
+ };
4366
+ item.arguments.forEach((argument, index) => {
4367
+ borrowed(call, argument, index, item.function);
4368
+ });
4369
+ if (item.destination) {
4370
+ const result = functions.get(item.function)?.result ?? "BOOL";
4371
+ write(item.destination, [], "call", expressions.add({ kind: "call", call, path: [], type: result }));
4372
+ }
4373
+ break;
4374
+ }
4375
+ case "blockUpdate": {
4376
+ const call = callIndexes.get(row)?.get(item) ?? 0;
4377
+ const instance = variables.get(item.instance);
4378
+ const type = instancedBlock7(instance?.type ?? "", types);
4379
+ const called = type && blocks.get(type.block);
4380
+ const target = receiver(row, item.instance, item.index, at, called?.id ?? "");
4381
+ const spelled = spell(row, item.instance, item.index ? [
4382
+ {
4383
+ kind: "index",
4384
+ value: conditions.reconstruct(item.index, at)
4385
+ }
4386
+ ] : []);
4387
+ calls[call] = {
4388
+ ...record,
4389
+ callee: called?.id ?? "",
4390
+ receiver: target,
4391
+ arguments: (called?.inputs ?? []).flatMap((input) => {
4392
+ const value = item.inputs[input.name];
4393
+ return value ? [reconstruct(value)] : [];
4394
+ }),
4395
+ loop
4396
+ };
4397
+ if (!called || !spelled) {
4398
+ break;
4399
+ }
4400
+ if (called.standard) {
4401
+ const native = standardBlocks4[called.standard];
4402
+ const elapsed = native.outputs.some(([name]) => name === "elapsed") ? extend(row, spelled, [{ kind: "field", name: "elapsed" }]) : undefined;
4403
+ assignments.push({
4404
+ ...record,
4405
+ kind: "block",
4406
+ writes: written(spelled),
4407
+ whole: true,
4408
+ value: null,
4409
+ block: {
4410
+ kind: called.standard,
4411
+ inputs: Object.fromEntries(Object.entries(item.inputs).map(([name, value]) => [
4412
+ name,
4413
+ reconstruct(value)
4414
+ ])),
4415
+ elapsed: elapsed ? expressions.add(elapsed.indexes.length ? {
4416
+ kind: "pattern",
4417
+ path: row.slots.paths.of(paths.add(elapsed.text)),
4418
+ indexes: [...elapsed.indexes],
4419
+ capturedAt: at,
4420
+ type: "TIME"
4421
+ } : {
4422
+ kind: "read",
4423
+ path: row.slots.paths.of(paths.add(elapsed.text)),
4424
+ capturedAt: at,
4425
+ type: "TIME"
4426
+ }) : null
4427
+ },
4428
+ via: [],
4429
+ loop
4430
+ });
4431
+ break;
4432
+ }
4433
+ called.inputs.forEach((input, index) => {
4434
+ const value = item.inputs[input.name];
4435
+ if (!value) {
4436
+ return;
4437
+ }
4438
+ if (value.kind === "borrow") {
4439
+ borrowed(call, value, index, called.id);
4440
+ return;
4441
+ }
4442
+ const field = extend(row, spelled, [
4443
+ { kind: "field", name: input.name }
4444
+ ]);
4445
+ assignments.push({
4446
+ ...record,
4447
+ kind: "input",
4448
+ writes: written(field),
4449
+ whole: typeIsAggregate(field),
4450
+ value: reconstruct(value),
4451
+ block: null,
4452
+ via: [],
4453
+ loop
4454
+ });
4455
+ });
4456
+ break;
4457
+ }
4458
+ case "for":
4459
+ write(item.counter, [], "counter", null);
4460
+ break;
4461
+ case "return": {
4462
+ returns.push({
4463
+ ...record,
4464
+ value: item.value ? reconstruct(item.value) : null
4465
+ });
4466
+ const value = item.value;
4467
+ if (!block || !value || row.instance === null) {
4468
+ break;
4469
+ }
4470
+ const returned = conditions.reconstruct(value, at);
4471
+ for (const output of block.outputs) {
4472
+ const field = spell(row, output.id, []);
4473
+ if (!field) {
4474
+ continue;
4475
+ }
4476
+ assignments.push({
4477
+ ...record,
4478
+ kind: "return",
4479
+ writes: written(field),
4480
+ whole: typeIsAggregate(field),
4481
+ value: expression(row, projectReconstruction(returned, [{ kind: "field", name: output.name }], output.type)),
4482
+ block: null,
4483
+ via: [],
4484
+ loop
4485
+ });
4486
+ }
4487
+ break;
4488
+ }
4489
+ default:
4490
+ break;
4491
+ }
4492
+ if (assignments.length > first) {
4493
+ recorded.set(item, [
4494
+ ...recorded.get(item) ?? [],
4495
+ ...Array.from({ length: assignments.length - first }, (_, offset) => first + offset)
4496
+ ]);
4497
+ }
4498
+ }
4499
+ }
4500
+ const calleeRows = (call, caller) => rows.filter((row) => {
4501
+ if (row.routine.id !== call.callee) {
4502
+ return false;
4503
+ }
4504
+ if (call.receiver.kind === "none") {
4505
+ return row.instance === null;
4506
+ }
4507
+ if (call.receiver.kind === "pattern") {
4508
+ return false;
4509
+ }
4510
+ return paths.items[call.receiver.path] === row.instance;
4511
+ }).concat(call.receiver.kind === "none" && caller.instance !== null && functions.get(call.callee)?.owner ? rows.filter((row) => row.routine.id === call.callee && row.instance === caller.instance) : []);
4512
+ const throughParameter = (target, callee, parameter, via, depth) => {
4513
+ const root = "parameters" in callee.routine ? callee.routine.parameters[parameter]?.id : undefined;
4514
+ if (root === undefined || depth > 16) {
4515
+ return;
4516
+ }
4517
+ for (const [item, flow] of callee.conditions.statements) {
4518
+ const at = flow.position;
4519
+ const record = {
4520
+ routine: callee.index,
4521
+ position: at,
4522
+ conditions: conditionsIndex(flow.conditions.map((part) => condition(callee, part))),
4523
+ site: site(item.span)
4524
+ };
4525
+ const fixed = (path) => path.every((segment) => segment.kind === "field" || segment.value.kind === "constant");
4526
+ if (item.kind === "assign" && item.root === root && fixed(item.path ?? [])) {
4527
+ const spelled = extend(callee, target, segments(callee, item.path ?? [], at));
4528
+ assignments.push({
4529
+ ...record,
4530
+ kind: "assign",
4531
+ writes: written(spelled),
4532
+ whole: typeIsAggregate(spelled),
4533
+ value: expression(callee, callee.conditions.reconstruct(item.value, at)),
4534
+ block: null,
4535
+ via: [...via],
4536
+ loop: loopOf(callee, flow.loop)
4537
+ });
4538
+ }
4539
+ const passed = calleeParameters(item);
4540
+ const call = callIndexes.get(callee)?.get(item);
4541
+ const nested = call === undefined ? undefined : calls[call];
4542
+ if (!passed || call === undefined || !nested) {
4543
+ continue;
4544
+ }
4545
+ passed.arguments.forEach((argument, index) => {
4546
+ if (argument.kind !== "borrow" || argument.place.root !== root || !fixed(argument.place.path) || !writesThrough.has(`${passed.routine}#${index}`)) {
4547
+ return;
4548
+ }
4549
+ const inner = extend(callee, target, segments(callee, argument.place.path, at));
4550
+ for (const next of calleeRows(nested, callee)) {
4551
+ throughParameter(inner, next, index, [call, ...via], depth + 1);
4552
+ }
4553
+ });
3655
4554
  }
3656
- return [
3657
- {
3658
- id: site.id,
3659
- kind: site.kind,
3660
- ...job && {
3661
- job: instrumentation.jobs.findIndex(({ block }) => block.id === job.block) + 1,
3662
- phase: job.phase
3663
- },
3664
- path: site.path,
3665
- ...owner && { function: owner.id },
3666
- type: site.type,
3667
- range,
3668
- text: site.text ?? sources.text(site.span) ?? "",
3669
- task: site.task,
3670
- operands: site.operands.map((operand) => ({
3671
- text: sources.text(operand.span) ?? "",
3672
- range: sources.range(operand.span) ?? range,
3673
- type: operand.capture.type,
3674
- ...operand.path && { path: operand.path },
3675
- stable: operand.stable
3676
- }))
4555
+ };
4556
+ for (const row of rows) {
4557
+ for (const [item, call] of callIndexes.get(row) ?? []) {
4558
+ const passed = calleeParameters(item);
4559
+ const record = calls[call];
4560
+ if (!passed || !record) {
4561
+ continue;
3677
4562
  }
3678
- ];
3679
- });
3680
- const jobs = instrumentation.jobs.flatMap(({ block, path }, index) => {
3681
- const job = required2(block.job);
3682
- const declaration = sources.range(job.span);
3683
- if (!declaration) {
3684
- return [];
4563
+ const at = row.conditions.statements.get(item)?.position ?? 0;
4564
+ passed.arguments.forEach((argument, index) => {
4565
+ if (argument.kind !== "borrow" || !writesThrough.has(`${passed.routine}#${index}`)) {
4566
+ return;
4567
+ }
4568
+ const target = spell(row, argument.place.root, segments(row, argument.place.path, at));
4569
+ if (!target) {
4570
+ return;
4571
+ }
4572
+ for (const callee of calleeRows(record, row)) {
4573
+ throughParameter(target, callee, index, [call], 0);
4574
+ }
4575
+ });
3685
4576
  }
3686
- const target = instancePath(symbols, path);
3687
- const startedAt = instrumentation.fields.get(block.id)?.startedAt;
3688
- return [
3689
- {
3690
- id: index + 1,
3691
- name: job.name,
3692
- declaration,
3693
- ...job.instance && { instance: job.instance },
3694
- target,
3695
- steps: job.steps.map((step) => ({
3696
- step: step.step,
3697
- kind: step.kind,
3698
- range: sources.range(step.span) ?? declaration,
3699
- text: step.text
3700
- })),
3701
- ...startedAt && { startedAt: `${target}.${startedAt}` },
3702
- requests: requests(context, block.id, target),
3703
- ...generated(job.name) && { generated: true }
4577
+ }
4578
+ const entries = [];
4579
+ const rowTasks = new Map;
4580
+ for (const task of plan.specializedTasks.tasks) {
4581
+ const reached = new Set;
4582
+ const visit = (row) => {
4583
+ if (reached.has(row.index)) {
4584
+ return;
3704
4585
  }
3705
- ];
3706
- });
3707
- const writers = settings?.writers ? instrumentation.analysis.outputs.map((output, index) => ({
3708
- output: output.key,
3709
- target: global(`${instrumentation.slots.writers}[${index}]`),
3710
- sites: required2(instrumentation.analysis.writers[index]).flatMap((site) => {
3711
- const owner = declared(site.routine);
3712
- return owner ? [
3713
- {
3714
- id: site.id,
3715
- range: sources.range(site.span) ?? owner.range,
3716
- function: owner.id
4586
+ reached.add(row.index);
4587
+ const tasks = rowTasks.get(row.index) ?? new Set;
4588
+ tasks.add(task.name);
4589
+ rowTasks.set(row.index, tasks);
4590
+ for (const call of callIndexes.get(row)?.values() ?? []) {
4591
+ const record = calls[call];
4592
+ if (!record) {
4593
+ continue;
3717
4594
  }
3718
- ] : [];
3719
- })
3720
- })) : [];
3721
- const roots = core.variables.filter((variable) => ["module", "instance", "input", "output"].includes(variable.storage)).map((variable) => {
3722
- const declaration = sources.range(variable.span);
3723
- return {
3724
- path: required2(storagePath(variable)),
3725
- target: required2(symbols.references.get(variable.id)),
3726
- type: variable.type,
3727
- ...declaration && { declaration },
3728
- readable: true,
3729
- ...variable.name.startsWith("tsplc") && {
3730
- generated: true
4595
+ const targets = record.receiver.kind === "pattern" ? rows.filter((candidate) => candidate.routine.id === record.callee) : calleeRows(record, row);
4596
+ targets.forEach(visit);
3731
4597
  }
3732
4598
  };
3733
- });
3734
- const types = debugTypes(core.types, symbols.targetTypes, symbols.blocks, (block, variable) => required2(required2(symbols.blockFields.get(block)).get(variable)), (block) => {
3735
- const fields = instrumentation.fields.get(block);
3736
- return ["busy", "step", "startedAt", "job", "sequence"].flatMap((key) => {
3737
- const name = fields?.[key];
3738
- return name ? [{ name, target: name, type: instrumentationFieldTypes[key] }] : [];
4599
+ task.programs.forEach((name) => {
4600
+ const entry = program.programs.find((item) => item.name === name)?.entry;
4601
+ const row = rows.find((candidate) => candidate.routine.id === entry && candidate.instance === null);
4602
+ if (row) {
4603
+ entries.push({
4604
+ routine: row.index,
4605
+ task: task.name,
4606
+ order: entries.filter((item) => item.task === task.name).length
4607
+ });
4608
+ visit(row);
4609
+ }
3739
4610
  });
3740
- }, sources);
3741
- const hardware = debugHardware(project.hardware ?? {
3742
- catalog: { descriptors: [], devices: [] },
3743
- config: { devices: {}, io: options.io },
3744
- tree: false
3745
- }, (key) => ioTarget(key), (id) => Object.fromEntries(Object.entries(instrumentation.devices.get(id) ?? {}).map(([direction, raw]) => [direction, global(raw.field)])));
3746
- const constants = debugConstants(core.folded ?? [], sources);
3747
- return {
3748
- kind: "tsplc-debug",
4611
+ }
4612
+ const flags = new Map;
4613
+ const flag = (path) => {
4614
+ const known = flags.get(path);
4615
+ if (known) {
4616
+ return known;
4617
+ }
4618
+ const created = {
4619
+ path: paths.add(path),
4620
+ input: null,
4621
+ clientWritable: false,
4622
+ hmiControl: null,
4623
+ retained: false,
4624
+ constantTable: false,
4625
+ writerTasks: [],
4626
+ service: null,
4627
+ initial: null,
4628
+ reference: false
4629
+ };
4630
+ flags.set(path, created);
4631
+ return created;
4632
+ };
4633
+ const writtenPaths = new Set(assignments.map((assignment) => paths.items[assignment.writes.path]));
4634
+ for (const variable of program.variables) {
4635
+ const path = variable.storage === "constant" ? `${moduleName(variable)}.${variable.name}` : storagePath(variable);
4636
+ if (path === undefined) {
4637
+ continue;
4638
+ }
4639
+ const published = access(variable) === "readwrite";
4640
+ const constant = variable.storage === "constant";
4641
+ if (published || variable.retain || constant) {
4642
+ const item = flag(path);
4643
+ item.clientWritable = published;
4644
+ item.retained = variable.retain;
4645
+ item.constantTable = constant;
4646
+ }
4647
+ if (variable.initial && (constant || !writtenPaths.has(path))) {
4648
+ flag(path).initial = constantValue(variable.initial);
4649
+ }
4650
+ }
4651
+ manifest.io.forEach((io, index) => {
4652
+ if (io.direction === "input") {
4653
+ flag(io.path).input = index;
4654
+ }
4655
+ });
4656
+ for (const block of program.blocks) {
4657
+ const endpoint = plan.http[block.id];
4658
+ if (!serviceBlock(block) || !endpoint) {
4659
+ continue;
4660
+ }
4661
+ for (const path of instances.get(block.id) ?? []) {
4662
+ const instance = instanceText(path);
4663
+ const owner = jobInstances.map((job, index) => ({ ...job, id: index + 1 })).filter((job) => instance.startsWith(`${job.instance}.`)).sort((a, b) => b.instance.length - a.instance.length)[0];
4664
+ flag(instance).service = {
4665
+ job: owner?.id ?? 0,
4666
+ service: serviceOfPath2(endpoint.path) ?? endpoint.path
4667
+ };
4668
+ }
4669
+ }
4670
+ for (const field of program.references?.fields ?? []) {
4671
+ flag(field).reference = true;
4672
+ }
4673
+ const targets = createPaths(manifest);
4674
+ for (const control of plan.project.hmi?.controls ?? []) {
4675
+ const path = targets.fromTarget(control.target);
4676
+ if (path) {
4677
+ flag(path).hmiControl = control.label;
4678
+ }
4679
+ }
4680
+ const writers = new Map;
4681
+ for (const assignment of assignments) {
4682
+ const path = paths.items[assignment.writes.path];
4683
+ if (path === undefined) {
4684
+ continue;
4685
+ }
4686
+ const tasks = writers.get(path) ?? new Set;
4687
+ for (const task of rowTasks.get(assignment.routine) ?? []) {
4688
+ tasks.add(task);
4689
+ }
4690
+ writers.set(path, tasks);
4691
+ }
4692
+ for (const [path, tasks] of writers) {
4693
+ const readTasks = new Set([...readers.get(path) ?? []].flatMap((row) => [
4694
+ ...rowTasks.get(row) ?? []
4695
+ ]));
4696
+ if (tasks.size > 1 || [...readTasks].some((task) => !tasks.has(task))) {
4697
+ flag(path).writerTasks = [...tasks].sort();
4698
+ }
4699
+ }
4700
+ const file = {
4701
+ kind: "tsplc-explain",
3749
4702
  version: 1,
3750
- build: {
3751
- id: "",
3752
- target: global("buildId"),
3753
- compiler: `@tsplc/compiler ${version}`
3754
- },
3755
- sources: sources.files,
3756
- types,
3757
- roots,
3758
- constants,
3759
- ...hardware,
3760
- functions,
3761
- jobs,
3762
- events,
3763
- writers,
3764
- tasks: deployment.tasks.map((task) => ({
3765
- name: task.name,
3766
- intervalMs: Number(task.intervalNanoseconds) / 1e6,
3767
- priority: task.priority
3768
- })),
3769
- errors: jobErrors2
4703
+ paths: paths.items,
4704
+ texts: texts.items,
4705
+ expressions: expressions.items,
4706
+ conditions: conditionTree.items,
4707
+ sites: sites.items,
4708
+ routines: routineRows.map((routine, index) => {
4709
+ const row = rows[index];
4710
+ const base = row ? loopBases.get(row) ?? 0 : 0;
4711
+ return {
4712
+ ...routine,
4713
+ job: row?.job ?? null,
4714
+ paths: row?.slots.paths.items ?? [],
4715
+ locals: row?.slots.locals.items ?? [],
4716
+ calls: row?.slots.calls.items ?? [],
4717
+ loops: Array.from({ length: row?.conditions.loops.length ?? 0 }, (_, loop) => base + loop)
4718
+ };
4719
+ }),
4720
+ loops,
4721
+ assignments,
4722
+ locals,
4723
+ returns,
4724
+ calls,
4725
+ entries,
4726
+ flags: [...flags.values()],
4727
+ references: Object.fromEntries((program.references?.objects ?? []).map(({ id, path }) => [
4728
+ String(id),
4729
+ paths.add(path)
4730
+ ]))
3770
4731
  };
4732
+ return { file, assignmentsOf: (statement) => recorded.get(statement) ?? [] };
4733
+ }
4734
+ function explainedWriters(manifest, explained, sites) {
4735
+ const explainer = createExplainer(manifest, explained.file);
4736
+ return manifest.writers.map((writer, index) => {
4737
+ const probed = sites[index] ?? [];
4738
+ const exact = explainer.explain(writer.output).writers.every((item) => {
4739
+ const assignment = explained.file.assignments[item.assignment];
4740
+ return assignment !== undefined && (assignment.kind === "assign" || assignment.kind === "call") && !assignment.via.length;
4741
+ });
4742
+ return {
4743
+ ...writer,
4744
+ exact,
4745
+ sites: writer.sites.map((site) => ({
4746
+ ...site,
4747
+ assignments: probed.filter((item) => item.id === site.id).flatMap((item) => [...explained.assignmentsOf(item.statement)]).filter((assignment) => {
4748
+ const written = explained.file.assignments[assignment];
4749
+ return written !== undefined && explainer.explain(writer.output).writers.some((item) => item.assignment === assignment);
4750
+ })
4751
+ }))
4752
+ };
4753
+ });
3771
4754
  }
3772
4755
 
3773
4756
  // packages/compiler/src/codesys/instrumentation.ts
4757
+ import { createHash } from "node:crypto";
4758
+ import { createPaths as createPaths2 } from "@tsplc/debug/paths";
4759
+ import { elementaryType as elementaryType2, integerRange as integerRange3 } from "@tsplc/iec";
4760
+
4761
+ // packages/compiler/src/codesys/expressions.ts
4762
+ var storageName = ({ names }, id) => {
4763
+ const value = names.get(id);
4764
+ if (!value) {
4765
+ throw new Error(`Missing verified storage ${id}.`);
4766
+ }
4767
+ return value;
4768
+ };
4769
+ var placeText = (scope, id, path = []) => {
4770
+ const { typeMap, blocks, blockFields, targetTypes } = scope.symbols;
4771
+ let text = storageName(scope, id);
4772
+ let typeId = required2(scope.types.get(id));
4773
+ let outputBlock;
4774
+ for (const segment of path) {
4775
+ const type = required2(typeMap.get(typeId));
4776
+ if (segment.kind === "field" && type.kind === "block" && segment.name === "out") {
4777
+ outputBlock = type.block;
4778
+ typeId = required2(type.output);
4779
+ continue;
4780
+ }
4781
+ if (segment.kind === "field" && outputBlock) {
4782
+ const output = required2(required2(blocks.get(outputBlock)).outputs.find((field) => field.name === segment.name));
4783
+ text += `.${required2(required2(blockFields.get(outputBlock)).get(output.id))}`;
4784
+ typeId = output.type;
4785
+ outputBlock = undefined;
4786
+ } else if (segment.kind === "field" && type.kind === "record") {
4787
+ text += `.${targetTypes.field(typeId, segment.name)}`;
4788
+ typeId = required2(type.fields.find((field) => field.name === segment.name)).type;
4789
+ } else if (segment.kind === "index" && type.kind === "array") {
4790
+ text += typeMap.get(segment.value.type)?.kind === "enum" ? `[TO_DINT(${expressionText(scope, segment.value)})]` : `[${expressionText(scope, segment.value)}]`;
4791
+ typeId = type.element;
4792
+ } else {
4793
+ throw new Error("Invalid verified place");
4794
+ }
4795
+ }
4796
+ return text;
4797
+ };
4798
+ var expressionText = (scope, value) => {
4799
+ const { typeMap, targetTypes, numeric } = scope.symbols;
4800
+ if (value.kind === "constant") {
4801
+ return targetTypes.literal(value.value, value.type);
4802
+ }
4803
+ if (value.kind === "load") {
4804
+ return placeText(scope, value.root, value.path);
4805
+ }
4806
+ if (value.kind === "borrow") {
4807
+ return placeText(scope, value.place.root, value.place.path);
4808
+ }
4809
+ if (value.kind === "convert" && typeMap.get(value.type)?.kind === "string") {
4810
+ return expressionText(scope, value.operand);
4811
+ }
4812
+ if (value.kind === "unary" || value.kind === "convert") {
4813
+ return numeric.render(value, [expressionText(scope, value.operand)]);
4814
+ }
4815
+ return numeric.render(value, [
4816
+ expressionText(scope, value.left),
4817
+ expressionText(scope, value.right)
4818
+ ]);
4819
+ };
4820
+
4821
+ // packages/compiler/src/codesys/instrumentation.ts
4822
+ var maxWriterPaths = 256;
4823
+ var storageShape = (core) => ({
4824
+ roots: core.variables.flatMap((variable) => {
4825
+ const path = variable.storage === "module" ? storagePath(variable) : undefined;
4826
+ return path ? [{ path, target: "", type: variable.type, readable: true }] : [];
4827
+ }),
4828
+ io: [],
4829
+ constants: [],
4830
+ types: Object.fromEntries(core.types.flatMap((type) => {
4831
+ switch (type.kind) {
4832
+ case "record":
4833
+ return [
4834
+ [
4835
+ type.id,
4836
+ {
4837
+ kind: "record",
4838
+ name: type.id,
4839
+ fields: type.fields.map((field) => ({
4840
+ name: field.name,
4841
+ target: field.name,
4842
+ type: field.type
4843
+ }))
4844
+ }
4845
+ ]
4846
+ ];
4847
+ case "array":
4848
+ return [
4849
+ [
4850
+ type.id,
4851
+ {
4852
+ kind: "array",
4853
+ element: type.element,
4854
+ length: type.length,
4855
+ lower: type.lowerBound
4856
+ }
4857
+ ]
4858
+ ];
4859
+ default:
4860
+ return [];
4861
+ }
4862
+ }))
4863
+ });
4864
+ function writerPaths(core, settings, report) {
4865
+ const writers = settings?.writers;
4866
+ if (typeof writers !== "object") {
4867
+ return [];
4868
+ }
4869
+ const expanded = (() => {
4870
+ try {
4871
+ return createPaths2(storageShape(core)).expand(writers.paths, maxWriterPaths);
4872
+ } catch (error) {
4873
+ if (error instanceof RangeError) {
4874
+ report(`debug.writers.paths match more than ${maxWriterPaths} values.`);
4875
+ return [];
4876
+ }
4877
+ throw error;
4878
+ }
4879
+ })();
4880
+ return expanded.flatMap((path) => {
4881
+ const resolved = resolveStoragePath(core, path);
4882
+ if ("error" in resolved) {
4883
+ report(`debug.writers.paths: ${resolved.error}`);
4884
+ return [];
4885
+ }
4886
+ return [resolved];
4887
+ });
4888
+ }
3774
4889
  function planInstrumentation(plan, symbols) {
3775
4890
  const { core, options } = plan;
3776
4891
  const settings = plan.project.debug;
@@ -3785,6 +4900,11 @@ function planInstrumentation(plan, symbols) {
3785
4900
  return "error" in resolved ? [] : [resolved];
3786
4901
  }) : plan.storageBindings.filter(({ key }) => required2(options.io[key]).address.startsWith("%Q"))).map(({ key, root, segments }) => ({ key, root, segments }))
3787
4902
  ];
4903
+ for (const { key, root, segments } of plan.writerPaths) {
4904
+ if (!outputs.some((output) => output.key === key)) {
4905
+ outputs.push({ key, root, segments });
4906
+ }
4907
+ }
3788
4908
  const analysis = new DebugAnalysis(core, plan.deployment, settings, outputs);
3789
4909
  const global = symbols.names.allocateObject("GVL", "TsplcDebug");
3790
4910
  const names = new Names;
@@ -3832,11 +4952,18 @@ function planInstrumentation(plan, symbols) {
3832
4952
  ])));
3833
4953
  }
3834
4954
  }
4955
+ const scanClocks = new Map(plan.writerPaths.length ? plan.deployment.tasks.flatMap((task) => rings.has(task.name) ? [] : [
4956
+ [
4957
+ task.name,
4958
+ `${global}.${names.allocate(`scanClock_${task.name}`)}`
4959
+ ]
4960
+ ]) : []);
3835
4961
  return {
3836
4962
  analysis,
3837
4963
  global,
3838
4964
  slots,
3839
4965
  rings,
4966
+ scanClocks,
3840
4967
  telemetryNames,
3841
4968
  jobs,
3842
4969
  jobIds,
@@ -3886,6 +5013,9 @@ ${object.implementation ?? ""}
3886
5013
  send.implementation = send.implementation.replace(buildPlaceholder, id);
3887
5014
  }
3888
5015
  const fields = [`buildId : STRING(16) := '${id}'`];
5016
+ for (const target of instrumentation.scanClocks.values()) {
5017
+ fields.push(`${target.slice(instrumentation.global.length + 1)} : DINT`);
5018
+ }
3889
5019
  for (const [task, field] of instrumentation.rings) {
3890
5020
  fields.push(`${field} : ${required2(instrumentation.telemetryNames).writer} := (task := '${task}')`);
3891
5021
  }
@@ -4019,10 +5149,10 @@ function jobTracking(probes, job, fields) {
4019
5149
  import {
4020
5150
  foldConstantRoutines,
4021
5151
  forwardTemporaries,
4022
- instancedBlock as instancedBlock7,
5152
+ instancedBlock as instancedBlock8,
4023
5153
  isVerifiedCore,
4024
5154
  joinPrograms,
4025
- nestedBodies as nestedBodies6,
5155
+ nestedBodies as nestedBodies7,
4026
5156
  shareRoutines,
4027
5157
  statementExpressions as statementExpressions4,
4028
5158
  subexpressions as subexpressions4
@@ -4184,7 +5314,7 @@ function planCodesys(specialized, deployment, value, project = { root: process.c
4184
5314
  };
4185
5315
  const http = new Map;
4186
5316
  for (const block of core.blocks) {
4187
- if (block.runtime?.kind === "http" || block.runtime?.kind === "rpc") {
5317
+ if (serviceBlock(block)) {
4188
5318
  try {
4189
5319
  validateHttpLayout(block, new Map(core.types.map((type) => [type.id, type])));
4190
5320
  http.set(block.id, block.runtime.kind === "rpc" ? {
@@ -4203,6 +5333,7 @@ function planCodesys(specialized, deployment, value, project = { root: process.c
4203
5333
  }
4204
5334
  }
4205
5335
  const storageBindings = validateIo(core, options, report);
5336
+ const writerBindings = writerPaths(core, project.debug, report);
4206
5337
  validateTasks(core, scheduled, report);
4207
5338
  validateStorage(core, options, report);
4208
5339
  validateConstants(core, report);
@@ -4219,11 +5350,15 @@ function planCodesys(specialized, deployment, value, project = { root: process.c
4219
5350
  }
4220
5351
  const plan = Object.freeze({
4221
5352
  core,
4222
- specialized: specialized.functions,
5353
+ specialized,
5354
+ specializedTasks: {
5355
+ tasks: schedulePrograms(specialized, deployment.tasks, () => {})
5356
+ },
4223
5357
  sharedRoutines: routines,
4224
5358
  deployment: structuredClone(scheduled),
4225
5359
  options: structuredClone(options),
4226
5360
  storageBindings,
5361
+ writerPaths: writerBindings,
4227
5362
  publication,
4228
5363
  http: Object.fromEntries(http),
4229
5364
  project,
@@ -4240,8 +5375,10 @@ function planCodesys(specialized, deployment, value, project = { root: process.c
4240
5375
  Object.freeze(value);
4241
5376
  };
4242
5377
  freeze(plan.deployment);
5378
+ freeze(plan.specializedTasks);
4243
5379
  freeze(plan.options);
4244
5380
  freeze(plan.storageBindings);
5381
+ freeze(plan.writerPaths);
4245
5382
  freeze(plan.publication);
4246
5383
  plans.add(plan);
4247
5384
  return { plan, diagnostics: [] };
@@ -4461,7 +5598,7 @@ function validateStorage(core, options, report) {
4461
5598
  const blockHasInOut = (id) => {
4462
5599
  const block = blocks.get(id);
4463
5600
  return block.inputs.some((input) => input.mode === "inOut") || block.state.some((field) => {
4464
- const type = instancedBlock7(field.type, types);
5601
+ const type = instancedBlock8(field.type, types);
4465
5602
  return type !== undefined && blockHasInOut(type.block);
4466
5603
  });
4467
5604
  };
@@ -4472,7 +5609,7 @@ function validateStorage(core, options, report) {
4472
5609
  }
4473
5610
  }
4474
5611
  for (const variable of core.variables) {
4475
- const type = instancedBlock7(variable.type, types);
5612
+ const type = instancedBlock8(variable.type, types);
4476
5613
  if (variable.retain && type && blockHasInOut(type.block)) {
4477
5614
  report("Retained function blocks cannot contain direct or nested InOut references.", variable.span);
4478
5615
  }
@@ -4511,7 +5648,7 @@ function validateConstants(core, report) {
4511
5648
  for (const item of items) {
4512
5649
  statementExpressions4(item).forEach(constantsInExpression);
4513
5650
  if (item.kind !== "switch") {
4514
- nestedBodies6(item).forEach(constantsInBody);
5651
+ nestedBodies7(item).forEach(constantsInBody);
4515
5652
  continue;
4516
5653
  }
4517
5654
  for (const branch of item.cases) {
@@ -4554,8 +5691,10 @@ function emitScanProgram({ plan, symbols, instrumentation }, ioChannels, program
4554
5691
  const call = `${functionNames.get(program.entry)}();`;
4555
5692
  const task = plan.deployment.tasks.find((item) => item.programs[0] === program.name);
4556
5693
  const ring = task && instrumentation.rings.get(task.name);
5694
+ const clock = task && instrumentation.scanClocks.get(task.name);
4557
5695
  const lines = [
4558
5696
  ...ring ? [`${instrumentation.global}.${ring}();`] : [],
5697
+ ...clock ? [`${clock} := TO_DINT(TIME_TO_UDINT(TIME()));`] : [],
4559
5698
  ...channels.filter((channel) => channel.input).map(({ target, wire, inverted }) => `${target} := ${inverted ? "NOT " : ""}${wire};`),
4560
5699
  stateful ? call : `plc_discard := ${call}`,
4561
5700
  ...channels.filter((channel) => !channel.input).map(({ target, wire }) => `${wire} := ${target};`)
@@ -4579,7 +5718,7 @@ END_VAR
4579
5718
  // packages/compiler/src/codesys/routines.ts
4580
5719
  import {
4581
5720
  defaultValue as defaultValue2,
4582
- instancedBlock as instancedBlock8
5721
+ instancedBlock as instancedBlock9
4583
5722
  } from "@tsplc/compiler/ir";
4584
5723
  function routineHeader(symbols, fn, name) {
4585
5724
  if ("inputs" in fn) {
@@ -4704,7 +5843,7 @@ function emitRoutine(context, fn) {
4704
5843
  }
4705
5844
  break;
4706
5845
  case "blockUpdate": {
4707
- const instance = instancedBlock8(required2(storage.types.get(item.instance)), typeMap);
5846
+ const instance = instancedBlock9(required2(storage.types.get(item.instance)), typeMap);
4708
5847
  if (!instance) {
4709
5848
  throw new Error("Invalid verified block receiver");
4710
5849
  }
@@ -4914,7 +6053,7 @@ function emitRoutine(context, fn) {
4914
6053
  line: declaration.length + 1,
4915
6054
  span: item.span
4916
6055
  });
4917
- const initial = item.initial && !instancedBlock8(item.type, typeMap) ? targetTypes.declarationInitializer(item.initial, item.type) : "";
6056
+ const initial = item.initial && !instancedBlock9(item.type, typeMap) ? targetTypes.declarationInitializer(item.initial, item.type) : "";
4918
6057
  declaration.push(` ${storageName(storage, item.id)} : ${targetTypes.name(item.type)}${initial};`);
4919
6058
  }
4920
6059
  declaration.push("END_VAR");
@@ -5162,7 +6301,7 @@ function emitCodesys(plan) {
5162
6301
  }
5163
6302
  const rpcChannels = [...telemetry.rpcChannels];
5164
6303
  for (const fn of routines) {
5165
- if ("inputs" in fn && (fn.runtime?.kind === "http" || fn.runtime?.kind === "rpc")) {
6304
+ if ("inputs" in fn && serviceBlock(fn)) {
5166
6305
  const service = emitServiceBlock(context, network?.name, fn);
5167
6306
  objects.push(...service.objects);
5168
6307
  rpcChannels.push(...service.rpcChannels);
@@ -5175,7 +6314,16 @@ function emitCodesys(plan) {
5175
6314
  for (const program of core.programs) {
5176
6315
  objects.push(emitScanProgram(context, ioList.channels, program));
5177
6316
  }
5178
- const debug = emitDebugGlobal(plan, instrumentation, objects, debugManifest(context, (key) => ioTarget(plan, symbols, key)));
6317
+ const sources = new Sources(plan.project.root);
6318
+ const functionIds = new Map;
6319
+ const manifest = debugManifest(context, (key) => ioTarget(plan, symbols, key), sources, functionIds);
6320
+ const explained = explanations(context, manifest, sources, functionIds);
6321
+ const explain = JSON.stringify(explained.file);
6322
+ const debug = emitDebugGlobal(plan, instrumentation, objects, {
6323
+ ...manifest,
6324
+ writers: explainedWriters(manifest, explained, instrumentation.analysis.writers),
6325
+ explain: { sha256: createHash2("sha256").update(explain).digest("hex") }
6326
+ });
5179
6327
  return {
5180
6328
  artifacts: [
5181
6329
  ...stFiles(plan, symbols, objects, mappings),
@@ -5190,6 +6338,7 @@ function emitCodesys(plan) {
5190
6338
  ioMappings: ioList.ioMappings,
5191
6339
  publication: publishedSymbols(plan, symbols, rpcChannels),
5192
6340
  debug,
6341
+ explain,
5193
6342
  diagnostics: []
5194
6343
  };
5195
6344
  }
@@ -5281,5 +6430,5 @@ export {
5281
6430
  publicationSelectors
5282
6431
  };
5283
6432
 
5284
- //# debugId=9F4012D381E173F564756E2164756E21
6433
+ //# debugId=D655035FED03E81364756E2164756E21
5285
6434
  //# sourceMappingURL=codesys.js.map