@tsplc/compiler 0.2.21 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +280 -223
  3. package/dist/cli.js.map +12 -12
  4. package/dist/codesys.js +452 -330
  5. package/dist/codesys.js.map +24 -24
  6. package/dist/elaborate-capture.js +112 -7
  7. package/dist/elaborate-capture.js.map +5 -4
  8. package/dist/index.js +5682 -5407
  9. package/dist/index.js.map +39 -37
  10. package/dist/ir.js +1154 -327
  11. package/dist/ir.js.map +23 -20
  12. package/dist/project.js +68 -29
  13. package/dist/project.js.map +4 -4
  14. package/dist/retain.js +8 -0
  15. package/dist/retain.js.map +10 -0
  16. package/dist/server-check.js +59 -0
  17. package/dist/server-check.js.map +11 -0
  18. package/dist/telemetry.js +19 -10
  19. package/dist/telemetry.js.map +3 -3
  20. package/package.json +33 -12
  21. package/src/codesys/config.ts +1 -1
  22. package/src/codesys/debug.ts +7 -21
  23. package/src/codesys/engineering.ts +8 -12
  24. package/src/codesys/global-lists.ts +19 -17
  25. package/src/codesys/global-names.ts +3 -3
  26. package/src/codesys/http.ts +37 -34
  27. package/src/codesys/index.ts +5 -22
  28. package/src/codesys/instrumentation.ts +3 -1
  29. package/src/codesys/io-paths.ts +2 -1
  30. package/src/codesys/manifest.ts +35 -18
  31. package/src/codesys/numeric.ts +2 -4
  32. package/src/codesys/plan.ts +94 -26
  33. package/src/codesys/publication.ts +4 -3
  34. package/src/codesys/routines.ts +2 -2
  35. package/src/codesys/sources.ts +1 -0
  36. package/src/codesys/st-files.ts +86 -50
  37. package/src/codesys/storage.ts +44 -9
  38. package/src/codesys/task-access.ts +32 -10
  39. package/src/codesys/telemetry.ts +93 -46
  40. package/src/codesys/types.ts +81 -3
  41. package/src/codesys/vendor.ts +1 -1
  42. package/src/frontend/analyzer.ts +15 -14
  43. package/src/frontend/async.ts +23 -21
  44. package/src/frontend/blocks.ts +7 -6
  45. package/src/frontend/configuration.ts +8 -6
  46. package/src/frontend/const-functions.ts +5 -5
  47. package/src/frontend/cooperative.ts +2 -1
  48. package/src/frontend/coroutines.ts +24 -21
  49. package/src/frontend/elaborate/calls.ts +12 -7
  50. package/src/frontend/elaborate/capture-protocol.ts +103 -0
  51. package/src/frontend/elaborate/capture.ts +48 -19
  52. package/src/frontend/elaborate/dialect.ts +2 -2
  53. package/src/frontend/elaborate/expressions.ts +9 -6
  54. package/src/frontend/elaborate/frame.ts +1 -1
  55. package/src/frontend/elaborate/graph.ts +27 -43
  56. package/src/frontend/elaborate/index.ts +52 -17
  57. package/src/frontend/elaborate/initializers.ts +3 -2
  58. package/src/frontend/elaborate/layouts.ts +2 -2
  59. package/src/frontend/elaborate/model.ts +34 -21
  60. package/src/frontend/elaborate/retention.ts +206 -0
  61. package/src/frontend/elaborate/specialize.ts +7 -6
  62. package/src/frontend/elaborate/statements.ts +47 -38
  63. package/src/frontend/elaborate/storage.ts +26 -6
  64. package/src/frontend/exposure.ts +6 -6
  65. package/src/frontend/expressions.ts +26 -25
  66. package/src/frontend/intrinsics.ts +3 -3
  67. package/src/frontend/module-graph.ts +1 -1
  68. package/src/frontend/positions.ts +2 -1
  69. package/src/frontend/promise-chains.ts +1 -0
  70. package/src/frontend/promises.ts +8 -7
  71. package/src/frontend/routines.ts +3 -2
  72. package/src/frontend/sdk.ts +2 -2
  73. package/src/frontend/services.ts +23 -20
  74. package/src/frontend/statements.ts +8 -6
  75. package/src/frontend/tasks.ts +11 -6
  76. package/src/frontend/telemetry.ts +1 -1
  77. package/src/frontend/types.ts +11 -9
  78. package/src/frontend/typescript.ts +92 -42
  79. package/src/index.ts +2 -1
  80. package/src/ir/aggregates.ts +4 -3
  81. package/src/ir/allocation.ts +2 -1
  82. package/src/ir/core-model.ts +38 -8
  83. package/src/ir/declarations.ts +12 -12
  84. package/src/ir/domains.ts +8 -8
  85. package/src/ir/fold.ts +2 -2
  86. package/src/ir/index.ts +53 -40
  87. package/src/ir/job-errors.ts +22 -11
  88. package/src/ir/layouts.ts +3 -2
  89. package/src/ir/link.ts +6 -24
  90. package/src/ir/model.ts +3 -2
  91. package/src/ir/normalization-error.ts +1 -1
  92. package/src/ir/normalize.ts +19 -12
  93. package/src/ir/numeric.ts +1 -0
  94. package/src/{codesys → ir}/operands.ts +2 -6
  95. package/src/ir/ranges.ts +2 -2
  96. package/src/ir/routine.ts +35 -20
  97. package/src/ir/scalars.ts +3 -3
  98. package/src/ir/share.ts +862 -0
  99. package/src/ir/temporaries.ts +236 -0
  100. package/src/ir/types.ts +1 -1
  101. package/src/project/artifacts.ts +12 -2
  102. package/src/project/cli.ts +42 -44
  103. package/src/project/debugger.ts +15 -9
  104. package/src/project/index.ts +1 -1
  105. package/src/project/plant.ts +34 -23
  106. package/src/project/project-commands.ts +92 -73
  107. package/src/project/project.ts +91 -42
  108. package/src/project/release.ts +50 -57
  109. package/src/project/server-check.ts +54 -0
  110. package/src/project/server.ts +60 -41
  111. package/src/project/terminal.ts +3 -1
  112. package/stdlib/retain.ts +2 -0
  113. package/types/globals.d.ts +1 -0
  114. package/types/retain.d.ts +6 -0
  115. package/types/telemetry.d.ts +2 -2
package/dist/codesys.js CHANGED
@@ -1,7 +1,10 @@
1
+ // packages/compiler/src/codesys/index.ts
2
+ import { engineeringBuildSchema as engineeringBuildSchema2 } from "@tsplc/config/build";
3
+
1
4
  // packages/compiler/src/codesys/config.ts
2
5
  import {
3
- httpOptionsSchema,
4
6
  buildTargetSchema,
7
+ httpOptionsSchema,
5
8
  publicationSchema
6
9
  } from "@tsplc/config";
7
10
  import { directIoBindingSchema } from "@tsplc/config/build";
@@ -10,18 +13,10 @@ import { z as z2 } from "zod";
10
13
  // packages/compiler/src/codesys/engineering.ts
11
14
  import { resolve } from "node:path";
12
15
  import {
13
- buildProject,
14
- configSchema,
15
- resolveConfig
16
+ buildProject
16
17
  } from "@tsplc/build";
18
+ import { engineeringBuildSchema, resolveConfig } from "@tsplc/config/build";
17
19
  import { z } from "zod";
18
- var engineeringBuildSchema = configSchema.omit({
19
- sourceDir: true,
20
- entry: true,
21
- outDir: true,
22
- task: true,
23
- tasks: true
24
- });
25
20
  var engineeringSchema = z.strictObject({
26
21
  kind: z.literal("v3.5"),
27
22
  build: engineeringBuildSchema.optional()
@@ -71,8 +66,8 @@ function codesysBuildConfig(plan, bundle, paths) {
71
66
  tasks
72
67
  }, paths.configFile);
73
68
  }
74
- async function buildCodesys(...arguments_) {
75
- return buildProject(codesysBuildConfig(...arguments_));
69
+ async function buildCodesys(plan, bundle, paths, options = {}) {
70
+ return buildProject(codesysBuildConfig(plan, bundle, paths), options);
76
71
  }
77
72
 
78
73
  // packages/compiler/src/codesys/names.ts
@@ -160,6 +155,11 @@ import {
160
155
  } from "@tsplc/compiler/ir";
161
156
  var moduleFile = (variable) => variable.id.slice(0, variable.id.indexOf(":"));
162
157
  var moduleName = (variable) => basename(moduleFile(variable)).replace(/\.[^.]+$/, "");
158
+ var sectionOrder = [
159
+ "constants",
160
+ "state",
161
+ "retained"
162
+ ];
163
163
  var globalStorage = (variable, retainedVariables) => {
164
164
  if (variable.storage === "constant") {
165
165
  return "constants";
@@ -197,18 +197,33 @@ function storageLayout(core) {
197
197
  continue;
198
198
  }
199
199
  const storage = globalStorage(variable, retainedVariables);
200
- const id = `${moduleFile(variable)}:${storage}`;
201
- let group = groups.get(id);
202
- if (!group) {
203
- group = { id, module: moduleName(variable), storage, variables: [] };
204
- groups.set(id, group);
200
+ const kind = storage === "constants" ? "constants" : "state";
201
+ const id = `${moduleFile(variable)}:${kind}`;
202
+ const group = groups.get(id) ?? {
203
+ id,
204
+ module: moduleName(variable),
205
+ kind,
206
+ sections: []
207
+ };
208
+ groups.set(id, group);
209
+ const section = group.sections.find((item) => item.storage === storage);
210
+ if (section) {
211
+ section.variables.push(variable);
212
+ } else {
213
+ group.sections.push({ storage, variables: [variable] });
205
214
  }
206
- group.variables.push(variable);
207
215
  }
208
216
  return {
209
217
  retainedBlocks,
210
218
  retainedVariables,
211
- globalLists: [...groups.values()]
219
+ globalLists: [...groups.values()].map((group) => {
220
+ const sections = sectionOrder.flatMap((storage) => group.sections.filter((section) => section.storage === storage));
221
+ return {
222
+ ...group,
223
+ sections,
224
+ variables: sections.flatMap((section) => section.variables)
225
+ };
226
+ })
212
227
  };
213
228
  }
214
229
 
@@ -285,7 +300,7 @@ function ioTargets(core) {
285
300
  }
286
301
  }
287
302
  if (type.kind === "array") {
288
- visit(`${key}[` + "${number}" + "]", types.get(type.element));
303
+ visit(`${key}[\${number}]`, types.get(type.element));
289
304
  }
290
305
  };
