@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -0,0 +1,111 @@
1
+ import { type Environment, type HttpOptions, secretValue } from "@tsplc/config";
2
+
3
+ /** Where a client sends its requests: a server over HTTP(S), or a route of the app server's OPC UA gateway. */
4
+ export type HttpEndpoint =
5
+ | {
6
+ transport: "http";
7
+ host: string;
8
+ port: number;
9
+ authority: string;
10
+ path: string;
11
+ token: string;
12
+ timeoutMs: number;
13
+ tls: boolean;
14
+ }
15
+ | { transport: "opcua"; path: string; timeoutMs: number };
16
+
17
+ export type NativeEndpoint = Extract<HttpEndpoint, { transport: "http" }>;
18
+
19
+ const invalidUrl = { error: "Invalid URL" };
20
+
21
+ /** Each configured credential's bearer token, by the exact origin it is sent to. */
22
+ export const resolveHttpCredentials = (
23
+ credentials: HttpOptions["credentials"],
24
+ environment: Environment,
25
+ ): { tokens: ReadonlyMap<string, string> } | { error: string } => {
26
+ const tokens = new Map<string, string>();
27
+ for (const credential of credentials) {
28
+ const configured = environment[credential.originEnv];
29
+ const secret = environment[credential.bearerTokenEnv];
30
+ if (!configured || !secret) {
31
+ return {
32
+ error: `HTTP credentials require ${credential.originEnv} and ${credential.bearerTokenEnv}.`,
33
+ };
34
+ }
35
+ const origin = URL.parse(configured);
36
+ if (!origin) {
37
+ return invalidUrl;
38
+ }
39
+ if (
40
+ !["http:", "https:"].includes(origin.protocol) ||
41
+ origin.username ||
42
+ origin.password ||
43
+ origin.pathname !== "/" ||
44
+ origin.search ||
45
+ origin.hash
46
+ ) {
47
+ return {
48
+ error: `HTTP credential origin ${credential.originEnv} must contain only a scheme, host and port.`,
49
+ };
50
+ }
51
+ if (tokens.has(origin.origin)) {
52
+ return { error: "HTTP credential origins must be unique." };
53
+ }
54
+ if (!secretValue.safeParse(secret).success) {
55
+ return { error: `Invalid bearer token in ${credential.bearerTokenEnv}.` };
56
+ }
57
+ tokens.set(origin.origin, secret);
58
+ }
59
+ return { tokens };
60
+ };
61
+
62
+ export const resolveHttpEndpoint = (
63
+ value: string,
64
+ input: HttpOptions,
65
+ environment: Environment,
66
+ ): NativeEndpoint | { error: string } => {
67
+ const url = URL.parse(value);
68
+ if (!url) {
69
+ return invalidUrl;
70
+ }
71
+ if (
72
+ !["http:", "https:"].includes(url.protocol) ||
73
+ url.username ||
74
+ url.password ||
75
+ url.hash ||
76
+ url.hostname.includes(":")
77
+ ) {
78
+ return {
79
+ error:
80
+ "fetch requires an HTTP(S) URL with an IPv4 address or DNS hostname, without credentials or fragment.",
81
+ };
82
+ }
83
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
84
+ if (
85
+ (url.pathname + url.search).length > 2048 ||
86
+ url.hostname.length > 253 ||
87
+ port === 0
88
+ ) {
89
+ return {
90
+ error:
91
+ "HTTP URL exceeds the native host/path limits or has an invalid port.",
92
+ };
93
+ }
94
+ const credentials = resolveHttpCredentials(input.credentials, environment);
95
+ if ("error" in credentials) {
96
+ return credentials;
97
+ }
98
+ return {
99
+ transport: "http",
100
+ host: url.hostname,
101
+ port,
102
+ authority: url.host,
103
+ path: url.pathname + url.search,
104
+ token: credentials.tokens.get(url.origin) ?? "",
105
+ timeoutMs: input.timeoutMs,
106
+ tls: url.protocol === "https:",
107
+ };
108
+ };
109
+
110
+ /** A server base URL as routes such as the telemetry path are appended to it, by the PLC and the Bun runtime alike. */
111
+ export const routeBase = (baseUrl: string) => baseUrl.replace(/\/+$/, "");
@@ -1,15 +1,17 @@
1
1
  import { resolve } from "node:path";
