@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/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "url": "git+https://github.com/rip-technologies/tsplc.git",
18
18
  "directory": "packages/compiler"
19
19
  },
20
- "version": "0.2.21",
20
+ "version": "0.4.0",
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": {
@@ -50,6 +50,11 @@
50
50
  "bun": "./stdlib/telemetry.ts",
51
51
  "default": "./dist/telemetry.js"
52
52
  },
53
+ "./retain": {
54
+ "types": "./types/retain.d.ts",
55
+ "bun": "./stdlib/retain.ts",
56
+ "default": "./dist/retain.js"
57
+ },
53
58
  "./math": {
54
59
  "types": "./stdlib/math.ts",
55
60
  "bun": "./stdlib/math.ts",
@@ -78,8 +83,7 @@
78
83
  "./plc": {
79
84
  "types": "./types/plc.d.ts",
80
85
  "default": "./types/plc.d.ts"
81
- },
82
- "./testing/machine": "./testing/machine.fixtures.ts"
86
+ }
83
87
  },
84
88
  "files": [
85
89
  "dist",
@@ -87,27 +91,44 @@
87
91
  "types",
88
92
  "stdlib",
89
93
  "!**/*.test.ts",
90
- "!**/*.fixtures.ts"
94
+ "!**/*.fixtures.ts",
95
+ "!**/test_*.py",
96
+ "!**/__pycache__/**",
97
+ "!**/*.pyc",
98
+ "!**/tests/**"
91
99
  ],
92
100
  "engines": {
93
101
  "bun": ">=1.4.3"
94
102
  },
95
103
  "dependencies": {
96
- "@tsplc/agent": "0.2.21",
97
- "@tsplc/build": "0.2.21",
98
- "@tsplc/config": "0.2.21",
99
- "@tsplc/debug": "0.2.21",
100
- "@tsplc/opcua": "0.2.21",
101
- "@tsplc/typegen": "0.2.21",
104
+ "@tsplc/agent": "0.4.0",
105
+ "@tsplc/build": "0.4.0",
106
+ "@tsplc/config": "0.4.0",
107
+ "@tsplc/debug": "0.4.0",
108
+ "@tsplc/opcua": "0.4.0",
109
+ "@tsplc/typegen": "0.4.0",
102
110
  "typescript": "6.0.3",
103
111
  "zod": "4.3.6",
104
112
  "@types/bun": "1.4.2",
105
- "@tsplc/server": "0.2.21",
106
- "@tsplc/iec": "0.2.21"
113
+ "@tsplc/server": "0.4.0",
114
+ "@tsplc/iec": "0.4.0"
107
115
  },
108
116
  "bin": {
109
117
  "tsplc": "./dist/cli.js"
110
118
  },
119
+ "buildEntries": {
120
+ "./dist/cli.js": {
121
+ "source": "./src/project/cli.ts"
122
+ },
123
+ "./dist/elaborate-capture.js": {
124
+ "source": "./src/frontend/elaborate/capture.ts",
125
+ "target": "bun"
126
+ },
127
+ "./dist/server-check.js": {
128
+ "source": "./src/project/server-check.ts",
129
+ "target": "bun"
130
+ }
131
+ },
111
132
  "publishConfig": {
112
133
  "access": "public"
113
134
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
- httpOptionsSchema,
3
2
  buildTargetSchema,
3
+ httpOptionsSchema,
4
4
  publicationSchema,
5
5
  type TargetDescriptor,
6
6
  } from "@tsplc/config";