291
306
  for (const variable of core.variables) {
@@ -312,60 +327,14 @@ import { escapeString } from "@tsplc/iec/st";
312
327
 
313
328
  // packages/compiler/src/codesys/numeric.ts
314
329
  import {
315
- integerRange,
316
330
  floatMaximum,
331
+ integerRange,
317
332
  integerType,
318
- nestedBodies
319
- } from "@tsplc/compiler/ir";
320
-
321
- // packages/compiler/src/codesys/operands.ts
322
- import {
323
- telemetryOperands
333
+ nestedBodies,
334
+ pathIndexes,
335
+ statementExpressions,
336
+ subexpressions
324
337
  } from "@tsplc/compiler/ir";
325
- var pathIndexes = (path = []) => path.flatMap((segment) => segment.kind === "index" ? [segment.value] : []);
326
- var subexpressions = (value) => {
327
- switch (value.kind) {
328
- case "constant":
329
- return [];
330
- case "load":
331
- return pathIndexes(value.path);
332
- case "borrow":
333
- return pathIndexes(value.place.path);
334
- case "unary":
335
- case "convert":
336
- return [value.operand];
337
- case "binary":
338
- return [value.left, value.right];
339
- }
340
- };
341
- var statementExpressions = (item) => {
342
- switch (item.kind) {
343
- case "assign":
344
- return [...pathIndexes(item.path), item.value];
345
- case "if":
346
- return [item.condition];
347
- case "switch":
348
- return [item.value];
349
- case "for":
350
- return item.dynamic ? [item.dynamic.start, item.dynamic.limit] : [];
351
- case "invoke":
352
- return [...item.index ? [item.index] : [], ...item.arguments];
353
- case "blockUpdate":
354
- return [
355
- ...item.index ? [item.index] : [],
356
- ...Object.values(item.inputs)
357
- ];
358
- case "return":
359
- return item.value ? [item.value] : [];
360
- case "telemetry":
361
- return telemetryOperands(item);
362
- case "break":
363
- case "continue":
364
- return [];
365
- }
366
- };
367
-
368
- // packages/compiler/src/codesys/numeric.ts
369
338
  var operatorTokens = {
370
339
  add: "+",
371
340
  subtract: "-",
@@ -667,15 +636,36 @@ var stEscapes = new Map([
667
636
  `, "$N"]
668
637
  ]);
669
638
  var stStringLiteral = (text) => `'${[...text].map((character) => stEscapes.get(character) ?? character).join("")}'`;
639
+ var anonymousRecordId = /:\d+:record(<.*>)?$/;
640
+ var required = (value) => {
641
+ if (value === undefined) {
642
+ throw new Error("Missing verified type name");
643
+ }
644
+ return value;
645
+ };
670
646
 
671
647
  class CodesysTypes {
672
648
  types;
673
649
  objects = [];
674
650
  names = new Map;
675
651
  fields = new Map;
652
+ aliases = new Set;
653
+ shapes = new Map;
676
654
  constructor(types, names, blockNames) {
677
655
  this.types = types;
656
+ const anonymous = new Map;
678
657
  for (const type of types.values()) {
658
+ const shape = this.anonymousShape(type);
659
+ const shared = shape === null ? undefined : anonymous.get(shape);
660
+ if (shared !== undefined) {
661
+ this.names.set(type.id, required(this.names.get(shared)));
662
+ this.fields.set(type.id, required(this.fields.get(shared)));
663
+ this.aliases.add(type.id);
664
+ continue;
665
+ }
666
+ if (shape !== null) {
667
+ anonymous.set(shape, type.id);
668
+ }
679
669
  if (type.kind === "block") {
680
670
  const name = blockNames.get(type.block);
681
671
  if (!name) {
@@ -708,7 +698,7 @@ class CodesysTypes {
708
698
  }
709
699
  const emitted = new Set;
710
700
  const emit = (type) => {
711
- if (instancedBlock2(type.id, types) || !this.names.has(type.id) || emitted.has(type.id)) {
701
+ if (instancedBlock2(type.id, types) || !this.names.has(type.id) || this.aliases.has(type.id) || emitted.has(type.id)) {
712
702
  return;
713
703
  }
714
704
  if (type.kind === "array") {
@@ -728,6 +718,21 @@ class CodesysTypes {
728
718
  emit(type);
729
719
  }
730
720
  }
721
+ anonymousShape(type) {
722
+ if (type.kind !== "record" || !anonymousRecordId.test(type.id)) {
723
+ return null;
724
+ }
725
+ const known = this.shapes.get(type.id);
726
+ if (known !== undefined) {
727
+ return known;
728
+ }
729
+ const shape = JSON.stringify(type.fields.map((field) => [
730
+ field.name,
731
+ this.anonymousShape(this.type(field.type)) ?? field.type
732
+ ]));
733
+ this.shapes.set(type.id, shape);
734
+ return shape;
735
+ }
731
736
  dutDeclaration(type, name) {
732
737
  if (type.kind === "record") {
733
738
  const fields = type.fields.map((field) => ` ${this.field(type.id, field.name)} : ${this.name(field.type)};`).join(`
@@ -785,7 +790,26 @@ END_TYPE
785
790
  if ((type.kind === "record" || type.kind === "array") && this.isZero(value)) {
786
791
  return "";
787
792
  }
788
- return ` := ${this.literal(value, id)}`;
793
+ return ` := ${this.initializer(value, id)}`;
794
+ }
795
+ initializer(value, id) {
796
+ const type = this.type(id);
797
+ if (type.kind === "array" && value.kind === "array") {
798
+ return `[${value.items.map((item) => this.initializer(item, type.element)).join(", ")}]`;
799
+ }
800
+ if (type.kind !== "record" || value.kind !== "record") {
801
+ return this.literal(value, id);
802
+ }
803
+ const fields = type.fields.flatMap((field) => {
804
+ const initial = value.fields[field.name];
805
+ if (!initial) {
806
+ throw new Error("Missing verified record initializer");
807
+ }
808
+ return this.type(field.type).kind !== "enum" && this.isZero(initial) ? [] : [
809
+ `${this.field(id, field.name)} := ${this.initializer(initial, field.type)}`
810
+ ];
811
+ });
812
+ return fields.length ? `(${fields.join(", ")})` : this.literal(value, id);
789
813
  }
790
814
  isZero(value) {
791
815
  if (value.kind === "bool") {
@@ -868,8 +892,8 @@ var planGlobalNames = (core, programNames = {}) => {
868
892
  const { globalLists, retainedVariables } = storageLayout(core);
869
893
  const hasExports = (group) => group.variables.some((variable) => variable.exported && !variable.exposure);
870
894
  const globals = globalLists.map((group) => {
871
- const splitByStorage = globalLists.some((other) => other.module === group.module && other.storage !== group.storage && hasExports(other));
872
- const name = hasExports(group) ? names.allocate(pascalCase(splitByStorage ? `${group.module}-${group.storage}` : group.module)) : names.allocateObject("GVL", `${group.module}_${group.storage}`);
895
+ const splitByStorage = globalLists.some((other) => other.module === group.module && other.kind !== group.kind && hasExports(other));
896
+ const name = hasExports(group) ? names.allocate(pascalCase(splitByStorage ? `${group.module}-${group.kind}` : group.module)) : names.allocateObject("GVL", `${group.module}_${group.kind}`);
873
897
  const fields = new Names;
874
898
  for (const name of blockNames.values()) {
875
899
  fields.reserve(name);
@@ -894,7 +918,9 @@ var planGlobalNames = (core, programNames = {}) => {
894
918
  import {
895
919
  instancedBlock as instancedBlock3,
896
920
  nanosecondsPerMillisecond as nanosecondsPerMillisecond2,
897
- nestedBodies as nestedBodies2
921
+ nestedBodies as nestedBodies2,
922
+ statementExpressions as statementExpressions2,
923
+ subexpressions as subexpressions2
898
924
  } from "@tsplc/compiler/ir";
899
925
  var variablesById = (core) => new Map([
900
926
  ...core.variables,
@@ -996,14 +1022,27 @@ function taskStorageOwnership(core, report) {
996
1022
  }
997
1023
  };
998
1024
  }
1025
+ var buildModuleTables = (core) => ({
1026
+ functions: new Map(core.functions.map((item) => [item.id, item])),
1027
+ blocks: new Map(core.blocks.map((item) => [item.id, item])),
1028
+ types: new Map(core.types.map((item) => [item.id, item])),
1029
+ variables: variablesById(core)
1030
+ });
1031
+ var builtTables = new WeakMap;
1032
+ var moduleTables = (core) => {
1033
+ const known = builtTables.get(core);
1034
+ if (known) {
1035
+ return known;
1036
+ }
1037
+ const tables = buildModuleTables(core);
1038
+ builtTables.set(core, tables);
1039
+ return tables;
1040
+ };
999
1041
  function accessedStorage(fn, core, scheduledHost) {
1000
1042
  const scheduledCall = fn.body.find((item) => item.kind === "invoke" && item.instance === scheduledHost);
1001
1043
  const result = new Set;
1002
1044
  const seen = new Set;
1003
- const functions = new Map(core.functions.map((item) => [item.id, item]));
1004
- const blocks = new Map(core.blocks.map((item) => [item.id, item]));
1005
- const types = new Map(core.types.map((item) => [item.id, item]));
1006
- const variables = variablesById(core);
1045
+ const { functions, blocks, types, variables } = moduleTables(core);
1007
1046
  const expression = (value) => {
1008
1047
  if (value.kind === "load") {
1009
1048
  result.add(value.root);
@@ -1011,7 +1050,7 @@ function accessedStorage(fn, core, scheduledHost) {
1011
1050
  if (value.kind === "borrow") {
1012
1051
  result.add(value.place.root);
1013
1052
  }
1014
- subexpressions(value).forEach(expression);
1053
+ subexpressions2(value).forEach(expression);
1015
1054
  };
1016
1055
  const body = (items) => {
1017
1056
  for (const item of items) {
@@ -1024,7 +1063,7 @@ function accessedStorage(fn, core, scheduledHost) {
1024
1063
  if (item.kind === "blockUpdate") {
1025
1064
  result.add(item.instance);
1026
1065
  }
1027
- statementExpressions(item).forEach(expression);
1066
+ statementExpressions2(item).forEach(expression);
1028
1067
  if (item.kind === "for") {
1029
1068
  result.add(item.counter);
1030
1069
  }
@@ -1101,7 +1140,7 @@ function appendContinuations(core, tasks, report) {
1101
1140
  }
1102
1141
 
1103
1142
  // packages/compiler/src/codesys/symbols.ts
1104
- function required(value) {
1143
+ function required2(value) {
1105
1144
  if (value === undefined) {
1106
1145
  throw new Error("Missing verified CODESYS symbol.");
1107
1146
  }
@@ -1155,7 +1194,7 @@ function allocateBlockFields(symbols, instrumentation, plan, objects) {
1155
1194
  }
1156
1195
  fields.reserve(instrumentation.global);
1157
1196
  for (const objectName of [
1158
- ...core.functions.filter((fn) => !fn.owner).map((fn) => required(functionNames.get(fn.id))),
1197
+ ...core.functions.filter((fn) => !fn.owner).map((fn) => required2(functionNames.get(fn.id))),
1159
1198
  ...blockNames.values()
1160
1199
  ]) {
1161
1200
  fields.reserve(objectName);
@@ -1165,7 +1204,7 @@ function allocateBlockFields(symbols, instrumentation, plan, objects) {
1165
1204
  }
1166
1205
  const native = block.standard && standardBlocks2[block.standard];
1167
1206
  for (const item of [...block.inputs, ...block.outputs, ...block.state]) {
1168
- mapped.set(item.id, native ? required([...native.inputs, ...native.outputs].find(([name]) => name === item.name))[1] : fields.allocate(item.name));
1207
+ mapped.set(item.id, native ? required2([...native.inputs, ...native.outputs].find(([name]) => name === item.name))[1] : fields.allocate(item.name));
1169
1208
  }
1170
1209
  if (block.runtime?.kind === "mailbox") {
1171
1210
  symbols.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
@@ -1211,13 +1250,13 @@ function allocateRoutineScope(symbols, instrumentation, objects, fn) {
1211
1250
  }
1212
1251
  if (owner) {
1213
1252
  for (const item of [...owner.outputs, ...owner.state]) {
1214
- const name = required(required(symbols.blockFields.get(owner.id)).get(item.id));
1253
+ const name = required2(required2(symbols.blockFields.get(owner.id)).get(item.id));
1215
1254
  names.reserve(name);
1216
1255
  references.set(item.id, name);
1217
1256
  }
1218
1257
  }
1219
1258
  for (const item of "parameters" in fn ? fn.parameters : fn.inputs) {
1220
- const name = block ? required(required(symbols.blockFields.get(block.id)).get(item.id)) : names.allocate(item.name);
1259
+ const name = block ? required2(required2(symbols.blockFields.get(block.id)).get(item.id)) : names.allocate(item.name);
1221
1260
  names.reserve(name);
1222
1261
  references.set(item.id, name);
1223
1262
  }
@@ -1251,24 +1290,26 @@ function emitGlobalLists(plan, symbols) {
1251
1290
  const publish = group.variables.some((variable) => published.has(variable.id));
1252
1291
  const lines = [
1253
1292
  ...publish ? ["{attribute 'linkalways'}"] : [],
1254
- "{attribute 'qualified_only'}",
1255
- globalSections[group.storage]
1293
+ "{attribute 'qualified_only'}"
1256
1294
  ];
1257
- for (const item of group.variables) {
1258
- const field = required(fields.get(item.id));
1259
- references.set(item.id, `${name}.${field}`);
1260
- if (published.has(item.id)) {
1261
- lines.push(` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`);
1295
+ for (const section of group.sections) {
1296
+ lines.push(globalSections[section.storage]);
1297
+ for (const item of section.variables) {
1298
+ const field = required2(fields.get(item.id));
1299
+ references.set(item.id, `${name}.${field}`);
1300
+ if (published.has(item.id)) {
1301
+ lines.push(` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`);
1302
+ }
1303
+ mappings.push({
1304
+ path: `${name}.st`,
1305
+ line: lines.length + 1,
1306
+ span: item.span
1307
+ });
1308
+ const initial = globalInitializer(symbols, section.storage, item);
1309
+ lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
1262
1310
  }
1263
- mappings.push({
1264
- path: `${name}.st`,
1265
- line: lines.length + 1,
1266
- span: item.span
1267
- });
1268
- const initial = globalInitializer(symbols, group.storage, item);
1269
- lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
1311
+ lines.push("END_VAR");
1270
1312
  }
1271
- lines.push("END_VAR");
1272
1313
  objects.push({
1273
1314
  id: group.id,
1274
1315
  kind: "globalList",
@@ -1300,7 +1341,7 @@ function emitIoList(plan, symbols) {
1300
1341
  for (const item of core.variables.filter((item) => item.storage === "input" || item.storage === "output")) {
1301
1342
  const field = ioFields.allocate(item.name);
1302
1343
  const initial = item.initial ?? defaultValue(item.type, typeMap);
1303
- const binding = required(options.io[item.name]);
1344
+ const binding = required2(options.io[item.name]);
1304
1345
  references.set(item.id, `${ioName}.${field}`);
1305
1346
  if (binding.mapped) {
1306
1347
  ioMappings.push({
@@ -1329,7 +1370,7 @@ function emitIoList(plan, symbols) {
1329
1370
  ioLines.push(` ${wire} AT ${binding.address} : ${targetTypes.name(item.type)};`, " {attribute 'symbol' := 'read'}", ` ${field} : ${targetTypes.name(item.type)} := ${targetTypes.literal(initial, item.type)};`);
1330
1371
  }
1331
1372
  for (const { key, root, segments, type } of plan.storageBindings) {
1332
- const { address, mapped, inverted } = required(options.io[key]);
1373
+ const { address, mapped, inverted } = required2(options.io[key]);
1333
1374
  const target = bindingTarget(symbols, { root, segments });
1334
1375
  if (mapped) {
1335
1376
  ioMappings.push({ key, address, variable: target });
@@ -1360,13 +1401,13 @@ function emitIoList(plan, symbols) {
1360
1401
  return { objects, mappings, channels, ioMappings };
1361
1402
  }
1362
1403
  function bindingTarget(symbols, { root, segments }) {
1363
- return segments.reduce((path, segment) => segment.kind === "field" ? `${path}.${symbols.targetTypes.field(segment.record, segment.name)}` : `${path}[${segment.value}]`, required(symbols.references.get(root.id)));
1404
+ return segments.reduce((path, segment) => segment.kind === "field" ? `${path}.${symbols.targetTypes.field(segment.record, segment.name)}` : `${path}[${segment.value}]`, required2(symbols.references.get(root.id)));
1364
1405
  }
1365
1406
  function ioTarget({ core }, symbols, key) {
1366
1407
  const logical = core.variables.find((variable) => (variable.storage === "input" || variable.storage === "output") && variable.name === key);
1367
1408
  if (logical) {
1368
1409
  return {
1369
- target: required(symbols.references.get(logical.id)),
1410
+ target: required2(symbols.references.get(logical.id)),
1370
1411
  type: logical.type
1371
1412
  };
1372
1413
  }
@@ -1378,11 +1419,15 @@ function ioTarget({ core }, symbols, key) {
1378
1419
  }
1379
1420
 
1380
1421
  // packages/compiler/src/codesys/http.ts
1422
+ import {
1423
+ httpErrors,
1424
+ jobError
1425
+ } from "@tsplc/compiler/ir";
1381
1426
  import { secretValue } from "@tsplc/config";
1382
1427
  import { elementaryType, integerRange as integerRange2 } from "@tsplc/iec";
1383
1428
  import { plcBufferBytes } from "@tsplc/server/wire";
1384
1429
  var opcuaServiceCapacity = 16;
1385
- var resolveHttpEndpoint = (value, input, env) => {
1430
+ var resolveHttpEndpoint = (value, input, environment) => {
1386
1431
  const url = new URL(value);
1387
1432
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || url.hostname.includes(":")) {
1388
1433
  throw new Error("fetch requires an HTTP(S) URL with an IPv4 address or DNS hostname, without credentials or fragment.");
@@ -1393,8 +1438,8 @@ var resolveHttpEndpoint = (value, input, env) => {
1393
1438
  let token = "";
1394
1439
  const origins = new Set;
1395
1440
  for (const credential of input.credentials) {
1396
- const configured = env[credential.originEnv];
1397
- const secret = env[credential.bearerTokenEnv];
1441
+ const configured = environment[credential.originEnv];
1442
+ const secret = environment[credential.bearerTokenEnv];
1398
1443
  if (!configured || !secret) {
1399
1444
  throw new Error(`HTTP credentials require ${credential.originEnv} and ${credential.bearerTokenEnv}.`);
1400
1445
  }
@@ -1507,7 +1552,7 @@ var serviceCodecs = (block, fields, types, target) => {
1507
1552
  const port = (label) => {
1508
1553
  const variable = [...block.inputs, ...block.outputs].find((v) => v.name === label);
1509
1554
  if (!variable) {
1510
- throw new Error("Missing HTTP port " + label);
1555
+ throw new Error(`Missing HTTP port ${label}`);
1511
1556
  }
1512
1557
  return fields.get(variable.id);
1513
1558
  };
@@ -1530,7 +1575,7 @@ var serviceCodecs = (block, fields, types, target) => {
1530
1575
  const requestCode = requestLayout.fields.map((field, i) => {
1531
1576
  const type = types.get(field.type);
1532
1577
  const value = `${port("request")}.${target.field(request.type, field.name)}`;
1533
- return `Append(${stStringLiteral((i ? "," : "") + '"' + field.name + '":')});${type.kind === "array" ? "Append('[');" : ""}${encode(field.type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
1578
+ return `Append(${stStringLiteral(`${i ? "," : ""}"${field.name}":`)});${type.kind === "array" ? "Append('[');" : ""}${encode(field.type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
1534
1579
  }).join(`
1535
1580
  `);
1536
1581
  const responseCode = responseLayout.fields.map((field, i) => {
@@ -1555,7 +1600,7 @@ WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
1555
1600
  ELSIF payload[cursor-1]<>125 THEN malformed:=TRUE;END_IF;
1556
1601
  END_WHILE;
1557
1602
  SkipWhitespace();
1558
- IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** responseLayout.fields.length - 1} THEN ${port("error")}:=4;END_IF;`;
1603
+ IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** responseLayout.fields.length - 1} THEN ${port("error")}:=${jobError.malformedResponse};END_IF;`;
1559
1604
  return { port, requestCode, decodeResponse, inputs, outputs };
1560
1605
  };
1561
1606
  var opcuaServiceBlock = (block, name, { port, requestCode, decodeResponse, inputs, outputs }, endpoint, rpcGlobal) => {
@@ -1585,16 +1630,16 @@ IF stage=0 THEN
1585
1630
  END_WHILE;
1586
1631
  IF slotIndex>0 THEN EXIT;END_IF;
1587
1632
  END_FOR;
1588
- IF slotIndex=0 THEN ${port("error")}:=7;stage:=90;
1633
+ IF slotIndex=0 THEN ${port("error")}:=${jobError.noRequestSlot};stage:=90;
1589
1634
  ELSE
1590
1635
  ${channel("sequence")}:=${channel("sequence")}+1;
1591
- IF ${channel("sequence")}=0 THEN ${channel("epochs")}:='';${port("error")}:=5;stage:=90;
1636
+ IF ${channel("sequence")}=0 THEN ${channel("epochs")}:='';${port("error")}:=${jobError.network};stage:=90;
1592
1637
  ELSE
1593
1638
  epoch:=${channel("epochs")};identity:=CONCAT(CONCAT(epoch,':'),UDINT_TO_STRING(${channel("sequence")}));
1594
1639
  prefix:=CONCAT(identity,'|');payload:='';malformed:=FALSE;
1595
1640
  Append('{');${requestCode}Append('}');
1596
- IF malformed THEN ${port("error")}:=3;stage:=90;
1597
- ELSIF ByteLength(payload)+LEN(prefix)>${plcBufferBytes} THEN ${port("error")}:=3;stage:=90;
1641
+ IF malformed THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
1642
+ ELSIF ByteLength(payload)+LEN(prefix)>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
1598
1643
  ELSE
1599
1644
  FOR candidate:=0 TO LEN(prefix)-1 DO ${channel("requests")}[candidate]:=prefix[candidate];END_FOR;
1600
1645
  FOR candidate:=0 TO ByteLength(payload)-1 DO ${channel("requests")}[candidate+LEN(prefix)]:=payload[candidate];END_FOR;
@@ -1604,13 +1649,13 @@ IF stage=0 THEN
1604
1649
  END_IF;
1605
1650
  END_IF;
1606
1651
  timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
1607
- IF timeout.Q THEN ${port("error")}:=2;stage:=90;END_IF;
1652
+ IF timeout.Q THEN ${port("error")}:=${jobError.timeout};stage:=90;END_IF;
1608
1653
  IF stage=1 THEN
1609
- IF ${channel("epochs")}<>epoch THEN ${port("error")}:=5;stage:=90;
1654
+ IF ${channel("epochs")}<>epoch THEN ${port("error")}:=${jobError.network};stage:=90;
1610
1655
  ELSIF ${channel("replyIds")}=identity AND_THEN LEFT(${channel("replies")},LEN(prefix))=prefix THEN
1611
1656
  payload:='';cursor:=LEN(prefix);
1612
- IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=4;
1613
- ELSIF ${channel("replies")}[cursor]<>48 OR ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=5;
1657
+ IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=${jobError.malformedResponse};
1658
+ ELSIF ${channel("replies")}[cursor]<>48 OR ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=${jobError.network};
1614
1659
  ELSE
1615
1660
  FOR candidate:=cursor+2 TO ByteLength(${channel("replies")})-1 DO payload[candidate-cursor-2]:=${channel("replies")}[candidate];END_FOR;
1616
1661
  payload[ByteLength(${channel("replies")})-cursor-2]:=0;
@@ -1705,53 +1750,53 @@ IF stage=0 THEN
1705
1750
  payload:=''; malformed:=FALSE; used:=0; received:='';${trace ? `
1706
1751
  ${trace.sequence}:=${trace.sequence}+1;` : ""}
1707
1752
  ${body}
1708
- IF malformed THEN ${port("error")}:=3; stage:=90;
1753
+ IF malformed THEN ${port("error")}:=${jobError.tooLarge}; stage:=90;
1709
1754
  ELSE
1710
1755
  wire:='';wireUsed:=0;
1711
- AppendWire(${stStringLiteral(method + " " + endpoint.path + ` HTTP/1.1\r
1712
- Host: ` + endpoint.authority + `\r
1713
- ` + (endpoint.token ? "Authorization: Bearer " + endpoint.token + `\r
1714
- ` : "") + (json ? `Content-Type: application/json\r
1715
- ` : "") + `Accept: application/json\r
1756
+ AppendWire(${stStringLiteral(`${method} ${endpoint.path} HTTP/1.1\r
1757
+ Host: ${endpoint.authority}\r
1758
+ ${endpoint.token ? `Authorization: Bearer ${endpoint.token}\r
1759
+ ` : ""}${json ? `Content-Type: application/json\r
1760
+ ` : ""}Accept: application/json\r
1716
1761
  Connection: close\r
1717
- ` + (trace ? "x-tsplc-request: " : "Content-Length: "))});${requestHeader}
1762
+ ${trace ? "x-tsplc-request: " : "Content-Length: "}`)});${requestHeader}
1718
1763
  AppendWire(UINT_TO_STRING(ByteLength(payload)));AppendWire('$R$N$R$N');AppendWire(payload); stage:=10;
1719
1764
  END_IF;
1720
1765
  END_IF;
1721
1766
  timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
1722
- IF timeout.Q THEN ${port("error")}:=2; stage:=90; END_IF;
1767
+ IF timeout.Q THEN ${port("error")}:=${jobError.timeout}; stage:=90; END_IF;
1723
1768
  ${port("busy")}:=stage<90;
1724
1769
  IF stage=10 THEN
1725
1770
  resolver(xExecute:=TRUE,sHostname:=${stStringLiteral(endpoint.host)},itfIPAddress:=remoteIP);
1726
- IF resolver.xError THEN ${port("error")}:=5;stage:=90;ELSIF resolver.xDone THEN stage:=1;END_IF;
1771
+ IF resolver.xError THEN ${port("error")}:=${jobError.network};stage:=90;ELSIF resolver.xDone THEN stage:=1;END_IF;
1727
1772
  END_IF;
1728
1773
  IF stage=1 THEN
1729
1774
  client(xEnable:=TRUE);
1730
- IF client.xError THEN ${port("error")}:=${endpoint.tls ? 6 : 5};stage:=90; ELSIF client.xActive THEN stage:=2;END_IF;
1775
+ IF client.xError THEN ${port("error")}:=${endpoint.tls ? jobError.tls : jobError.network};stage:=90; ELSIF client.xActive THEN stage:=2;END_IF;
1731
1776
  END_IF;
1732
1777
  IF stage=2 THEN
1733
1778
  writer(xExecute:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(wire),udiSize:=UINT_TO_UDINT(wireUsed));
1734
- IF writer.xError THEN ${port("error")}:=5;stage:=90;ELSIF writer.xDone THEN stage:=3;END_IF;
1779
+ IF writer.xError THEN ${port("error")}:=${jobError.network};stage:=90;ELSIF writer.xDone THEN stage:=3;END_IF;
1735
1780
  END_IF;
1736
1781
  IF stage=3 THEN
1737
- IF used>=8191 THEN ${port("error")}:=3;stage:=90;
1782
+ IF used>=8191 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
1738
1783
  ELSE
1739
1784
  reader(xEnable:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(chunk),udiSize:=8191);
1740
- IF reader.xError THEN ${port("error")}:=5;stage:=90;
1785
+ IF reader.xError THEN ${port("error")}:=${jobError.network};stage:=90;
1741
1786
  ELSIF reader.xReady AND reader.udiCount>0 THEN
1742
- IF TO_UDINT(used)+reader.udiCount>8191 THEN ${port("error")}:=3;stage:=90;
1787
+ IF TO_UDINT(used)+reader.udiCount>8191 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
1743
1788
  ELSE
1744
1789
  FOR index:=0 TO TO_UINT(reader.udiCount)-1 DO received[used+index]:=chunk[index];END_FOR;
1745
1790
  used:=used+TO_UINT(reader.udiCount);received[used]:=0;
1746
1791
  FindHeaders();
1747
- IF headerEnd=0 AND used>4096 THEN ${port("error")}:=3;stage:=90;END_IF;
1792
+ IF headerEnd=0 AND used>4096 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;END_IF;
1748
1793
  IF headerEnd>0 THEN
1749
- IF headerEnd>4096 THEN ${port("error")}:=3;stage:=90;
1794
+ IF headerEnd>4096 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
1750
1795
  ELSE
1751
1796
  ReadHeaders();
1752
- IF malformed OR contentLength<0 OR contentLength>${plcBufferBytes} THEN ${port("error")}:=3;stage:=90;
1797
+ IF malformed OR contentLength<0 OR contentLength>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
1753
1798
  ELSIF TO_DINT(used)>=TO_DINT(headerEnd)+3+contentLength THEN
1754
- IF status<200 OR status>=300 THEN ${port("error")}:=10000+status;stage:=90;
1799
+ IF status<200 OR status>=300 THEN ${port("error")}:=${httpErrors.base}+status;stage:=90;
1755
1800
  ELSE
1756
1801
  payload:='';IF contentLength>0 THEN FOR index:=0 TO TO_UINT(contentLength)-1 DO payload[index]:=received[headerEnd+3+index]; END_FOR;END_IF;payload[TO_UINT(contentLength)]:=0; ${decode}
1757
1802
  stage:=90;
@@ -1908,11 +1953,11 @@ IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberVal
1908
1953
  function emitServiceBlock({ plan, symbols, instrumentation }, networkName, fn) {
1909
1954
  const objects = [];
1910
1955
  const rpcChannels = [];
1911
- const endpoint = required(plan.http[fn.id]);
1912
- const rpcGlobal = endpoint.transport === "opcua" ? symbols.names.allocateObject("GVL", "TsplcRpc_" + required(symbols.blockNames.get(fn.id))) : undefined;
1956
+ const endpoint = required2(plan.http[fn.id]);
1957
+ const rpcGlobal = endpoint.transport === "opcua" ? symbols.names.allocateObject("GVL", `TsplcRpc_${required2(symbols.blockNames.get(fn.id))}`) : undefined;
1913
1958
  if (rpcGlobal) {
1914
1959
  objects.push({
1915
- id: fn.id + ":rpc",
1960
+ id: `${fn.id}:rpc`,
1916
1961
  kind: "globalList",
1917
1962
  name: rpcGlobal,
1918
1963
  declaration: `{attribute 'qualified_only'}
@@ -1937,10 +1982,10 @@ END_VAR`
1937
1982
  });
1938
1983
  }
1939
1984
  }
1940
- const name = required(symbols.blockNames.get(fn.id));
1941
- const codecs = serviceCodecs(fn, required(symbols.blockFields.get(fn.id)), symbols.typeMap, symbols.targetTypes);
1985
+ const name = required2(symbols.blockNames.get(fn.id));
1986
+ const codecs = serviceCodecs(fn, required2(symbols.blockFields.get(fn.id)), symbols.typeMap, symbols.targetTypes);
1942
1987
  const requestFields = instrumentation.fields.get(fn.id);
1943
- const generated = rpcGlobal ? opcuaServiceBlock(fn, name, codecs, endpoint, rpcGlobal) : httpServiceBlock(fn, name, codecs, endpoint, `${required(networkName)}.network`, requestFields?.job && requestFields.sequence ? { job: requestFields.job, sequence: requestFields.sequence } : undefined);
1988
+ const generated = rpcGlobal ? opcuaServiceBlock(fn, name, codecs, endpoint, rpcGlobal) : httpServiceBlock(fn, name, codecs, endpoint, `${required2(networkName)}.network`, requestFields?.job && requestFields.sequence ? { job: requestFields.job, sequence: requestFields.sequence } : undefined);
1944
1989
  objects.push(generated, ...httpMethods(generated.id, endpoint.transport), ...httpCertificateVerifier(generated.id, generated.name, endpoint));
1945
1990
  return { objects, rpcChannels };
1946
1991
  }
@@ -1966,7 +2011,7 @@ import { createHash } from "node:crypto";
1966
2011
  import { elementaryType as elementaryType2, integerRange as integerRange3 } from "@tsplc/iec";
1967
2012
 
1968
2013
  // packages/compiler/src/codesys/debug.ts
1969
- import { instancedBlock as instancedBlock5, nestedBodies as nestedBodies3 } from "@tsplc/compiler/ir";
2014
+ import { directWrites, instancedBlock as instancedBlock5, nestedBodies as nestedBodies3 } from "@tsplc/compiler/ir";
1970
2015
  var temporary = (id) => id.includes(":temporary:");
1971
2016
  var constantIndex = (value) => value.kind === "constant" && value.value.kind === "integer" ? Number(value.value.value) : undefined;
1972
2017
  var wholeTarget = (item) => {
@@ -2161,31 +2206,15 @@ class DebugAnalysis {
2161
2206
  statementWrites(items) {
2162
2207
  const result = new Set;
2163
2208
  for (const item of items) {
2164
- if (item.kind === "assign") {
2165
- result.add(item.root);
2166
- }
2167
- if (item.kind === "for") {
2168
- result.add(item.counter);
2209
+ for (const root of directWrites(item)) {
2210
+ result.add(root);
2169
2211
  }
2170
2212
  if (item.kind === "invoke") {
2171
- if (item.destination) {
2172
- result.add(item.destination);
2173
- }
2174
- for (const argument of item.arguments) {
2175
- if (argument.kind === "borrow") {
2176
- result.add(argument.place.root);
2177
- }
2178
- }
2179
2213
  for (const root of this.writes(item.function)) {
2180
2214
  result.add(root);
2181
2215
  }
2182
2216
  }
2183
2217
  if (item.kind === "blockUpdate") {
2184
- for (const input of Object.values(item.inputs)) {
2185
- if (input.kind === "borrow") {
2186
- result.add(input.place.root);
2187
- }
2188
- }
2189
2218
  const block = instancedBlock5(this.variables.get(item.instance).type, this.types);
2190
2219
  if (block) {
2191
2220
  for (const root of this.writes(block.block)) {
@@ -2435,23 +2464,23 @@ var storageName = ({ names }, id) => {
2435
2464
  var placeText = (scope, id, path = []) => {
2436
2465
  const { typeMap, blocks, blockFields, targetTypes } = scope.symbols;
2437
2466
  let text = storageName(scope, id);
2438
- let typeId = required(scope.types.get(id));
2467
+ let typeId = required2(scope.types.get(id));
2439
2468
  let outputBlock;
2440
2469
  for (const segment of path) {
2441
- const type = required(typeMap.get(typeId));
2470
+ const type = required2(typeMap.get(typeId));
2442
2471
  if (segment.kind === "field" && type.kind === "block" && segment.name === "out") {
2443
2472
  outputBlock = type.block;
2444
- typeId = required(type.output);
2473
+ typeId = required2(type.output);
2445
2474
  continue;
2446
2475
  }
2447
2476
  if (segment.kind === "field" && outputBlock) {
2448
- const output = required(required(blocks.get(outputBlock)).outputs.find((field) => field.name === segment.name));
2449
- text += `.${required(required(blockFields.get(outputBlock)).get(output.id))}`;
2477
+ const output = required2(required2(blocks.get(outputBlock)).outputs.find((field) => field.name === segment.name));
2478
+ text += `.${required2(required2(blockFields.get(outputBlock)).get(output.id))}`;
2450
2479
  typeId = output.type;
2451
2480
  outputBlock = undefined;
2452
2481
  } else if (segment.kind === "field" && type.kind === "record") {
2453
2482
  text += `.${targetTypes.field(typeId, segment.name)}`;
2454
- typeId = required(type.fields.find((field) => field.name === segment.name)).type;
2483
+ typeId = required2(type.fields.find((field) => field.name === segment.name)).type;
2455
2484
  } else if (segment.kind === "index" && type.kind === "array") {
2456
2485
  text += typeMap.get(segment.value.type)?.kind === "enum" ? `[TO_DINT(${expressionText(scope, segment.value)})]` : `[${expressionText(scope, segment.value)}]`;
2457
2486
  typeId = type.element;
@@ -2490,11 +2519,13 @@ import {
2490
2519
  jobErrors as jobErrors2,
2491
2520
  nanosecondsPerMillisecond as nanosecondsPerMillisecond3,
2492
2521
  nestedBodies as nestedBodies5,
2493
- standardBlocks as standardBlocks3
2522
+ standardBlocks as standardBlocks3,
2523
+ statementExpressions as statementExpressions3,
2524
+ subexpressions as subexpressions3
2494
2525
  } from "@tsplc/compiler/ir";
2495
2526
  import { serviceOfPath } from "@tsplc/server";
2496
2527
  // packages/compiler/package.json
2497
- var version = "0.2.21";
2528
+ var version = "0.4.0";
2498
2529
 
2499
2530
  // packages/compiler/src/codesys/sources.ts
2500
2531
  import { existsSync, readFileSync } from "node:fs";
@@ -2563,13 +2594,11 @@ class Sources {
2563
2594
  // packages/compiler/src/codesys/telemetry.ts
2564
2595
  import {
2565
2596
  errorName,
2566
- httpErrors,
2597
+ httpErrors as httpErrors2,
2567
2598
  jobErrors,
2568
2599
  nestedBodies as nestedBodies4
2569
2600
  } from "@tsplc/compiler/ir";
2570
- import {
2571
- telemetrySchema
2572
- } from "@tsplc/config";
2601
+ import { telemetrySchema } from "@tsplc/config";
2573
2602
  import { plcBufferBytes as plcBufferBytes2 } from "@tsplc/server/wire";
2574
2603
  var telemetryClient = "tsplc:telemetry";
2575
2604
  var telemetryPath = "/tsplc/telemetry";
@@ -2704,6 +2733,7 @@ function planTelemetry(core, deployment, options, project, report) {
2704
2733
  }
2705
2734
  };
2706
2735
  const calls = new Map;
2736
+ const recordIds = new Map;
2707
2737
  for (const { routine, call } of statements) {
2708
2738
  const task = tasks.get(routine);
2709
2739
  if (!task) {
@@ -2715,16 +2745,34 @@ function planTelemetry(core, deployment, options, project, report) {
2715
2745
  const prefix = `${recordHead(record)},"source":${source},"properties":{`;
2716
2746
  const size = prefix.length + call.properties.reduce((total, { name, value, length }, index) => total + (index ? 1 : 0) + asciiJson(name).length + 1 + valueSize(types.get(value.type), length !== undefined), 0) + 1 + (record.kind === "exception" ? codeSize : 0) + commitSize;
2717
2747
  tooLarge(size, "This telemetry record", call.span);
2718
- calls.set(call, { id: calls.size + 1, task, record: prefix, call });
2748
+ const key = JSON.stringify([
2749
+ prefix,
2750
+ record.kind,
2751
+ call.properties.map(({ name }) => name),
2752
+ callParameters(call).map(({ name, value, text }) => [
2753
+ name,
2754
+ value.type,
2755
+ text
2756
+ ])
2757
+ ]);
2758
+ const id = recordIds.get(key) ?? recordIds.size + 1;
2759
+ recordIds.set(key, id);
2760
+ calls.set(call, { id, task, record: prefix, call });
2719
2761
  }
2720
2762
  const failures = new Map;
2763
+ const failureIds = new Map;
2721
2764
  for (const [block, job] of planJobFailures(core, tasks, location)) {
2722
- const record = `{"kind":"exception","handled":false,"function":${asciiJson(job.function)},${job.instance ? `"instance":${asciiJson(job.instance)},` : ""}"properties":{}`;
2723
- tooLarge(record.length + codeSize + ',"source":""'.length + maximum([...job.sources.map(({ source }) => source), job.fallback].map((source) => asciiJson(source).length - 2)) + commitSize, `The failure record of ${job.function}`, job.span);
2765
+ const record = `{"kind":"exception","handled":false,"function":${asciiJson(job.function)},`;
2766
+ const instance = job.instance ? `"instance":${asciiJson(job.instance)},` : null;
2767
+ tooLarge(record.length + (instance?.length ?? 0) + '"properties":{}'.length + codeSize + ',"source":""'.length + maximum([...job.sources.map(({ source }) => source), job.fallback].map((source) => asciiJson(source).length - 2)) + commitSize, `The failure record of ${job.function}`, job.span);
2768
+ const key = JSON.stringify([record, instance !== null, job.sources]);
2769
+ const id = failureIds.get(key) ?? failureIds.size + 1;
2770
+ failureIds.set(key, id);
2724
2771
  failures.set(block, {
2725
- id: failures.size + 1,
2772
+ id,
2726
2773
  task: job.task,
2727
2774
  record,
2775
+ instance,
2728
2776
  sources: job.sources
2729
2777
  });
2730
2778
  }
@@ -2732,7 +2780,7 @@ function planTelemetry(core, deployment, options, project, report) {
2732
2780
  tooLarge(traceRecord(project.trace.operands).size, "A debug.trace record with its operands");
2733
2781
  }
2734
2782
  const server = project.server;
2735
- const base = server?.baseUrlEnv && project.env[server.baseUrlEnv];
2783
+ const base = server?.baseUrlEnv && project.environment[server.baseUrlEnv];
2736
2784
  if (server?.transport === "opcua") {
2737
2785
  report(`Telemetry posts to the app server's ${telemetryPath} over HTTP; set server.transport to "http".`);
2738
2786
  return {};
@@ -2750,7 +2798,7 @@ function planTelemetry(core, deployment, options, project, report) {
2750
2798
  failures,
2751
2799
  ...project.trace && { traceOperands: project.trace.operands }
2752
2800
  },
2753
- endpoint: resolveHttpEndpoint(`${base.replace(/\/+$/, "")}${telemetryPath}`, options.http, project.env)
2801
+ endpoint: resolveHttpEndpoint(`${base.replace(/\/+$/, "")}${telemetryPath}`, options.http, project.environment)
2754
2802
  };
2755
2803
  } catch (cause) {
2756
2804
  report(cause instanceof Error ? cause.message : String(cause));
@@ -2764,6 +2812,15 @@ var callParameters = ({ record, properties }) => [
2764
2812
  ]),
2765
2813
  ...record.kind === "exception" ? [{ name: "code", value: record.code, text: false }] : []
2766
2814
  ];
2815
+ function firstOfEach(sites) {
2816
+ const first = new Map;
2817
+ for (const site of sites) {
2818
+ if (!first.has(site.id)) {
2819
+ first.set(site.id, site);
2820
+ }
2821
+ }
2822
+ return [...first.values()].sort((a, b) => a.id - b.id);
2823
+ }
2767
2824
  var header = (build) => ({
2768
2825
  start: `{"build":${asciiJson(build)},"task":"`,
2769
2826
  rest: [
@@ -2811,7 +2868,7 @@ ${declaration}`,
2811
2868
  }
2812
2869
  return jsonScalar(type, parameter).code;
2813
2870
  };
2814
- const calls = [...plan.calls.values()].map(({ id, record, call }) => {
2871
+ const calls = firstOfEach(plan.calls.values()).map(({ id, record, call }) => {
2815
2872
  const parameters = callParameters(call);
2816
2873
  const inputs = parameters.filter((parameter) => !parameter.text);
2817
2874
  const references = parameters.filter((parameter) => parameter.text);
@@ -2832,7 +2889,7 @@ ${code}`;
2832
2889
  "END_VAR"
2833
2890
  ] : []
2834
2891
  ].map((line) => `${line}
2835
- `).join(""), [
2892
+ `).join(""), `${[
2836
2893
  "payload := '';",
2837
2894
  `Append(${stStringLiteral(record)});`,
2838
2895
  ...properties,
@@ -2844,30 +2901,36 @@ ${code}`;
2844
2901
  ] : [],
2845
2902
  "Commit();"
2846
2903
  ].join(`
2847
- `) + `
2904
+ `)}
2848
2905
  `);
2849
2906
  });
2850
- const failures = [...plan.failures.values()].map(({ id, record, sources }) => method(`Failure${id}`, `VAR_INPUT
2907
+ const failures = firstOfEach(plan.failures.values()).map(({ id, record, sources }) => {
2908
+ const instances = [...plan.failures.values()].flatMap((failure) => failure.id === id && failure.instance !== null ? [failure.instance.length] : []);
2909
+ return method(`Failure${id}`, `VAR_INPUT
2851
2910
  code : UDINT;
2852
2911
  step : UINT;
2853
- END_VAR
2854
- `, [
2855
- "payload := '';",
2856
- `Append(${stStringLiteral(`${record},"code":`)});`,
2857
- "Append(UDINT_TO_STRING(code));",
2858
- "ErrorName(code);",
2859
- `Append(',"source":"');`,
2860
- "CASE step OF",
2861
- ...sources.map(({ source, steps }) => `${steps.join(", ")}: Append(${stStringLiteral(asciiJson(source).slice(1, -1))});`),
2862
- "END_CASE;",
2863
- `Append('"');`,
2864
- "Commit();"
2865
- ].join(`
2866
- `) + `
2867
- `));
2912
+ ${instances.length ? ` instance : STRING(${maximum(instances)});
2913
+ ` : ""}END_VAR
2914
+ `, `${[
2915
+ "payload := '';",
2916
+ `Append(${stStringLiteral(record)});`,
2917
+ ...instances.length ? ["Append(instance);"] : [],
2918
+ `Append(${stStringLiteral('"properties":{},"code":')});`,
2919
+ "Append(UDINT_TO_STRING(code));",
2920
+ "ErrorName(code);",
2921
+ `Append(',"source":"');`,
2922
+ "CASE step OF",
2923
+ ...sources.map(({ source, steps }) => `${steps.join(", ")}: Append(${stStringLiteral(asciiJson(source).slice(1, -1))});`),
2924
+ "END_CASE;",
2925
+ `Append('"');`,
2926
+ "Commit();"
2927
+ ].join(`
2928
+ `)}
2929
+ `);
2930
+ });
2868
2931
  const operands = plan.traceOperands;
2869
2932
  const trace = operands === undefined ? [] : [
2870
- method("Trace", [
2933
+ method("Trace", `${[
2871
2934
  "VAR_INPUT",
2872
2935
  " site : UINT;",
2873
2936
  " value : DINT;",
@@ -2875,8 +2938,8 @@ END_VAR
2875
2938
  ...Array.from({ length: operands }, (_, index) => ` operand${index} : DINT;`),
2876
2939
  "END_VAR"
2877
2940
  ].join(`
2878
- `) + `
2879
- `, [
2941
+ `)}
2942
+ `, `${[
2880
2943
  "payload := '';",
2881
2944
  `Append(${stStringLiteral(traceRecord(operands).prefix)});`,
2882
2945
  "Append(UINT_TO_STRING(site));",
@@ -2887,7 +2950,7 @@ END_VAR
2887
2950
  "Append(']');",
2888
2951
  "Commit();"
2889
2952
  ].join(`
2890
- `) + `
2953
+ `)}
2891
2954
  `)
2892
2955
  ];
2893
2956
  const { start, rest } = header(build);
@@ -2960,10 +3023,10 @@ now := TIME_TO_UDINT(TIME());
2960
3023
  IF sending THEN
2961
3024
  client(start := TRUE, cancel := FALSE, body := batch);
2962
3025
  IF client.done THEN
2963
- IF client.error = ${httpErrors.base + 400} THEN
3026
+ IF client.error = ${httpErrors2.base + 400} THEN
2964
3027
  dropped := dropped + (batched - sent);
2965
3028
  END_IF;
2966
- IF client.error = 0 OR client.error = ${httpErrors.base + 400} THEN
3029
+ IF client.error = 0 OR client.error = ${httpErrors2.base + 400} THEN
2967
3030
  sent := batched;
2968
3031
  END_IF;
2969
3032
  sending := FALSE;
@@ -3030,7 +3093,7 @@ END_VAR
3030
3093
  `, `CASE code OF
3031
3094
  ${errorNames.map(([code, name]) => `${code}: Append(${stStringLiteral(`,"name":${asciiJson(name)}`)});`).join(`
3032
3095
  `)}
3033
- ${httpErrors.base + 1}..${httpErrors.last}: Append(',"name":"HTTP '); Append(UDINT_TO_STRING(code - ${httpErrors.base})); Append('"');
3096
+ ${httpErrors2.base + 1}..${httpErrors2.last}: Append(',"name":"HTTP '); Append(UDINT_TO_STRING(code - ${httpErrors2.base})); Append('"');
3034
3097
  END_CASE;
3035
3098
  `, "PRIVATE "),
3036
3099
  method("WriteText", `VAR_INPUT
@@ -3272,25 +3335,25 @@ function instancePath(symbols, path) {
3272
3335
  let text = "";
3273
3336
  let holder;
3274
3337
  for (const { variable, index } of path) {
3275
- text += holder ? `.${required(required(symbols.blockFields.get(holder)).get(variable.id))}` : required(symbols.references.get(variable.id));
3338
+ text += holder ? `.${required2(required2(symbols.blockFields.get(holder)).get(variable.id))}` : required2(symbols.references.get(variable.id));
3276
3339
  if (index !== undefined) {
3277
3340
  text += `[${index}]`;
3278
3341
  }
3279
- holder = required(instancedBlock6(variable.type, symbols.typeMap)).block;
3342
+ holder = required2(instancedBlock6(variable.type, symbols.typeMap)).block;
3280
3343
  }
3281
3344
  return text;
3282
3345
  }
3283
3346
  function requests(context, id, prefix, job) {
3284
3347
  const { plan, symbols, instrumentation } = context;
3285
- const block = required(symbols.blocks.get(id));
3348
+ const block = required2(symbols.blocks.get(id));
3286
3349
  return block.state.flatMap((child) => {
3287
3350
  const instance = instancedBlock6(child.type, symbols.typeMap);
3288
3351
  if (!instance) {
3289
3352
  return [];
3290
3353
  }
3291
3354
  const caller = instrumentation.jobIds.get(child.id) ?? job;
3292
- const type = required(symbols.typeMap.get(child.type));
3293
- const field = `${prefix}.${required(required(symbols.blockFields.get(id)).get(child.id))}`;
3355
+ const type = required2(symbols.typeMap.get(child.type));
3356
+ const field = `${prefix}.${required2(required2(symbols.blockFields.get(id)).get(child.id))}`;
3294
3357
  const targets = type.kind === "array" ? Array.from({ length: type.length }, (_, index) => `${field}[${type.lowerBound + index}]`) : [field];
3295
3358
  const sequence = instrumentation.fields.get(instance.block)?.sequence;
3296
3359
  const path = plan.http[instance.block]?.path;
@@ -3304,17 +3367,17 @@ function requests(context, id, prefix, job) {
3304
3367
  ] : requests(context, instance.block, target, caller));
3305
3368
  });
3306
3369
  }
3307
- function reads(instrumentation, body, sources) {
3370
+ function reads(variables, body, sources) {
3308
3371
  const reads = new Map;
3309
3372
  const expression = (value) => {
3310
3373
  if (value.kind === "borrow") {
3311
3374
  return;
3312
3375
  }
3313
- subexpressions(value).forEach(expression);
3376
+ subexpressions3(value).forEach(expression);
3314
3377
  if (value.kind !== "load") {
3315
3378
  return;
3316
3379
  }
3317
- const read = storagePath(required(instrumentation.analysis.variables.get(value.root)), value.path);
3380
+ const read = storagePath(required2(variables.get(value.root)), value.path);
3318
3381
  const range = read && sources.range(value.span);
3319
3382
  if (range) {
3320
3383
  reads.set(`${JSON.stringify(range)}${read}`, { range, path: read });
@@ -3322,7 +3385,7 @@ function reads(instrumentation, body, sources) {
3322
3385
  };
3323
3386
  const statements = (items) => {
3324
3387
  for (const item of items) {
3325
- statementExpressions(item).forEach(expression);
3388
+ statementExpressions3(item).forEach(expression);
3326
3389
  nestedBodies5(item).forEach(statements);
3327
3390
  }
3328
3391
  };
@@ -3331,10 +3394,10 @@ function reads(instrumentation, body, sources) {
3331
3394
  }
3332
3395
  var routineTarget = (symbols, routine) => {
3333
3396
  if ("inputs" in routine) {
3334
- return required(symbols.blockNames.get(routine.id));
3397
+ return required2(symbols.blockNames.get(routine.id));
3335
3398
  }
3336
- const name = required(symbols.functionNames.get(routine.id));
3337
- return routine.owner ? `${required(symbols.blockNames.get(routine.owner.block))}.${name}` : name;
3399
+ const name = required2(symbols.functionNames.get(routine.id));
3400
+ return routine.owner ? `${required2(symbols.blockNames.get(routine.owner.block))}.${name}` : name;
3338
3401
  };
3339
3402
  function debugManifest(context, ioTarget) {
3340
3403
  const { plan, symbols, instrumentation } = context;
@@ -3343,8 +3406,13 @@ function debugManifest(context, ioTarget) {
3343
3406
  const sources = new Sources(project.root);
3344
3407
  const global = (field) => `${instrumentation.global}.${field}`;
3345
3408
  const declaredFunctions = new Map;
3409
+ const routines = new Map(core.functions.map((fn) => [fn.id, fn]));
3410
+ const variables = new Map([
3411
+ ...instrumentation.analysis.variables,
3412
+ ...plan.specialized.flatMap((fn) => [...fn.parameters, ...fn.locals].map((variable) => [variable.id, variable]))
3413
+ ]);
3346
3414
  const functions = [
3347
- ...core.functions,
3415
+ ...plan.specialized,
3348
3416
  ...core.blocks.filter((block) => !block.standard && !block.runtime)
3349
3417
  ].flatMap((routine) => {
3350
3418
  const block = "inputs" in routine ? routine : undefined;
@@ -3353,9 +3421,13 @@ function debugManifest(context, ioTarget) {
3353
3421
  if (!declaration) {
3354
3422
  return [];
3355
3423
  }
3424
+ const runs = fn ? routines.get(plan.sharedRoutines.get(fn.id) ?? fn.id) : routine;
3425
+ if (!runs) {
3426
+ return [];
3427
+ }
3356
3428
  const id = declaredFunctions.size;
3357
3429
  declaredFunctions.set(routine.id, { id, range: declaration });
3358
- const task = instrumentation.analysis.tasks.get(routine.id);
3430
+ const task = instrumentation.analysis.tasks.get(runs.id);
3359
3431
  const origin = fn?.origin;
3360
3432
  return [
3361
3433
  {
@@ -3364,8 +3436,8 @@ function debugManifest(context, ioTarget) {
3364
3436
  declaration,
3365
3437
  ...origin?.instance && { instance: origin.instance },
3366
3438
  ...task && { task },
3367
- target: routineTarget(symbols, routine),
3368
- reads: reads(instrumentation, routine.body, sources)
3439
+ target: routineTarget(symbols, runs),
3440
+ reads: reads(variables, routine.body, sources)
3369
3441
  }
3370
3442
  ];
3371
3443
  });
@@ -3402,7 +3474,7 @@ function debugManifest(context, ioTarget) {
3402
3474
  ];
3403
3475
  });
3404
3476
  const jobs = instrumentation.jobs.flatMap(({ block, path }, index) => {
3405
- const job = required(block.job);
3477
+ const job = required2(block.job);
3406
3478
  const declaration = sources.range(job.span);
3407
3479
  if (!declaration) {
3408
3480
  return [];
@@ -3431,7 +3503,7 @@ function debugManifest(context, ioTarget) {
3431
3503
  const writers = settings?.writers ? instrumentation.analysis.outputs.map((output, index) => ({
3432
3504
  output: output.key,
3433
3505
  target: global(`${instrumentation.slots.writers}[${index}]`),
3434
- sites: required(instrumentation.analysis.writers[index]).flatMap((site) => {
3506
+ sites: required2(instrumentation.analysis.writers[index]).flatMap((site) => {
3435
3507
  const owner = declared(site.routine);
3436
3508
  return owner ? [
3437
3509
  {
@@ -3445,8 +3517,8 @@ function debugManifest(context, ioTarget) {
3445
3517
  const roots = core.variables.filter((variable) => ["module", "instance", "input", "output"].includes(variable.storage)).map((variable) => {
3446
3518
  const declaration = sources.range(variable.span);
3447
3519
  return {
3448
- path: required(storagePath(variable)),
3449
- target: required(symbols.references.get(variable.id)),
3520
+ path: required2(storagePath(variable)),
3521
+ target: required2(symbols.references.get(variable.id)),
3450
3522
  type: variable.type,
3451
3523
  ...declaration && { declaration },
3452
3524
  readable: true,
@@ -3455,7 +3527,7 @@ function debugManifest(context, ioTarget) {
3455
3527
  }
3456
3528
  };
3457
3529
  });
3458
- const types = debugTypes(core.types, symbols.targetTypes, symbols.blocks, (block, variable) => required(required(symbols.blockFields.get(block)).get(variable)), (block) => {
3530
+ const types = debugTypes(core.types, symbols.targetTypes, symbols.blocks, (block, variable) => required2(required2(symbols.blockFields.get(block)).get(variable)), (block) => {
3459
3531
  const fields = instrumentation.fields.get(block);
3460
3532
  return ["busy", "step", "startedAt", "job", "sequence"].flatMap((key) => {
3461
3533
  const name = fields?.[key];
@@ -3507,7 +3579,7 @@ function planInstrumentation(plan, symbols) {
3507
3579
  }
3508
3580
  const resolved = resolveStoragePath(core, key);
3509
3581
  return "error" in resolved ? [] : [resolved];
3510
- }) : plan.storageBindings.filter(({ key }) => required(options.io[key]).address.startsWith("%Q"))).map(({ key, root, segments }) => ({ key, root, segments }))
3582
+ }) : plan.storageBindings.filter(({ key }) => required2(options.io[key]).address.startsWith("%Q"))).map(({ key, root, segments }) => ({ key, root, segments }))
3511
3583
  ];
3512
3584
  const analysis = new DebugAnalysis(core, plan.deployment, settings, outputs);
3513
3585
  const global = symbols.names.allocateObject("GVL", "TsplcDebug");
@@ -3579,8 +3651,8 @@ function emitTelemetry(plan, symbols, instrumentation, networkName) {
3579
3651
  plan: telemetry,
3580
3652
  names,
3581
3653
  target: symbols.targetTypes,
3582
- endpoint: required(plan.http[telemetryClient]),
3583
- network: `${required(networkName)}.network`,
3654
+ endpoint: required2(plan.http[telemetryClient]),
3655
+ network: `${required2(networkName)}.network`,
3584
3656
  build: buildPlaceholder,
3585
3657
  types: symbols.typeMap
3586
3658
  });
@@ -3601,7 +3673,7 @@ ${object.implementation ?? ""}
3601
3673
  }
3602
3674
  const fields = [`buildId : STRING(16) := '${id}'`];
3603
3675
  for (const [task, field] of instrumentation.rings) {
3604
- fields.push(`${field} : ${required(instrumentation.telemetryNames).writer} := (task := '${task}')`);
3676
+ fields.push(`${field} : ${required2(instrumentation.telemetryNames).writer} := (task := '${task}')`);
3605
3677
  }
3606
3678
  const settings = plan.project.debug;
3607
3679
  if (settings) {
@@ -3628,10 +3700,10 @@ ${fields.map((field) => ` ${field};
3628
3700
  });
3629
3701
  return { ...manifest, build: { ...manifest.build, id } };
3630
3702
  }
3631
- var ringTarget = ({ global, rings }, task) => `${global}.${required(rings.get(required(task)))}`;
3703
+ var ringTarget = ({ global, rings }, task) => `${global}.${required2(rings.get(required2(task)))}`;
3632
3704
  var [dintMinimum, dintMaximum] = integerRange3(elementaryType2("DINT"));
3633
3705
  var traceOperand = (storage, value) => {
3634
- const type = required(storage.symbols.typeMap.get(value.type));
3706
+ const type = required2(storage.symbols.typeMap.get(value.type));
3635
3707
  const text = expressionText(storage, value);
3636
3708
  if (type.kind === "bool") {
3637
3709
  return `BOOL_TO_DINT(${text})`;
@@ -3651,7 +3723,7 @@ var traceOperand = (storage, value) => {
3651
3723
  return `TO_DINT(MIN(TO_${wide}(${text}), ${wide}#${dintMaximum}))`;
3652
3724
  };
3653
3725
  var traceCall = ({ context, storage, task }, site, value, operands = []) => {
3654
- const captured = Array.from({ length: required(context.plan.telemetry?.traceOperands) }, (_, index) => {
3726
+ const captured = Array.from({ length: required2(context.plan.telemetry?.traceOperands) }, (_, index) => {
3655
3727
  const operand = operands[index];
3656
3728
  return `, operand${index} := ${operand ? traceOperand(storage, operand.capture) : "DINT#0"}`;
3657
3729
  });
@@ -3677,7 +3749,7 @@ function writeProbes(probes, write, item, depth) {
3677
3749
  if (item.kind === "assign") {
3678
3750
  write(`IF ${placeText(storage, item.root, item.path)} <> ${expressionText(storage, probe.value)} THEN`, depth, item.span);
3679
3751
  } else {
3680
- const last = `${instrumentation.global}.${instrumentation.slots.decisions}[${required(probe.slot)}]`;
3752
+ const last = `${instrumentation.global}.${instrumentation.slots.decisions}[${required2(probe.slot)}]`;
3681
3753
  write(`IF ${value} <> ${last} THEN`, depth, item.span);
3682
3754
  write(`${last} := ${value};`, depth + 1, item.span);
3683
3755
  }
@@ -3685,7 +3757,7 @@ function writeProbes(probes, write, item, depth) {
3685
3757
  write("END_IF;", depth, item.span);
3686
3758
  }
3687
3759
  }
3688
- var jobField = (storage, job, name) => storageName(storage, required(job.state.find((item) => item.name === name)).id);
3760
+ var jobField = (storage, job, name) => storageName(storage, required2(job.state.find((item) => item.name === name)).id);
3689
3761
  function jobTracking(probes, job, fields) {
3690
3762
  const { plan, instrumentation } = probes.context;
3691
3763
  const busy = jobField(probes.storage, job, "busy");
@@ -3693,7 +3765,7 @@ function jobTracking(probes, job, fields) {
3693
3765
  const failure = plan.telemetry?.failures.get(job.id);
3694
3766
  const lines = [];
3695
3767
  const line = (text, depth) => lines.push(" ".repeat(depth) + text);
3696
- line(`IF ${busy} = ${required(fields.busy)} THEN`, 0);
3768
+ line(`IF ${busy} = ${required2(fields.busy)} THEN`, 0);
3697
3769
  line("RETURN;", 1);
3698
3770
  line("END_IF;", 0);
3699
3771
  if (fields.startedAt || sites) {
@@ -3713,12 +3785,12 @@ function jobTracking(probes, job, fields) {
3713
3785
  line(`IF ${error} <> 0 THEN`, 1);
3714
3786
  line(traceCall(probes, sites.completion, `-TO_DINT(${error})`), 2);
3715
3787
  line("ELSE", 1);
3716
- line(traceCall(probes, sites.completion, `TO_DINT(${required(fields.step)})`), 2);
3788
+ line(traceCall(probes, sites.completion, `TO_DINT(${required2(fields.step)})`), 2);
3717
3789
  line("END_IF;", 1);
3718
3790
  }
3719
3791
  if (failure) {
3720
3792
  line(`IF ${error} <> 0 AND ${error} <> 1 THEN`, 1);
3721
- line(`${ringTarget(instrumentation, failure.task)}.Failure${failure.id}(code := ${error}, step := ${required(fields.step)});`, 2);
3793
+ line(`${ringTarget(instrumentation, failure.task)}.Failure${failure.id}(code := ${error}, step := ${required2(fields.step)}${failure.instance === null ? "" : `, instance := ${stStringLiteral(failure.instance)}`});`, 2);
3722
3794
  line("END_IF;", 1);
3723
3795
  }
3724
3796
  line("END_IF;", 0);
@@ -3731,14 +3803,22 @@ function jobTracking(probes, job, fields) {
3731
3803
 
3732
3804
  // packages/compiler/src/codesys/plan.ts
3733
3805
  import {
3806
+ foldConstantRoutines,
3807
+ forwardTemporaries,
3734
3808
  instancedBlock as instancedBlock7,
3735
3809
  isVerifiedCore,
3736
- nestedBodies as nestedBodies6
3810
+ joinPrograms,
3811
+ nestedBodies as nestedBodies6,
3812
+ shareRoutines,
3813
+ statementExpressions as statementExpressions4,
3814
+ subexpressions as subexpressions4
3737
3815
  } from "@tsplc/compiler/ir";
3816
+ import { cyclicTasksSchema } from "@tsplc/config/build";
3738
3817
  import { ioScalarBits, sizePrefixes } from "@tsplc/iec";
3739
3818
  import { ioLayout as ioLayout2 } from "@tsplc/typegen/hardware";
3740
3819
 
3741
3820
  // packages/compiler/src/codesys/publication.ts
3821
+ import { emittedFiles } from "@tsplc/config/project-files";
3742
3822
  var globals = (core) => core.variables.filter((variable) => variable.storage === "module" && variable.exported);
3743
3823
  var publicationSelectors = (core) => {
3744
3824
  const variables = globals(core);
@@ -3792,7 +3872,7 @@ var publishedSymbols = (plan, symbols, rpcChannels) => {
3792
3872
  channel.epoch
3793
3873
  ].map((path) => path.replace(/\[\d+\]$/, ""))))
3794
3874
  ];
3795
- const published = (ids) => [...ids, ...logicalIo].map((id) => required(symbols.references.get(id))).concat(rpcSymbols);
3875
+ const published = (ids) => [...ids, ...logicalIo].map((id) => required2(symbols.references.get(id))).concat(rpcSymbols);
3796
3876
  return {
3797
3877
  production: published(plan.publication.production),
3798
3878
  development: published(plan.publication.development)
@@ -3814,7 +3894,7 @@ var machineInterfaces = ({ core }, symbols, rpcChannels) => {
3814
3894
  if (record?.kind !== "record") {
3815
3895
  throw new Error("Invalid exposure record.");
3816
3896
  }
3817
- const root = required(symbols.references.get(variable.id));
3897
+ const root = required2(symbols.references.get(variable.id));
3818
3898
  const fields = Object.fromEntries(record.fields.filter((field) => field.name !== "contractVersion").map((field) => [
3819
3899
  field.name,
3820
3900
  {
@@ -3836,11 +3916,11 @@ var machineInterfaces = ({ core }, symbols, rpcChannels) => {
3836
3916
  return [
3837
3917
  {
3838
3918
  path: "exposures.json",
3839
- content: JSON.stringify(exposures, null, 2) + `
3919
+ content: `${JSON.stringify(exposures, null, 2)}
3840
3920
  `
3841
3921
  },
3842
3922
  {
3843
- path: "machines.ts",
3923
+ path: emittedFiles.machines,
3844
3924
  content: `// Generated explicit read-only machine interfaces. Do not edit.
3845
3925
  export const machines=${JSON.stringify(exposures, null, 2)} as const;
3846
3926
  export const serviceChannels=${JSON.stringify(rpcChannels, null, 2)} as const;
@@ -3850,7 +3930,6 @@ export const serviceChannels=${JSON.stringify(rpcChannels, null, 2)} as const;
3850
3930
  };
3851
3931
 
3852
3932
  // packages/compiler/src/codesys/plan.ts
3853
- import { cyclicTasksSchema } from "@tsplc/config/build";
3854
3933
  var planned = Symbol("CODESYS plan");
3855
3934
  var plans = new WeakSet;
3856
3935
  function diagnostic(message, span) {
@@ -3865,8 +3944,8 @@ function diagnostic(message, span) {
3865
3944
  function isCodesysPlan(plan) {
3866
3945
  return plans.has(plan);
3867
3946
  }
3868
- function planCodesys(core, deployment, value, project = { root: process.cwd() }) {
3869
- if (!isVerifiedCore(core)) {
3947
+ function planCodesys(specialized, deployment, value, project = { root: process.cwd() }) {
3948
+ if (!isVerifiedCore(specialized)) {
3870
3949
  return {
3871
3950
  diagnostics: [
3872
3951
  diagnostic("CODESYS requires a verified, normalized core module.")
@@ -3880,14 +3959,15 @@ function planCodesys(core, deployment, value, project = { root: process.cwd() })
3880
3959
  };
3881
3960
  }
3882
3961
  const options = parsed.data;
3962
+ const environment = project.environment ?? { ...process.env };
3883
3963
  const diagnostics = [];
3884
3964
  const report = (message, span) => {
3885
3965
  diagnostics.push(diagnostic(message, span));
3886
3966
  };
3967
+ const { core, routines } = sharedRoutines(specialized, deployment, project.debug);
3887
3968
  const scheduled = {
3888
3969
  tasks: schedulePrograms(core, deployment.tasks, report)
3889
3970
  };
3890
- const env = project.env ?? process.env;
3891
3971
  const http = new Map;
3892
3972
  for (const block of core.blocks) {
3893
3973
  if (block.runtime?.kind === "http" || block.runtime?.kind === "rpc") {
@@ -3902,7 +3982,7 @@ function planCodesys(core, deployment, value, project = { root: process.cwd() })
3902
3982
  token: "",
3903
3983
  timeoutMs: options.http.timeoutMs,
3904
3984
  tls: false
3905
- } : resolveHttpEndpoint(block.runtime.url, options.http, env));
3985
+ } : resolveHttpEndpoint(block.runtime.url, options.http, environment));
3906
3986
  } catch (cause) {
3907
3987
  report(cause instanceof Error ? cause.message : String(cause), block.span);
3908
3988
  }
@@ -3912,7 +3992,7 @@ function planCodesys(core, deployment, value, project = { root: process.cwd() })
3912
3992
  validateTasks(core, scheduled, report);
3913
3993
  validateStorage(core, options, report);
3914
3994
  validateConstants(core, report);
3915
- const { telemetry, endpoint } = planTelemetry(core, scheduled, options, { ...project, env, trace: project.debug?.trace }, report);
3995
+ const { telemetry, endpoint } = planTelemetry(core, scheduled, options, { ...project, environment, trace: project.debug?.trace }, report);
3916
3996
  if (endpoint) {
3917
3997
  http.set(telemetryClient, endpoint);
3918
3998
  }
@@ -3925,6 +4005,8 @@ function planCodesys(core, deployment, value, project = { root: process.cwd() })
3925
4005
  }
3926
4006
  const plan = Object.freeze({
3927
4007
  core,
4008
+ specialized: specialized.functions,
4009
+ sharedRoutines: routines,
3928
4010
  deployment: structuredClone(scheduled),
3929
4011
  options: structuredClone(options),
3930
4012
  storageBindings,
@@ -3950,6 +4032,32 @@ function planCodesys(core, deployment, value, project = { root: process.cwd() })
3950
4032
  plans.add(plan);
3951
4033
  return { plan, diagnostics: [] };
3952
4034
  }
4035
+ function sharedRoutines(core, deployment, debug) {
4036
+ const unshared = { core, routines: new Map };
4037
+ if (debug) {
4038
+ return unshared;
4039
+ }
4040
+ const issues = [];
4041
+ const scheduled = {
4042
+ tasks: schedulePrograms(core, deployment.tasks, (message) => {
4043
+ issues.push(message);
4044
+ })
4045
+ };
4046
+ if (issues.length) {
4047
+ return unshared;
4048
+ }
4049
+ const continuations = new Set(core.programs.flatMap((program) => program.continuation ? [program.name] : []));
4050
+ const joined = joinPrograms(core, scheduled.tasks.map((task) => task.programs.filter((name) => continuations.has(name))));
4051
+ const folded = foldConstantRoutines(joined.core);
4052
+ const tasks = routineTasks(folded.core, {
4053
+ tasks: schedulePrograms(folded.core, deployment.tasks, () => {})
4054
+ });
4055
+ const shared = shareRoutines(folded.core, (routine) => tasks.get(routine.id));
4056
+ return {
4057
+ core: forwardTemporaries(shared.core),
4058
+ routines: new Map([...joined.routines, ...shared.routines])
4059
+ };
4060
+ }
3953
4061
  function validateIo(core, options, report) {
3954
4062
  const types = new Map(core.types.map((type) => [type.id, type]));
3955
4063
  const targets = [];
@@ -4183,11 +4291,11 @@ function validateConstants(core, report) {
4183
4291
  if (value.kind === "constant") {
4184
4292
  constant(value.value, value.type, value.span);
4185
4293
  }
4186
- subexpressions(value).forEach(constantsInExpression);
4294
+ subexpressions4(value).forEach(constantsInExpression);
4187
4295
  };
4188
4296
  const constantsInBody = (items) => {
4189
4297
  for (const item of items) {
4190
- statementExpressions(item).forEach(constantsInExpression);
4298
+ statementExpressions4(item).forEach(constantsInExpression);
4191
4299
  if (item.kind !== "switch") {
4192
4300
  nestedBodies6(item).forEach(constantsInBody);
4193
4301
  continue;
@@ -4225,7 +4333,7 @@ function emitScanProgram({ plan, symbols, instrumentation }, ioChannels, program
4225
4333
  const { names, functionNames } = symbols;
4226
4334
  const explicit = options.programNames && Object.hasOwn(options.programNames, program.name) ? options.programNames[program.name] : undefined;
4227
4335
  const name = explicit ?? names.allocateObject("PRG", program.name);
4228
- const fn = required(core.functions.find((item) => item.id === program.entry));
4336
+ const fn = required2(core.functions.find((item) => item.id === program.entry));
4229
4337
  const used = accessedStorage(fn, core);
4230
4338
  const channels = ioChannels.filter((channel) => used.has(channel.root));
4231
4339
  const stateful = symbols.programRoutines.has(program.entry);
@@ -4295,17 +4403,17 @@ function emitRoutine(context, fn) {
4295
4403
  const block = "inputs" in fn ? fn : undefined;
4296
4404
  const method = "owner" in fn ? fn.owner : undefined;
4297
4405
  const program = symbols.programRoutines.has(fn.id);
4298
- const owner = method ? required(blocks.get(method.block)) : block;
4299
- const name = block ? required(blockNames.get(block.id)) : required(functionNames.get(fn.id));
4406
+ const owner = method ? required2(blocks.get(method.block)) : block;
4407
+ const name = block ? required2(blockNames.get(block.id)) : required2(functionNames.get(fn.id));
4300
4408
  const inputs = "parameters" in fn ? fn.parameters : fn.inputs;
4301
4409
  const state = owner ? [...owner.outputs, ...owner.state] : [];
4302
4410
  const mappingName = method ? fn.id : name;
4303
- const routineScope = required(symbols.routineScopes.get(fn.id));
4411
+ const routineScope = required2(symbols.routineScopes.get(fn.id));
4304
4412
  const scope = new Map([...references, ...routineScope.references]);
4305
4413
  const locals = routineScope.names;
4306
- const declarations = fn.locals.map((item) => ` ${required(scope.get(item.id))} : ${targetTypes.name(item.type)};`);
4414
+ const declarations = fn.locals.map((item) => ` ${required2(scope.get(item.id))} : ${targetTypes.name(item.type)};`);
4307
4415
  const declarationSpans = fn.locals.map((item) => item.span);
4308
- const mutex = method && owner?.runtime?.kind === "mailbox" ? required(symbols.mailboxLocks.get(owner.id)) : undefined;
4416
+ const mutex = method && owner?.runtime?.kind === "mailbox" ? required2(symbols.mailboxLocks.get(owner.id)) : undefined;
4309
4417
  const acquired = mutex ? locals.allocate("plc_acquired") : undefined;
4310
4418
  const unavailable = mutex && fn.result ? locals.allocate("plc_unavailable") : undefined;
4311
4419
  if (acquired) {
@@ -4346,10 +4454,10 @@ function emitRoutine(context, fn) {
4346
4454
  task: instrumentation.analysis.tasks.get(fn.id)
4347
4455
  };
4348
4456
  const assignConstant = (destination, value, id, depth, span) => {
4349
- const type = required(typeMap.get(id));
4457
+ const type = required2(typeMap.get(id));
4350
4458
  if (type.kind === "record" && value.kind === "record") {
4351
4459
  type.fields.forEach((field) => {
4352
- assignConstant(`${destination}.${targetTypes.field(id, field.name)}`, required(value.fields[field.name]), field.type, depth, span);
4460
+ assignConstant(`${destination}.${targetTypes.field(id, field.name)}`, required2(value.fields[field.name]), field.type, depth, span);
4353
4461
  });
4354
4462
  } else if (type.kind === "array" && value.kind === "array") {
4355
4463
  value.items.forEach((item, index) => {
@@ -4375,14 +4483,14 @@ function emitRoutine(context, fn) {
4375
4483
  }
4376
4484
  break;
4377
4485
  case "blockUpdate": {
4378
- const instance = instancedBlock8(required(storage.types.get(item.instance)), typeMap);
4486
+ const instance = instancedBlock8(required2(storage.types.get(item.instance)), typeMap);
4379
4487
  if (!instance) {
4380
4488
  throw new Error("Invalid verified block receiver");
4381
4489
  }
4382
- const target = required(blocks.get(instance.block));
4490
+ const target = required2(blocks.get(instance.block));
4383
4491
  const arguments_ = Object.entries(item.inputs).map(([input, value]) => {
4384
- const formal = required(target.inputs.find((field) => field.name === input));
4385
- return `${required(required(blockFields.get(target.id)).get(formal.id))} := ${expressionText(storage, value)}`;
4492
+ const formal = required2(target.inputs.find((field) => field.name === input));
4493
+ return `${required2(required2(blockFields.get(target.id)).get(formal.id))} := ${expressionText(storage, value)}`;
4386
4494
  });
4387
4495
  const job = instrumentation.fields.get(target.id)?.job;
4388
4496
  const id = instrumentation.jobIds.get(item.instance);
@@ -4396,21 +4504,21 @@ function emitRoutine(context, fn) {
4396
4504
  }
4397
4505
  case "invoke": {
4398
4506
  const receiver = item.instance ? `${storageName(storage, item.instance)}${item.index ? `[${expressionText(storage, item.index)}]` : ""}.` : "";
4399
- const called = required(core.functions.find((fn) => fn.id === item.function));
4507
+ const called = required2(core.functions.find((fn) => fn.id === item.function));
4400
4508
  const programCall = symbols.programRoutines.has(called.id);
4401
4509
  const arguments_ = item.arguments.map((value, index) => {
4402
4510
  if (!called.owner && !programCall && !called.parameters.some((parameter) => parameter.mode === "inOut")) {
4403
4511
  return expressionText(storage, value);
4404
4512
  }
4405
- const parameter = required(called.parameters[index]);
4406
- const formal = required(required(symbols.routineScopes.get(called.id)).references.get(parameter.id));
4513
+ const parameter = required2(called.parameters[index]);
4514
+ const formal = required2(required2(symbols.routineScopes.get(called.id)).references.get(parameter.id));
4407
4515
  return `${formal} := ${expressionText(storage, value)}`;
4408
4516
  });
4409
- const call = `${receiver}${required(functionNames.get(item.function))}(${arguments_.join(", ")})`;
4517
+ const call = `${receiver}${required2(functionNames.get(item.function))}(${arguments_.join(", ")})`;
4410
4518
  if (programCall) {
4411
4519
  write(`${call};`, depth, item.span);
4412
4520
  if (item.destination) {
4413
- write(`${storageName(storage, item.destination)} := ${required(functionNames.get(called.id))}.${required(symbols.programResults.get(called.id))};`, depth, item.span);
4521
+ write(`${storageName(storage, item.destination)} := ${required2(functionNames.get(called.id))}.${required2(symbols.programResults.get(called.id))};`, depth, item.span);
4414
4522
  }
4415
4523
  break;
4416
4524
  }
@@ -4497,12 +4605,12 @@ function emitRoutine(context, fn) {
4497
4605
  if (item.value) {
4498
4606
  const returned = expressionText(storage, item.value);
4499
4607
  for (const output of block.outputs) {
4500
- write(`${storageName(storage, output.id)} := ${returned}.${targetTypes.field(required(block.result), output.name)};`, depth, item.span);
4608
+ write(`${storageName(storage, output.id)} := ${returned}.${targetTypes.field(required2(block.result), output.name)};`, depth, item.span);
4501
4609
  }
4502
4610
  }
4503
4611
  } else if (program) {
4504
4612
  if (item.value) {
4505
- write(`${required(symbols.programResults.get(fn.id))} := ${expressionText(storage, item.value)};`, depth, item.span);
4613
+ write(`${required2(symbols.programResults.get(fn.id))} := ${expressionText(storage, item.value)};`, depth, item.span);
4506
4614
  }
4507
4615
  } else if (!method || fn.result) {
4508
4616
  write(`${name} := ${item.value ? expressionText(storage, item.value) : "TRUE"};`, depth, item.span);
@@ -4522,7 +4630,7 @@ function emitRoutine(context, fn) {
4522
4630
  write("CONTINUE;", depth, item.span);
4523
4631
  break;
4524
4632
  case "telemetry": {
4525
- const site = required(plan.telemetry?.calls.get(item));
4633
+ const site = required2(plan.telemetry?.calls.get(item));
4526
4634
  const arguments_ = callParameters(item).map(({ name, value }) => `${name} := ${expressionText(storage, value)}`);
4527
4635
  write(`${ringTarget(instrumentation, site.task)}.Record${site.id}(${arguments_.join(", ")});`, depth, item.span);
4528
4636
  break;
@@ -4583,15 +4691,15 @@ function emitRoutine(context, fn) {
4583
4691
  };
4584
4692
  section("VAR_INPUT", inputs.filter((item) => item.mode !== "inOut"));
4585
4693
  section("VAR_IN_OUT", inputs.filter((item) => item.mode === "inOut"));
4586
- if (tracked && tracked.job) {
4694
+ if (tracked?.job) {
4587
4695
  declaration.push("VAR_INPUT", ` ${tracked.job} : ${instrumentationFieldTypes.job};`, "END_VAR");
4588
4696
  }
4589
4697
  if (program && "parameters" in fn && fn.result) {
4590
- declaration.push("VAR_OUTPUT", ` ${required(symbols.programResults.get(fn.id))} : ${targetTypes.name(fn.result)};`, "END_VAR");
4698
+ declaration.push("VAR_OUTPUT", ` ${required2(symbols.programResults.get(fn.id))} : ${targetTypes.name(fn.result)};`, "END_VAR");
4591
4699
  }
4592
4700
  if (block) {
4593
4701
  if (block.runtime?.kind === "mailbox") {
4594
- declaration.push("VAR", ` ${required(symbols.mailboxLocks.get(block.id))} : __XWORD;`, "END_VAR");
4702
+ declaration.push("VAR", ` ${required2(symbols.mailboxLocks.get(block.id))} : __XWORD;`, "END_VAR");
4595
4703
  }
4596
4704
  section("VAR_OUTPUT", block.outputs);
4597
4705
  section("VAR", block.state.filter((item) => !retainedVariables.has(item.id)));
@@ -4643,8 +4751,9 @@ function emitRoutine(context, fn) {
4643
4751
  // packages/compiler/src/codesys/st-files.ts
4644
4752
  var declarationFile = (path, object) => object.implementation === undefined ? `${path}.st` : `${path}/declaration.st`;
4645
4753
  function stFiles(plan, symbols, objects, mappings) {
4754
+ const paths = objectPaths(plan, symbols, objects);
4646
4755
  const placed = objects.map((object) => {
4647
- const path = objectPath(plan, symbols, objects, object);
4756
+ const path = paths(object);
4648
4757
  object.sourcePath = declarationFile(path, object);
4649
4758
  return { object, path };
4650
4759
  });
@@ -4657,17 +4766,36 @@ function stFiles(plan, symbols, objects, mappings) {
4657
4766
  }
4658
4767
  ]
4659
4768
  ]);
4769
+ const owners = firstBy(placed, ({ object }) => mappingKey(object));
4660
4770
  for (const mapping of mappings) {
4661
- const owner = placed.find(({ object }) => {
4662
- const key = mappingKey(object);
4663
- return mapping.path === `${key}.st` || mapping.path.startsWith(`${key}/`);
4664
- });
4771
+ const owner = mappingOwner(owners, mapping.path);
4665
4772
  if (owner) {
4666
4773
  mapping.path = owner.path + mapping.path.slice(mappingKey(owner.object).length);
4667
4774
  }
4668
4775
  }
4669
4776
  return artifacts;
4670
4777
  }
4778
+ var firstBy = (items, key) => {
4779
+ const index = new Map;
4780
+ items.forEach((item, position) => {
4781
+ const name = key(item);
4782
+ if (!index.has(name)) {
4783
+ index.set(name, { item, position });
4784
+ }
4785
+ });
4786
+ return index;
4787
+ };
4788
+ var mappingOwner = (owners, path) => {
4789
+ const candidates = [
4790
+ ...path.endsWith(".st") ? [path.slice(0, -".st".length)] : [],
4791
+ ...[...path.matchAll(/\//g)].map((match) => path.slice(0, match.index))
4792
+ ];
4793
+ const [first] = candidates.flatMap((key) => {
4794
+ const owner = owners.get(key);
4795
+ return owner ? [owner] : [];
4796
+ }).sort((left, right) => left.position - right.position);
4797
+ return first?.item;
4798
+ };
4671
4799
  var mappingKey = (object) => object.kind === "method" ? object.id : object.name;
4672
4800
  var generatedFolder = (object) => {
4673
4801
  if (object.kind === "dataType") {
@@ -4675,37 +4803,47 @@ var generatedFolder = (object) => {
4675
4803
  }
4676
4804
  return object.id === "io" ? "IO" : "_Generated";
4677
4805
  };
4678
- var sourceModule = ({ core }, symbols, object) => {
4679
- const group = symbols.globals.find((item) => item.id === object.id);
4680
- if (group) {
4681
- return group.variables[0]?.id.split(":")[0] ?? "";
4682
- }
4683
- const program = core.programs.find((item) => item.id === object.id);
4684
- return (program ? program.entry : object.id).split(":")[0] ?? "";
4806
+ var sourceModules = ({ core }, symbols) => {
4807
+ const groups = firstBy(symbols.globals, (item) => item.id);
4808
+ const programs = firstBy(core.programs, (item) => item.id);
4809
+ return (object) => {
4810
+ const group = groups.get(object.id)?.item;
4811
+ if (group) {
4812
+ return group.variables[0]?.id.split(":")[0] ?? "";
4813
+ }
4814
+ const program = programs.get(object.id)?.item;
4815
+ return (program ? program.entry : object.id).split(":")[0] ?? "";
4816
+ };
4685
4817
  };
4686
- function objectPath(plan, symbols, objects, object) {
4687
- const { core } = plan;
4688
- if (object.kind === "method" && object.parent) {
4689
- const parent = required(objects.find((candidate) => candidate.id === object.parent));
4690
- return `${objectPath(plan, symbols, objects, parent)}/methods/${object.name}`;
4691
- }
4692
- if (object.kind === "method") {
4693
- const method = required(core.functions.find((fn) => fn.id === object.id));
4694
- const owner = required(objects.find((item) => item.id === method.owner?.block));
4695
- return `${objectPath(plan, symbols, objects, owner)}/methods/${object.name}`;
4696
- }
4697
- const source = sourceModule(plan, symbols, object);
4698
- if (/^[\w./ -]+\.tsx?$/.test(source) && !source.split(/[\\/]/).includes("..") && !source.startsWith("/")) {
4699
- const segments = source.replaceAll("\\", "/").split("/").slice(0, -1);
4700
- if (segments[0] === "src") {
4701
- segments.shift();
4702
- }
4703
- if (object.kind !== "dataType" && segments.at(-1) === object.name) {
4704
- segments.pop();
4818
+ function objectPaths(plan, symbols, objects) {
4819
+ const byId = firstBy(objects, (item) => item.id);
4820
+ const functions = firstBy(plan.core.functions, (fn) => fn.id);
4821
+ const sourceModule = sourceModules(plan, symbols);
4822
+ const objectPath = (object) => {
4823
+ if (object.kind === "method" && object.parent) {
4824
+ const parent = required2(byId.get(object.parent)?.item);
4825
+ return `${objectPath(parent)}/methods/${object.name}`;
4826
+ }
4827
+ if (object.kind === "method") {
4828
+ const method = required2(functions.get(object.id)?.item);
4829
+ const block = method.owner?.block;
4830
+ const owner = required2(block === undefined ? undefined : byId.get(block)?.item);
4831
+ return `${objectPath(owner)}/methods/${object.name}`;
4832
+ }
4833
+ const source = sourceModule(object);
4834
+ if (/^[\w./ -]+\.tsx?$/.test(source) && !source.split(/[\\/]/).includes("..") && !source.startsWith("/")) {
4835
+ const segments = source.replaceAll("\\", "/").split("/").slice(0, -1);
4836
+ if (segments[0] === "src") {
4837
+ segments.shift();
4838
+ }
4839
+ if (object.kind !== "dataType" && segments.at(-1) === object.name) {
4840
+ segments.pop();
4841
+ }
4842
+ return [...segments, object.name].join("/");
4705
4843
  }
4706
- return [...segments, object.name].join("/");
4707
- }
4708
- return `${generatedFolder(object)}/${object.name}`;
4844
+ return `${generatedFolder(object)}/${object.name}`;
4845
+ };
4846
+ return objectPath;
4709
4847
  }
4710
4848
 
4711
4849
  // packages/compiler/src/codesys/emit.ts
@@ -4864,33 +5002,17 @@ function diagnoseCodesys(cause, bundle) {
4864
5002
  ];
4865
5003
  }
4866
5004
  export {
4867
- Sources,
4868
- accessedStorage,
4869
5005
  buildCodesys,
4870
5006
  codesys,
4871
5007
  codesysBuildConfig,
4872
5008
  diagnoseCodesys,
4873
5009
  direct,
4874
5010
  emitCodesys,
4875
- engineeringBuildSchema,
4876
- iecSpelling,
5011
+ engineeringBuildSchema2 as engineeringBuildSchema,
4877
5012
  ioTargets,
4878
- isStoragePath,
4879
- jsonScalar,
4880
5013
  planCodesys,
4881
- planGlobalNames,
4882
- planJobFailures,
4883
- publicationSelectors,
4884
- resolvePublication,
4885
- resolveStoragePath,
4886
- routineTasks,
4887
- schedulePrograms,
4888
- storageLayout,
4889
- taskStorageOwnership,
4890
- telemetryCalls,
4891
- telemetryPath,
4892
- validateHttpLayout
5014
+ publicationSelectors
4893
5015
  };
4894
5016
 
4895
- //# debugId=CC5033E15302A89764756E2164756E21
5017
+ //# debugId=CDE3110BCF012FF964756E2164756E21
4896
5018
  //# sourceMappingURL=codesys.js.map