2
2
  import {
3
- buildProject,
3
+ compileStructuredText,
4
4
  type InstalledLibrary,
5
5
  type ProgressOptions,
6
6
  } from "@tsplc/build";
7
- import type { EmitResult } from "@tsplc/compiler/ir";
8
7
  import type { Controller, DeviceTree } from "@tsplc/config";
9
8
  import { engineeringBuildSchema, resolveConfig } from "@tsplc/config/build";
10
9
  import { z } from "zod";
10
+ import type { CodesysBundle } from "./emit";
11
+ import { httpLibraryReferences } from "./http";
11
12
  import type { CodesysPlan } from "./plan";
12
13
  import { taskPrograms } from "./programs";
14
+ import { required } from "./required";
13
15
 
14
16
  export const engineeringSchema = z.strictObject({
15
17
  kind: z.literal("v3.5"),
@@ -19,7 +21,7 @@ export type CodesysEngineeringBuild = z.input<typeof engineeringBuildSchema>;
19
21
 
20
22
  export function codesysBuildConfig(
21
23
  plan: CodesysPlan,
22
- bundle: Pick<EmitResult, "objects">,
24
+ bundle: Pick<CodesysBundle, "objects">,
23
25
  paths: {
24
26
  configFile: string;
25
27
  sourceDir: string;
@@ -32,77 +34,48 @@ export function codesysBuildConfig(
32
34
  const settings = plan.options.engineering.build;
33
35
  if (!settings) {
34
36
  throw new Error(
35
- "CODESYS build requires engineering.build settings (codesys installation and template). Configure them or use --emit-only.",
37
+ 'Compiling with CODESYS needs a build section in the config, for example build: { outDir: "build/codesys" }. Add one, or emit the Structured Text only with build --emit-only.',
36
38
  );
37
39
  }
40
+ const [first] = plan.core.programs;
41
+ if (!first) {
42
+ throw new Error("CODESYS build requires a generated PROGRAM entry.");
43
+ }
38
44
  const programs = new Map(
39
- plan.core.programs.map((program) => {
40
- const matches = bundle.objects.filter(
41
- (object) => object.id === program.id && object.kind === "program",
42
- );
43
- const generated = matches[0];
44
- if (matches.length !== 1 || !generated) {
45
- throw new Error(
46
- `Generated bundle must contain one PROGRAM object for ${program.name}.`,
47
- );
48
- }
49
- return [program.name, generated] as const;
50
- }),
45
+ bundle.objects
46
+ .filter((object) => object.kind === "program")
47
+ .map((object) => [object.id, object]),
51
48
  );
49
+ const programIds = new Map(
50
+ plan.core.programs.map((program) => [program.name, program.id]),
51
+ );
52
+ const programObject = (id: string) => required(programs.get(id));
52
53
  const tasks = plan.deployment.tasks.map((task) => {
53
54
  const { configured, wrapper } = taskPrograms(plan, task);
54
- const wrapperObject = bundle.objects.find(
55
- (object) => object.id === wrapper.id && object.kind === "program",
56
- );
57
- if (!wrapperObject) {
58
- throw new Error(
59
- `Generated bundle has no wrapper PROGRAM for ${task.name}.`,
60
- );
61
- }
62
55
  return {
63
56
  ...task,
64
57
  programs: [
65
- ...configured.map((name) => {
66
- const program = programs.get(name);
67
- if (!program) {
68
- throw new Error(
69
- `Task ${task.name} references a missing generated PROGRAM ${name}.`,
70
- );
71
- }
72
- return program.name;
73
- }),
74
- wrapperObject.name,
58
+ ...configured.map(
59
+ (name) => programObject(required(programIds.get(name))).name,
60
+ ),
61
+ programObject(wrapper.id).name,
75
62
  ],
76
63
  };
77
64
  });
78
- const first = plan.core.programs[0];
79
- const entry = first && programs.get(first.name);
80
- if (!entry) {
81
- throw new Error("CODESYS build requires a generated PROGRAM entry.");
82
- }
65
+ const entry = programObject(first.id);
83
66
  const sourceDir = resolve(paths.sourceDir);
84
67
  return resolveConfig(
85
68
  {
86
69
  ...settings,
87
70
  libraryReferences: [
88
- ...(settings.libraryReferences ?? []),
89
- ...(Object.values(plan.http).some(
90
- (endpoint) => endpoint.transport !== "opcua",
91
- )
92
- ? ["Net Base Services, 4.0.0.0 (CODESYS)"]
93
- : []),
94
- ...(Object.values(plan.http).some((endpoint) => endpoint.tls)
95
- ? ["CmpX509Cert Implementation, 3.5.22.0 (System)"]
96
- : []),
71
+ ...settings.libraryReferences,
72
+ ...httpLibraryReferences(plan),
97
73
  ],
98
74
  ...(paths.libraries ? { libraries: paths.libraries } : {}),
99
75
  ...(paths.deviceTree ? { deviceTree: paths.deviceTree } : {}),
100
76
  ...(paths.controller ? { controller: paths.controller } : {}),
101
77
  sourceDir,
102
- entry: resolve(
103
- sourceDir,
104
- entry.sourcePath ?? `${entry.name}/declaration.st`,
105
- ),
78
+ entry: resolve(sourceDir, entry.sourcePath),
106
79
  outDir: resolve(paths.outDir),
107
80
  tasks,
108
81
  },
@@ -112,9 +85,12 @@ export function codesysBuildConfig(
112
85
 
113
86
  export async function buildCodesys(
114
87
  plan: CodesysPlan,
115
- bundle: Pick<EmitResult, "objects">,
88
+ bundle: Pick<CodesysBundle, "objects">,
116
89
  paths: Parameters<typeof codesysBuildConfig>[2],
117
90
  options: ProgressOptions = {},
118
91
  ) {
119
- return buildProject(codesysBuildConfig(plan, bundle, paths), options);
92
+ return compileStructuredText(
93
+ codesysBuildConfig(plan, bundle, paths),
94
+ options,
95
+ );
120
96
  }
@@ -0,0 +1,445 @@
1
+ import {
2
+ type Constant,
3
+ type CoreTables,
4
+ instanceFields,
5
+ type PathCondition,
6
+ type PlcType,
7
+ type ReconstructedSegment,
8
+ type Reconstruction,
9
+ staticNames,
10
+ type Variable,
11
+ type VerifiedCoreModule,
12
+ } from "@tsplc/compiler/ir";
13
+ import type {
14
+ ExplainAssignment,
15
+ ExplainCondition,
16
+ ExplainLocal,
17
+ } from "@tsplc/debug/explain-file";
18
+ import { anyIndex, patternOf } from "@tsplc/debug/paths";
19
+ import { typescriptPath } from "../debug";
20
+ import { constantValue } from "../manifest";
21
+ import { storagePath } from "../storage";
22
+ import { parameterKey } from "./parameters";
23
+ import type { Row } from "./rows";
24
+ import type { ExplainTables } from "./tables";
25
+
26
+ /** A place as the debugger names it: a storage path, with a `[*]` for each dynamic index. */
27
+ export interface Spelled {
28
+ readonly text: string;
29
+ readonly indexes: readonly number[];
30
+ readonly type: PlcType | undefined;
31
+ }
32
+
33
+ const aggregateKinds: ReadonlySet<PlcType["kind"]> = new Set([
34
+ "record",
35
+ "array",
36
+ "block",
37
+ ]);
38
+
39
+ /** The storage path of a module variable or constant table; undefined for anything else. */
40
+ export const storedPath = (variable: Variable): string | undefined =>
41
+ variable.storage === "constant"
42
+ ? storagePath(variable)
43
+ : typescriptPath(variable);
44
+
45
+ /** The part of a constant at a path of record fields; an element of an array stays a read of the table. */
46
+ const constantAt = (
47
+ value: Constant,
48
+ names: readonly string[],
49
+ ): Constant | undefined => {
50
+ const [name, ...rest] = names;
51
+ if (name === undefined) {
52
+ return value;
53
+ }
54
+ if (value.kind === "record") {
55
+ const field = value.fields[name];
56
+ return field && constantAt(field, rest);
57
+ }
58
+ return undefined;
59
+ };
60
+
61
+ /**
62
+ * Writes reconstructions, conditions and places into `tables` as a row names them, and keeps the
63
+ * locals the rows define and the rows that read each path.
64
+ */
65
+ export function explainEncoder(
66
+ program: VerifiedCoreModule,
67
+ core: CoreTables,
68
+ tables: ExplainTables,
69
+ /** The parameters each routine writes through, by `parameterKey`. */
70
+ writesThrough: ReadonlySet<string>,
71
+ ) {
72
+ const { paths, texts, expressions } = tables;
73
+ /** Fields that hold an object reference, with every index as `[*]`. */
74
+ const referenceFields = new Set(
75
+ (program.references?.fields ?? []).map(patternOf),
76
+ );
77
+ /** The rows that read each path. */
78
+ const readers = new Map<string, Set<number>>();
79
+ const locals: ExplainLocal[] = [];
80
+ const rowLocals = new Map<
81
+ string,
82
+ { index: number; definitions: ExplainLocal["definitions"] }
83
+ >();
84
+
85
+ /** A local of a row, by its index in `locals`, made when the row first names it. */
86
+ const local = (row: Row, root: string) => {
87
+ const key = `${row.index}:${root}`;
88
+ const known = rowLocals.get(key);
89
+ if (known) {
90
+ return known;
91
+ }
92
+ const variable = core.variableOf(root);
93
+ const created: ExplainLocal = {
94
+ routine: row.index,
95
+ name: variable.name,
96
+ parameter: variable.storage === "parameter",
97
+ reference: false,
98
+ definitions: [],
99
+ };
100
+ const entry = { index: locals.length, definitions: created.definitions };
101
+ locals.push(created);
102
+ rowLocals.set(key, entry);
103
+ return entry;
104
+ };
105
+
106
+ const fieldType = (
107
+ type: PlcType | undefined,
108
+ name: string,
109
+ ): PlcType | undefined => {
110
+ if (type?.kind === "block") {
111
+ const block = core.blockOf(type.block);
112
+ const field = instanceFields(block).find(
113
+ (variable) => variable.name === name,
114
+ );
115
+ return field && core.types.get(field.type);
116
+ }
117
+ if (type?.kind === "record") {
118
+ const field = type.fields.find((item) => item.name === name);
119
+ return field && core.types.get(field.type);
120
+ }
121
+ return undefined;
122
+ };
123
+
124
+ /** A spelled place followed further along a path evaluated in `row`. */
125
+ const extend = (
126
+ row: Row,
127
+ spelled: Spelled,
128
+ path: readonly ReconstructedSegment[],
129
+ ): Spelled =>
130
+ path.reduce<Spelled>((place, segment) => {
131
+ if (segment.kind === "field") {
132
+ // Block outputs are fields of the instance itself, so its `out` view adds no segment.
133
+ if (place.type?.kind === "block" && segment.name === "out") {
134
+ const { output } = place.type;
135
+ return {
136
+ text: place.text,
137
+ indexes: place.indexes,
138
+ type: output ? core.types.get(output) : undefined,
139
+ };
140
+ }
141
+ return {
142
+ text: `${place.text}.${segment.name}`,
143
+ indexes: place.indexes,
144
+ type: fieldType(place.type, segment.name),
145
+ };
146
+ }
147
+ const type =
148
+ place.type?.kind === "array"
149
+ ? core.types.get(place.type.element)
150
+ : undefined;
151
+ const value = segment.value;
152
+ if (value.kind === "constant" && value.value.kind === "integer") {
153
+ return {
154
+ text: `${place.text}[${value.value.value}]`,
155
+ indexes: place.indexes,
156
+ type,
157
+ };
158
+ }
159
+ return {
160
+ text: `${place.text}${anyIndex}`,
161
+ indexes: [...place.indexes, expression(row, value)],
162
+ type,
163
+ };
164
+ }, spelled);
165
+
166
+ /** The storage path of a place in a row, or nothing for a temporary, local or parameter. */
167
+ const spell = (
168
+ row: Row,
169
+ root: string,
170
+ path: readonly ReconstructedSegment[],
171
+ ): Spelled | undefined => {
172
+ const variable = core.variableOf(root);
173
+ const field = row.fields.has(root);
174
+ if (field && row.instance === null) {
175
+ return undefined;
176
+ }
177
+ const start = field
178
+ ? `${row.instance}.${variable.name}`
179
+ : storedPath(variable);
180
+ if (start === undefined) {
181
+ return undefined;
182
+ }
183
+ return extend(
184
+ row,
185
+ { text: start, indexes: [], type: core.types.get(variable.type) },
186
+ path,
187
+ );
188
+ };
189
+
190
+ /** A place as a record names what it writes or calls. */
191
+ const placeRef = (spelled: Spelled): ExplainAssignment["writes"] =>
192
+ spelled.indexes.length
193
+ ? {
194
+ kind: "pattern",
195
+ path: paths.add(spelled.text),
196
+ indexes: [...spelled.indexes],
197
+ }
198
+ : { kind: "path", path: paths.add(spelled.text) };
199
+
200
+ const isAggregate = (spelled: Spelled): boolean =>
201
+ spelled.type !== undefined && aggregateKinds.has(spelled.type.kind);
202
+
203
+ /** A live read of a stored place at `capturedAt`. */
204
+ const storedRead = (
205
+ row: Row,
206
+ spelled: Spelled,
207
+ read: {
208
+ capturedAt: number;
209
+ interleaved?: true;
210
+ type: string;
211
+ },
212
+ ): number => {
213
+ const path = row.slots.paths.add(paths.add(spelled.text));
214
+ const { capturedAt, interleaved, type } = read;
215
+ return expressions.add(
216
+ spelled.indexes.length
217
+ ? {
218
+ kind: "pattern",
219
+ path,
220
+ indexes: [...spelled.indexes],
221
+ capturedAt,
222
+ ...(interleaved && { interleaved }),
223
+ type,
224
+ }
225
+ : {
226
+ kind: "read",
227
+ path,
228
+ capturedAt,
229
+ ...(interleaved && { interleaved }),
230
+ type,
231
+ },
232
+ );
233
+ };
234
+
235
+ const opaque = (
236
+ reason: string,
237
+ type: string,
238
+ reads: readonly number[] = [],
239
+ ): number =>
240
+ expressions.add({
241
+ kind: "opaque",
242
+ text: texts.add(reason),
243
+ reads: [...reads],
244
+ type,
245
+ });
246
+
247
+ const expression = (row: Row, node: Reconstruction): number => {
248
+ switch (node.kind) {
249
+ case "read": {
250
+ // A constant table read at fixed indexes is its value; there is nothing to read live.
251
+ const table = core.variableOf(node.root);
252
+ const names = staticNames(node.path);
253
+ const fixed =
254
+ table.storage === "constant" && table.initial && names
255
+ ? constantAt(table.initial, names)
256
+ : undefined;
257
+ if (fixed) {
258
+ return expressions.add({
259
+ kind: "constant",
260
+ value: constantValue(fixed),
261
+ type: node.type,
262
+ });
263
+ }
264
+ const spelled = spell(row, node.root, node.path);
265
+ if (!spelled) {
266
+ return opaque("not stored", node.type);
267
+ }
268
+ const read = storedRead(row, spelled, {
269
+ capturedAt: node.capturedAt,
270
+ ...(node.interleaved && { interleaved: true as const }),
271
+ type: node.type,
272
+ });
273
+ const readBy = readers.get(spelled.text) ?? new Set<number>();
274
+ readBy.add(row.index);
275
+ readers.set(spelled.text, readBy);
276
+ // A field holding an object reference holds the object's id: show the object.
277
+ return referenceFields.has(patternOf(spelled.text))
278
+ ? expressions.add({ kind: "reference", operand: read })
279
+ : read;
280
+ }
281
+ case "local": {
282
+ const names = staticNames(node.path);
283
+ return names
284
+ ? expressions.add({
285
+ kind: "local",
286
+ local: row.slots.locals.add(local(row, node.root).index),
287
+ path: names,
288
+ at: node.at,
289
+ type: node.type,
290
+ })
291
+ : opaque("a local at a dynamic index", node.type);
292
+ }
293
+ case "parameter": {
294
+ const names = staticNames(node.path);
295
+ if (!names) {
296
+ return opaque("a parameter at a dynamic index", node.type);
297
+ }
298
+ const written = writesThrough.has(
299
+ parameterKey(row.routine.id, node.parameter),
300
+ );
301
+ return expressions.add({
302
+ kind: "parameter",
303
+ parameter: node.parameter,
304
+ path: names,
305
+ at: node.at,
306
+ local: written
307
+ ? row.slots.locals.add(local(row, node.root).index)
308
+ : null,
309
+ type: node.type,
310
+ });
311
+ }
312
+ case "call": {
313
+ const call = row.calls.get(node.call);
314
+ return call === undefined
315
+ ? opaque("a call that isn't traced", node.type)
316
+ : expressions.add({
317
+ kind: "call",
318
+ call: row.slots.calls.add(call),
319
+ path: [...node.path],
320
+ type: node.type,
321
+ });
322
+ }
323
+ case "constant":
324
+ return expressions.add({
325
+ kind: "constant",
326
+ value: constantValue(node.value),
327
+ type: node.type,
328
+ });
329
+ case "clock":
330
+ return expressions.add({ kind: "clock", type: node.type });
331
+ case "unary":
332
+ return expressions.add({
333
+ kind: "unary",
334
+ operator: node.operator,
335
+ operand: expression(row, node.operand),
336
+ type: node.type,
337
+ });
338
+ case "binary":
339
+ return expressions.add({
340
+ kind: "binary",
341
+ operator: node.operator,
342
+ ...(node.policy && { policy: node.policy }),
343
+ left: expression(row, node.left),
344
+ right: expression(row, node.right),
345
+ type: node.type,
346
+ });
347
+ case "convert":
348
+ return expressions.add({
349
+ kind: "convert",
350
+ policy: node.policy,
351
+ operand: expression(row, node.operand),
352
+ type: node.type,
353
+ });
354
+ case "logical":
355
+ return expressions.add({
356
+ kind: "logical",
357
+ operator: node.operator,
358
+ left: expression(row, node.left),
359
+ right: expression(row, node.right),
360
+ });
361
+ case "select":
362
+ return expressions.add({
363
+ kind: "select",
364
+ condition: expression(row, node.condition),
365
+ // biome-ignore lint/suspicious/noThenProperty: a `?:` branch is data, not a thenable.
366
+ then: expression(row, node.then),
367
+ else: expression(row, node.else),
368
+ type: node.type,
369
+ });
370
+ case "record":
371
+ return expressions.add({
372
+ kind: "record",
373
+ fields: Object.fromEntries(
374
+ Object.entries(node.fields).map(([name, value]) => [
375
+ name,
376
+ expression(row, value),
377
+ ]),
378
+ ),
379
+ type: node.type,
380
+ });
381
+ case "array":
382
+ return expressions.add({
383
+ kind: "array",
384
+ lower: node.lower,
385
+ items: node.items.map((item) => expression(row, item)),
386
+ type: node.type,
387
+ });
388
+ case "opaque":
389
+ return opaque(
390
+ node.reason,
391
+ node.type,
392
+ node.reads.map((read) => expression(row, read)),
393
+ );
394
+ }
395
+ };
396
+
397
+ const condition = (row: Row, item: PathCondition): ExplainCondition => {
398
+ switch (item.kind) {
399
+ case "test":
400
+ return {
401
+ kind: "test",
402
+ test: expression(row, item.test),
403
+ holds: item.holds,
404
+ at: item.at,
405
+ text: tables.text(item.span),
406
+ };
407
+ case "cases":
408
+ return {
409
+ kind: "cases",
410
+ test: expression(row, item.test),
411
+ values: item.values.map(constantValue),
412
+ member: item.member,
413
+ at: item.at,
414
+ text: tables.text(item.span),
415
+ };
416
+ case "exits":
417
+ return {
418
+ kind: "exits",
419
+ any: item.any.map((all) => all.map((part) => condition(row, part))),
420
+ };
421
+ case "loop":
422
+ case "loopReturns":
423
+ return { kind: item.kind, loop: item.loop };
424
+ case "job":
425
+ return { kind: "job", step: item.step };
426
+ case "jobBusy":
427
+ return { kind: "jobBusy" };
428
+ }
429
+ };
430
+
431
+ return {
432
+ expression,
433
+ condition,
434
+ spell,
435
+ extend,
436
+ local,
437
+ placeRef,
438
+ isAggregate,
439
+ storedRead,
440
+ readers,
441
+ locals,
442
+ };
443
+ }
444
+
445
+ export type ExplainEncoder = ReturnType<typeof explainEncoder>;