@@ -1,5 +1,4 @@
1
- import { instancedBlock, nestedBodies } from "@tsplc/compiler/ir";
2
- import { routineTasks, variablesById } from "./task-access.ts";
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
3
2
  import type {
4
3
  CoreExpression,
5
4
  CoreFunction,
@@ -12,8 +11,10 @@ import type {
12
11
  Variable,
13
12
  VerifiedCoreModule,
14
13
  } from "@tsplc/compiler/ir";
14
+ import { directWrites, instancedBlock, nestedBodies } from "@tsplc/compiler/ir";
15
15
  import type { ResolvedDebugConfig } from "@tsplc/config";
16
16
  import { moduleName } from "./storage.ts";
17
+ import { routineTasks, variablesById } from "./task-access.ts";
17
18
 
18
19
  type Routine = CoreFunction | CoreFunctionBlock;
19
20
 
@@ -68,7 +69,8 @@ interface Output {
68
69
  key: string;
69
70
  root: Variable;
70
71
  segments: readonly (
71
- { kind: "field"; name: string } | { kind: "index"; value: number }
72
+ | { kind: "field"; name: string }
73
+ | { kind: "index"; value: number }
72
74
  )[];
73
75
  }
74
76
 
@@ -338,31 +340,15 @@ export class DebugAnalysis {
338
340
  private statementWrites(items: readonly CoreStatement[]): Set<string> {
339
341
  const result = new Set<string>();
340
342
  for (const item of items) {
341
- if (item.kind === "assign") {
342
- result.add(item.root);
343
- }
344
- if (item.kind === "for") {
345
- result.add(item.counter);
343
+ for (const root of directWrites(item)) {
344
+ result.add(root);
346
345
  }
347
346
  if (item.kind === "invoke") {
348
- if (item.destination) {
349
- result.add(item.destination);
350
- }
351
- for (const argument of item.arguments) {
352
- if (argument.kind === "borrow") {
353
- result.add(argument.place.root);
354
- }
355
- }
356
347
  for (const root of this.writes(item.function)) {
357
348
  result.add(root);
358
349
  }
359
350
  }
360
351
  if (item.kind === "blockUpdate") {
361
- for (const input of Object.values(item.inputs)) {
362
- if (input.kind === "borrow") {
363
- result.add(input.place.root);
364
- }
365
- }
366
352
  const block = instancedBlock(
367
353
  this.variables.get(item.instance)!.type,
368
354
  this.types,
@@ -1,22 +1,15 @@
1
1
  import { resolve } from "node:path";
2
- import type { EmitResult } from "@tsplc/compiler/ir";
3
2
  import {
4
3
  buildProject,
5
- configSchema,
6
4
  type InstalledLibrary,
7
- resolveConfig,
5
+ type ProgressOptions,
8
6
  } from "@tsplc/build";
7
+ import type { EmitResult } from "@tsplc/compiler/ir";
9
8
  import type { Controller, DeviceTree } from "@tsplc/config";
9
+ import { engineeringBuildSchema, resolveConfig } from "@tsplc/config/build";
10
10
  import { z } from "zod";
11
11
  import type { CodesysPlan } from "./plan.ts";
12
12
 
13
- export const engineeringBuildSchema = configSchema.omit({
14
- sourceDir: true,
15
- entry: true,
16
- outDir: true,
17
- task: true,
18
- tasks: true,
19
- });
20
13
  export const engineeringSchema = z.strictObject({
21
14
  kind: z.literal("v3.5"),
22
15
  build: engineeringBuildSchema.optional(),
@@ -103,7 +96,10 @@ export function codesysBuildConfig(
103
96
  }
104
97
 
105
98
  export async function buildCodesys(
106
- ...arguments_: Parameters<typeof codesysBuildConfig>
99
+ plan: CodesysPlan,
100
+ bundle: Pick<EmitResult, "objects">,
101
+ paths: Parameters<typeof codesysBuildConfig>[2],
102
+ options: ProgressOptions = {},
107
103
  ) {
108
- return buildProject(codesysBuildConfig(...arguments_));
104
+ return buildProject(codesysBuildConfig(plan, bundle, paths), options);
109
105
  }
@@ -11,8 +11,8 @@ import {
11
11
  type StorageBinding,
12
12
  } from "./io-paths.ts";
13
13
  import { Names } from "./names.ts";
14
- import type { GlobalStorage } from "./storage.ts";
15
14
  import type { CodesysPlan } from "./plan.ts";
15
+ import type { GlobalStorage } from "./storage.ts";
16
16
  import { type CodesysSymbols, required } from "./symbols.ts";
17
17
 
18
18
  const globalSections = {
@@ -72,25 +72,27 @@ export function emitGlobalLists(
72
72
  const lines = [
73
73
  ...(publish ? ["{attribute 'linkalways'}"] : []),
74
74
  "{attribute 'qualified_only'}",
75
- globalSections[group.storage],
76
75
  ];
77
- for (const item of group.variables) {
78
- const field = required(fields.get(item.id));
79
- references.set(item.id, `${name}.${field}`);
80
- if (published.has(item.id)) {
81
- lines.push(
82
- ` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`,
83
- );
76
+ for (const section of group.sections) {
77
+ lines.push(globalSections[section.storage]);
78
+ for (const item of section.variables) {
79
+ const field = required(fields.get(item.id));
80
+ references.set(item.id, `${name}.${field}`);
81
+ if (published.has(item.id)) {
82
+ lines.push(
83
+ ` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`,
84
+ );
85
+ }
86
+ mappings.push({
87
+ path: `${name}.st`,
88
+ line: lines.length + 1,
89
+ span: item.span,
90
+ });
91
+ const initial = globalInitializer(symbols, section.storage, item);
92
+ lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
84
93
  }
85
- mappings.push({
86
- path: `${name}.st`,
87
- line: lines.length + 1,
88
- span: item.span,
89
- });
90
- const initial = globalInitializer(symbols, group.storage, item);
91
- lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
94
+ lines.push("END_VAR");
92
95
  }
93
- lines.push("END_VAR");
94
96
  objects.push({
95
97
  id: group.id,
96
98
  kind: "globalList",
@@ -33,17 +33,17 @@ export const planGlobalNames = (
33
33
  const splitByStorage = globalLists.some(
34
34
  (other) =>
35
35
  other.module === group.module &&
36
- other.storage !== group.storage &&
36
+ other.kind !== group.kind &&
37
37
  hasExports(other),
38
38
  );
39
39
  // Exported lists are the program's public interface. Private storage stays generated.
40
40
  const name = hasExports(group)
41
41
  ? names.allocate(
42
42
  pascalCase(
43
- splitByStorage ? `${group.module}-${group.storage}` : group.module,
43
+ splitByStorage ? `${group.module}-${group.kind}` : group.module,
44
44
  ),
45
45
  )
46
- : names.allocateObject("GVL", `${group.module}_${group.storage}`);
46
+ : names.allocateObject("GVL", `${group.module}_${group.kind}`);
47
47
  const fields = new Names();
48
48
  for (const name of blockNames.values()) {
49
49
  fields.reserve(name);
@@ -1,9 +1,12 @@
1
- import type {
2
- CoreFunctionBlock,
3
- GeneratedObject,
4
- PlcType,
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
+ import {
3
+ type CoreFunctionBlock,
4
+ type GeneratedObject,
5
+ httpErrors,
6
+ jobError,
7
+ type PlcType,
5
8
  } from "@tsplc/compiler/ir";
6
- import { type Environment, type HttpOptions, secretValue } from "@tsplc/config";
9
+ import { type HttpOptions, secretValue } from "@tsplc/config";
7
10
  import { elementaryType, integerRange } from "@tsplc/iec";
8
11
  import { plcBufferBytes } from "@tsplc/server/wire";
9
12
  import type { CodesysPlan } from "./plan.ts";
@@ -30,7 +33,7 @@ export interface HttpEndpoint {
30
33
  export const resolveHttpEndpoint = (
31
34
  value: string,
32
35
  input: HttpOptions,
33
- env: Environment,
36
+ environment: Readonly<Record<string, string | undefined>>,
34
37
  ): HttpEndpoint => {
35
38
  const url = new URL(value);
36
39
  if (
@@ -56,8 +59,8 @@ export const resolveHttpEndpoint = (
56
59
  let token = "";
57
60
  const origins = new Set<string>();
58
61
  for (const credential of input.credentials) {
59
- const configured = env[credential.originEnv];
60
- const secret = env[credential.bearerTokenEnv];
62
+ const configured = environment[credential.originEnv];
63
+ const secret = environment[credential.bearerTokenEnv];
61
64
  if (!configured || !secret) {
62
65
  throw new Error(
63
66
  `HTTP credentials require ${credential.originEnv} and ${credential.bearerTokenEnv}.`,
@@ -264,7 +267,7 @@ const serviceCodecs = (
264
267
  (v) => v.name === label,
265
268
  );
266
269
  if (!variable) {
267
- throw new Error("Missing HTTP port " + label);
270
+ throw new Error(`Missing HTTP port ${label}`);
268
271
  }
269
272
  return fields.get(variable.id)!;
270
273
  };
@@ -296,7 +299,7 @@ const serviceCodecs = (
296
299
  .map((field, i) => {
297
300
  const type = types.get(field.type)!;
298
301
  const value = `${port("request")}.${target.field(request.type, field.name)}`;
299
- return `Append(${stStringLiteral((i ? "," : "") + '"' + field.name + '":')});${type.kind === "array" ? "Append('[');" : ""}${encode(field.type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
302
+ return `Append(${stStringLiteral(`${i ? "," : ""}"${field.name}":`)});${type.kind === "array" ? "Append('[');" : ""}${encode(field.type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
300
303
  })
301
304
  .join("\n");
302
305
  const responseCode = responseLayout.fields
@@ -324,7 +327,7 @@ WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
324
327
  ELSIF payload[cursor-1]<>125 THEN malformed:=TRUE;END_IF;
325
328
  END_WHILE;
326
329
  SkipWhitespace();
327
- IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** responseLayout.fields.length - 1} THEN ${port("error")}:=4;END_IF;`;
330
+ IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** responseLayout.fields.length - 1} THEN ${port("error")}:=${jobError.malformedResponse};END_IF;`;
328
331
  return { port, requestCode, decodeResponse, inputs, outputs };
329
332
  };
330
333
 
@@ -363,16 +366,16 @@ IF stage=0 THEN
363
366
  END_WHILE;
364
367
  IF slotIndex>0 THEN EXIT;END_IF;
365
368
  END_FOR;
366
- IF slotIndex=0 THEN ${port("error")}:=7;stage:=90;
369
+ IF slotIndex=0 THEN ${port("error")}:=${jobError.noRequestSlot};stage:=90;
367
370
  ELSE
368
371
  ${channel("sequence")}:=${channel("sequence")}+1;
369
- IF ${channel("sequence")}=0 THEN ${channel("epochs")}:='';${port("error")}:=5;stage:=90;
372
+ IF ${channel("sequence")}=0 THEN ${channel("epochs")}:='';${port("error")}:=${jobError.network};stage:=90;
370
373
  ELSE
371
374
  epoch:=${channel("epochs")};identity:=CONCAT(CONCAT(epoch,':'),UDINT_TO_STRING(${channel("sequence")}));
372
375
  prefix:=CONCAT(identity,'|');payload:='';malformed:=FALSE;
373
376
  Append('{');${requestCode}Append('}');
374
- IF malformed THEN ${port("error")}:=3;stage:=90;
375
- ELSIF ByteLength(payload)+LEN(prefix)>${plcBufferBytes} THEN ${port("error")}:=3;stage:=90;
377
+ IF malformed THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
378
+ ELSIF ByteLength(payload)+LEN(prefix)>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
376
379
  ELSE
377
380
  FOR candidate:=0 TO LEN(prefix)-1 DO ${channel("requests")}[candidate]:=prefix[candidate];END_FOR;
378
381
  FOR candidate:=0 TO ByteLength(payload)-1 DO ${channel("requests")}[candidate+LEN(prefix)]:=payload[candidate];END_FOR;
@@ -382,13 +385,13 @@ IF stage=0 THEN
382
385
  END_IF;
383
386
  END_IF;
384
387
  timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
385
- IF timeout.Q THEN ${port("error")}:=2;stage:=90;END_IF;
388
+ IF timeout.Q THEN ${port("error")}:=${jobError.timeout};stage:=90;END_IF;
386
389
  IF stage=1 THEN
387
- IF ${channel("epochs")}<>epoch THEN ${port("error")}:=5;stage:=90;
390
+ IF ${channel("epochs")}<>epoch THEN ${port("error")}:=${jobError.network};stage:=90;
388
391
  ELSIF ${channel("replyIds")}=identity AND_THEN LEFT(${channel("replies")},LEN(prefix))=prefix THEN
389
392
  payload:='';cursor:=LEN(prefix);
390
- IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=4;
391
- ELSIF ${channel("replies")}[cursor]<>48 OR ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=5;
393
+ IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=${jobError.malformedResponse};
394
+ ELSIF ${channel("replies")}[cursor]<>48 OR ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=${jobError.network};
392
395
  ELSE
393
396
  FOR candidate:=cursor+2 TO ByteLength(${channel("replies")})-1 DO payload[candidate-cursor-2]:=${channel("replies")}[candidate];END_FOR;
394
397
  payload[ByteLength(${channel("replies")})-cursor-2]:=0;
@@ -517,47 +520,47 @@ END_IF;
517
520
  IF stage=0 THEN
518
521
  payload:=''; malformed:=FALSE; used:=0; received:='';${trace ? `\n ${trace.sequence}:=${trace.sequence}+1;` : ""}
519
522
  ${body}
520
- IF malformed THEN ${port("error")}:=3; stage:=90;
523
+ IF malformed THEN ${port("error")}:=${jobError.tooLarge}; stage:=90;
521
524
  ELSE
522
525
  wire:='';wireUsed:=0;
523
- AppendWire(${stStringLiteral(method + " " + endpoint.path + " HTTP/1.1\r\nHost: " + endpoint.authority + "\r\n" + (endpoint.token ? "Authorization: Bearer " + endpoint.token + "\r\n" : "") + (json ? "Content-Type: application/json\r\n" : "") + "Accept: application/json\r\nConnection: close\r\n" + (trace ? "x-tsplc-request: " : "Content-Length: "))});${requestHeader}
526
+ AppendWire(${stStringLiteral(`${method} ${endpoint.path} HTTP/1.1\r\nHost: ${endpoint.authority}\r\n${endpoint.token ? `Authorization: Bearer ${endpoint.token}\r\n` : ""}${json ? "Content-Type: application/json\r\n" : ""}Accept: application/json\r\nConnection: close\r\n${trace ? "x-tsplc-request: " : "Content-Length: "}`)});${requestHeader}
524
527
  AppendWire(UINT_TO_STRING(ByteLength(payload)));AppendWire('$R$N$R$N');AppendWire(payload); stage:=10;
525
528
  END_IF;
526
529
  END_IF;
527
530
  timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
528
- IF timeout.Q THEN ${port("error")}:=2; stage:=90; END_IF;
531
+ IF timeout.Q THEN ${port("error")}:=${jobError.timeout}; stage:=90; END_IF;
529
532
  ${port("busy")}:=stage<90;
530
533
  IF stage=10 THEN
531
534
  resolver(xExecute:=TRUE,sHostname:=${stStringLiteral(endpoint.host)},itfIPAddress:=remoteIP);
532
- IF resolver.xError THEN ${port("error")}:=5;stage:=90;ELSIF resolver.xDone THEN stage:=1;END_IF;
535
+ IF resolver.xError THEN ${port("error")}:=${jobError.network};stage:=90;ELSIF resolver.xDone THEN stage:=1;END_IF;
533
536
  END_IF;
534
537
  IF stage=1 THEN
535
538
  client(xEnable:=TRUE);
536
- IF client.xError THEN ${port("error")}:=${endpoint.tls ? 6 : 5};stage:=90; ELSIF client.xActive THEN stage:=2;END_IF;
539
+ IF client.xError THEN ${port("error")}:=${endpoint.tls ? jobError.tls : jobError.network};stage:=90; ELSIF client.xActive THEN stage:=2;END_IF;
537
540
  END_IF;
538
541
  IF stage=2 THEN
539
542
  writer(xExecute:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(wire),udiSize:=UINT_TO_UDINT(wireUsed));
540
- IF writer.xError THEN ${port("error")}:=5;stage:=90;ELSIF writer.xDone THEN stage:=3;END_IF;
543
+ IF writer.xError THEN ${port("error")}:=${jobError.network};stage:=90;ELSIF writer.xDone THEN stage:=3;END_IF;
541
544
  END_IF;
542
545
  IF stage=3 THEN
543
- IF used>=8191 THEN ${port("error")}:=3;stage:=90;
546
+ IF used>=8191 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
544
547
  ELSE
545
548
  reader(xEnable:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(chunk),udiSize:=8191);
546
- IF reader.xError THEN ${port("error")}:=5;stage:=90;
549
+ IF reader.xError THEN ${port("error")}:=${jobError.network};stage:=90;
547
550
  ELSIF reader.xReady AND reader.udiCount>0 THEN
548
- IF TO_UDINT(used)+reader.udiCount>8191 THEN ${port("error")}:=3;stage:=90;
551
+ IF TO_UDINT(used)+reader.udiCount>8191 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
549
552
  ELSE
550
553
  FOR index:=0 TO TO_UINT(reader.udiCount)-1 DO received[used+index]:=chunk[index];END_FOR;
551
554
  used:=used+TO_UINT(reader.udiCount);received[used]:=0;
552
555
  FindHeaders();
553
- IF headerEnd=0 AND used>4096 THEN ${port("error")}:=3;stage:=90;END_IF;
556
+ IF headerEnd=0 AND used>4096 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;END_IF;
554
557
  IF headerEnd>0 THEN
555
- IF headerEnd>4096 THEN ${port("error")}:=3;stage:=90;
558
+ IF headerEnd>4096 THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
556
559
  ELSE
557
560
  ReadHeaders();
558
- IF malformed OR contentLength<0 OR contentLength>${plcBufferBytes} THEN ${port("error")}:=3;stage:=90;
561
+ IF malformed OR contentLength<0 OR contentLength>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
559
562
  ELSIF TO_DINT(used)>=TO_DINT(headerEnd)+3+contentLength THEN
560
- IF status<200 OR status>=300 THEN ${port("error")}:=10000+status;stage:=90;
563
+ IF status<200 OR status>=300 THEN ${port("error")}:=${httpErrors.base}+status;stage:=90;
561
564
  ELSE
562
565
  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}
563
566
  stage:=90;
@@ -807,12 +810,12 @@ export function emitServiceBlock(
807
810
  endpoint.transport === "opcua"
808
811
  ? symbols.names.allocateObject(
809
812
  "GVL",
810
- "TsplcRpc_" + required(symbols.blockNames.get(fn.id)),
813
+ `TsplcRpc_${required(symbols.blockNames.get(fn.id))}`,
811
814
  )
812
815
  : undefined;
813
816
  if (rpcGlobal) {
814
817
  objects.push({
815
- id: fn.id + ":rpc",
818
+ id: `${fn.id}:rpc`,
816
819
  kind: "globalList",
817
820
  name: rpcGlobal,
818
821
  declaration: `{attribute 'qualified_only'}
@@ -1,30 +1,13 @@
1
+ export { engineeringBuildSchema } from "@tsplc/config/build";
1
2
  export { type CodesysOptions, codesys, direct } from "./config.ts";
2
3
  export { emitCodesys, type SourceMapping } from "./emit.ts";
3
4
  export {
4
5
  buildCodesys,
5
- codesysBuildConfig,
6
6
  type CodesysEngineeringBuild,
7
- engineeringBuildSchema,
7
+ codesysBuildConfig,
8
8
  } from "./engineering.ts";
9
- export { type CodesysPlan, type CodesysProject, planCodesys } from "./plan.ts";
9
+ export { ioTargets } from "./io-paths.ts";
10
10
  export type { ProjectHardware } from "./manifest.ts";
11
+ export { type CodesysPlan, type CodesysProject, planCodesys } from "./plan.ts";
12
+ export { publicationSelectors } from "./publication.ts";
11
13
  export { diagnoseCodesys } from "./vendor.ts";
12
- export {
13
- iecSpelling,
14
- ioTargets,
15
- isStoragePath,
16
- resolveStoragePath,
17
- type StorageBinding,
18
- } from "./io-paths.ts";
19
- export { planGlobalNames } from "./global-names.ts";
20
- export { publicationSelectors, resolvePublication } from "./publication.ts";
21
- export { jsonScalar, validateHttpLayout } from "./http.ts";
22
- export { Sources } from "./sources.ts";
23
- export { storageLayout } from "./storage.ts";
24
- export {
25
- accessedStorage,
26
- routineTasks,
27
- schedulePrograms,
28
- taskStorageOwnership,
29
- } from "./task-access.ts";
30
- export { planJobFailures, telemetryCalls, telemetryPath } from "./telemetry.ts";
@@ -1,3 +1,4 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import { createHash } from "node:crypto";
2
3
  import type {
3
4
  CoreExpression,
@@ -25,6 +26,7 @@ import {
25
26
  required,
26
27
  } from "./symbols.ts";
27
28
  import { telemetryClient, telemetryObjects } from "./telemetry.ts";
29
+ import { stStringLiteral } from "./types.ts";
28
30
 
29
31
  /**
30
32
  * The debugger's and telemetry's names in the program: `GVL_TsplcDebug` and its fields, each
@@ -418,7 +420,7 @@ export function jobTracking(
418
420
  if (failure) {
419
421
  line(`IF ${error} <> 0 AND ${error} <> 1 THEN`, 1);
420
422
  line(
421
- `${ringTarget(instrumentation, failure.task)}.Failure${failure.id}(code := ${error}, step := ${required(fields.step)});`,
423
+ `${ringTarget(instrumentation, failure.task)}.Failure${failure.id}(code := ${error}, step := ${required(fields.step)}${failure.instance === null ? "" : `, instance := ${stStringLiteral(failure.instance)}`});`,
422
424
  2,
423
425
  );
424
426
  line("END_IF;", 1);
@@ -1,3 +1,4 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import type { PlcType, Variable, VerifiedCoreModule } from "@tsplc/compiler/ir";
2
3
  import { type IoTarget, ioLayout } from "@tsplc/typegen/hardware";
3
4
  import { moduleName } from "./storage.ts";
@@ -123,7 +124,7 @@ export function ioTargets(core: VerifiedCoreModule): IoTarget[] {
123
124
  }
124
125
  // Typegen writes keys as template literal types, so any index matches here.
125
126
  if (type.kind === "array") {
126
- visit(`${key}[` + "${number}" + "]", types.get(type.element)!);
127
+ visit(`${key}[\${number}]`, types.get(type.element)!);
127
128
  }
128
129
  };
129
130
  for (const variable of core.variables) {
@@ -1,10 +1,4 @@
1
- import {
2
- instancedBlock,
3
- jobErrors,
4
- nanosecondsPerMillisecond,
5
- nestedBodies,
6
- standardBlocks,
7
- } from "@tsplc/compiler/ir";
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
8
2
  import type {
9
3
  Constant,
10
4
  CoreExpression,
@@ -13,6 +7,16 @@ import type {
13
7
  CoreStatement,
14
8
  PlcModule,
15
9
  PlcType,
10
+ Variable,
11
+ } from "@tsplc/compiler/ir";
12
+ import {
13
+ instancedBlock,
14
+ jobErrors,
15
+ nanosecondsPerMillisecond,
16
+ nestedBodies,
17
+ standardBlocks,
18
+ statementExpressions,
19
+ subexpressions,
16
20
  } from "@tsplc/compiler/ir";
17
21
  import type { ResolvedTsplcConfig } from "@tsplc/config";
18
22
  import type {
@@ -30,8 +34,6 @@ import { serviceOfPath } from "@tsplc/server";
30
34
  import type { HardwareCatalog } from "@tsplc/typegen/hardware";
31
35
  import { version } from "../../package.json";
32
36
  import { type InstancePath, storagePath } from "./debug.ts";
33
- import type { Instrumentation } from "./instrumentation.ts";
34
- import { statementExpressions, subexpressions } from "./operands.ts";
35
37
  import { Sources } from "./sources.ts";
36
38
  import {
37
39
  type CodesysSymbols,
@@ -383,7 +385,7 @@ function requests(
383
385
 
384
386
  /** Static member reads in a body, by TypeScript path. */
385
387
  function reads(
386
- instrumentation: Instrumentation,
388
+ variables: ReadonlyMap<string, Variable>,
387
389
  body: readonly CoreStatement[],
388
390
  sources: Sources,
389
391
  ): DebugFunction["reads"] {
@@ -397,10 +399,7 @@ function reads(
397
399
  if (value.kind !== "load") {
398
400
  return;
399
401
  }
400
- const read = storagePath(
401
- required(instrumentation.analysis.variables.get(value.root)),
402
- value.path,
403
- );
402
+ const read = storagePath(required(variables.get(value.root)), value.path);
404
403
  const range = read && sources.range(value.span);
405
404
  if (range) {
406
405
  reads.set(`${JSON.stringify(range)}${read}`, { range, path: read });
@@ -445,8 +444,18 @@ export function debugManifest(
445
444
  string,
446
445
  { id: number; range: SourceRange }
447
446
  >();
447
+ const routines = new Map(core.functions.map((fn) => [fn.id, fn]));
448
+ // A merged instance's own locals are not in the program's variables any more.
449
+ const variables = new Map([
450
+ ...instrumentation.analysis.variables,
451
+ ...plan.specialized.flatMap((fn) =>
452
+ [...fn.parameters, ...fn.locals].map(
453
+ (variable) => [variable.id, variable] as const,
454
+ ),
455
+ ),
456
+ ]);
448
457
  const functions = [
449
- ...core.functions,
458
+ ...plan.specialized,
450
459
  ...core.blocks.filter((block) => !block.standard && !block.runtime),
451
460
  ].flatMap((routine): DebugFunction[] => {
452
461
  const block = "inputs" in routine ? routine : undefined;
@@ -455,9 +464,17 @@ export function debugManifest(
455
464
  if (!declaration) {
456
465
  return [];
457
466
  }
467
+ // An instance whose routine was merged runs as the routine shared with the others. A
468
+ // routine that only returned a constant was replaced by it, and has nothing to describe.
469
+ const runs = fn
470
+ ? routines.get(plan.sharedRoutines.get(fn.id) ?? fn.id)
471
+ : routine;
472
+ if (!runs) {
473
+ return [];
474
+ }
458
475
  const id = declaredFunctions.size;
459
476
  declaredFunctions.set(routine.id, { id, range: declaration });
460
- const task = instrumentation.analysis.tasks.get(routine.id);
477
+ const task = instrumentation.analysis.tasks.get(runs.id);
461
478
  const origin = fn?.origin;
462
479
  return [
463
480
  {
@@ -466,8 +483,8 @@ export function debugManifest(
466
483
  declaration,
467
484
  ...(origin?.instance && { instance: origin.instance }),
468
485
  ...(task && { task }),
469
- target: routineTarget(symbols, routine),
470
- reads: reads(instrumentation, routine.body, sources),
486
+ target: routineTarget(symbols, runs),
487
+ reads: reads(variables, routine.body, sources),
471
488
  },
472
489
  ];
473
490
  });
@@ -2,18 +2,16 @@ import {
2
2
  type Constant,
3
3
  type CoreExpression,
4
4
  type CoreStatement,
5
+ floatMaximum,
5
6
  type GeneratedObject,
6
7
  integerRange,
7
- floatMaximum,
8
8
  integerType,
9
9
  nestedBodies,
10
10
  type PlcType,
11
- } from "@tsplc/compiler/ir";
12
- import {
13
11
  pathIndexes,
14
12
  statementExpressions,
15
13
  subexpressions,
16
- } from "./operands.ts";
14
+ } from "@tsplc/compiler/ir";
17
15
 
18
16
  const operatorTokens: Readonly<Record<string, string>> = {
19
17
  add: "+",