@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6558 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16076 -0
  12. package/dist/index.js.map +61 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1078 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,324 @@
1
+ import { readFile, realpath } from "node:fs/promises";
2
+ import { isAbsolute, join, relative, resolve } from "node:path";
3
+ import { failureCode, failureName, jobError } from "@tsplc/compiler/ir";
4
+ import {
5
+ controllerDeviceName,
6
+ type Environment,
7
+ loadTsplcConfig,
8
+ } from "@tsplc/config";
9
+ import { opcuaPort } from "@tsplc/config/build";
10
+ import { emittedStDirectory } from "@tsplc/config/project-files";
11
+ import { debugManifest, debugManifestFile } from "@tsplc/debug/manifest";
12
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
13
+ import {
14
+ type PublishedScalar,
15
+ publishedScalars,
16
+ servePublishedGlobals,
17
+ } from "@tsplc/opcua/server";
18
+ import { telemetryPath } from "@tsplc/server/telemetry";
19
+ import { readDeclarations } from "@tsplc/typegen/declarations";
20
+ import { now } from "../../stdlib/clock";
21
+ import { plcTime } from "../../stdlib/plc-time";
22
+ import { persist, retain } from "../../stdlib/retain";
23
+ import { onTelemetry, telemetry } from "../../stdlib/telemetry";
24
+ import { createAsync, oneLaunchAtATime } from "./async";
25
+ import { type Launch, runtimeDirectory, runtimeFiles } from "./launch";
26
+ import { loadProgram, type SdkModule } from "./program";
27
+ import { createRetention } from "./retain";
28
+ import { runtimeSettings } from "./settings";
29
+ import { createStorage } from "./storage";
30
+ import { plcGlobals } from "./symbols";
31
+ import { createTelemetry } from "./telemetry";
32
+ import { httpTransport, opcuaSlots, readServiceChannels } from "./transport";
33
+
34
+ /** Where the runtime publishes OPC UA: the local CODESYS runtime's address and port. */
35
+ export const runtimeEndpoint = { host: "127.0.0.1", port: opcuaPort } as const;
36
+
37
+ export interface RuntimeOptions {
38
+ launch: Launch;
39
+ /** The environment the config's variables resolve in, before the launch's target's values. */
40
+ environment: Environment;
41
+ /** Where OPC UA listens; `runtimeEndpoint` unless a test picks a free port. */
42
+ port: number;
43
+ log: (line: string) => void;
44
+ }
45
+
46
+ /** A telemetry record's `file:line`, relative to the project's real directory rather than to the working directory. */
47
+ const projectSource = (root: string, source: unknown) => {
48
+ if (typeof source !== "string" || !source) {
49
+ return "";
50
+ }
51
+ const separator = source.lastIndexOf(":");
52
+ const file = resolve(source.slice(0, separator));
53
+ const path = relative(root, file);
54
+ return `${isAbsolute(path) ? file : path.replaceAll("\\", "/")}${source.slice(separator)}`;
55
+ };
56
+
57
+ /**
58
+ * Runs a project's PLC program in this Bun process, as `tsplc run --bun` does: each task's programs
59
+ * scan to completion on the task's cycle, services and telemetry go to the project's server over
60
+ * `server.transport` as the compiled program sends them, and the development publication is served
61
+ * over OPC UA as the local CODESYS runtime serves it. Reads the last build's artifacts.
62
+ */
63
+ export const startRuntime = async (options: RuntimeOptions) => {
64
+ const { launch, log } = options;
65
+ const { config, root, env } = await loadTsplcConfig(launch.config, {
66
+ env: options.environment,
67
+ target: launch.target ?? undefined,
68
+ forAgent: false,
69
+ });
70
+ const { compiler, tasks } = config;
71
+ if (!compiler || !tasks) {
72
+ throw new Error("The Bun runtime runs a TypeScript program.");
73
+ }
74
+ const st = resolve(root, emittedStDirectory);
75
+ const manifest = debugManifest.parse(
76
+ JSON.parse(await readFile(join(st, debugManifestFile), "utf8")),
77
+ );
78
+ const globals = plcGlobals(await readDeclarations(st));
79
+
80
+ const { http, baseUrl, telemetryCapacity } = runtimeSettings(config, env);
81
+ // Over OPC UA the app server's gateway serves the slots this process publishes, as it serves a PLC's.
82
+ const slots =
83
+ config.server?.transport === "opcua"
84
+ ? opcuaSlots(await readServiceChannels(st), http.timeoutMs)
85
+ : null;
86
+ const transport =
87
+ slots?.transport ??
88
+ (baseUrl === null ? null : httpTransport(http, baseUrl));
89
+
90
+ /**
91
+ * The task whose scan runs, or last ran: continuations run in their caller's task. `time` is
92
+ * the clock as that scan read it when it began.
93
+ */
94
+ const current = {
95
+ task: tasks[0]?.name ?? "",
96
+ scan: 0,
97
+ scanning: false,
98
+ time: 0,
99
+ };
100
+ const diagnostics = { count: 0, lastError: 0 };
101
+ const records = createTelemetry({
102
+ build: manifest.build.id,
103
+ capacity: telemetryCapacity,
104
+ post: transport ? (body) => transport.call(telemetryPath, body) : null,
105
+ clock: plcTime,
106
+ log,
107
+ });
108
+ const realRoot = await realpath(root);
109
+ const stopTelemetry = onTelemetry((record) =>
110
+ records.record(current.task, {
111
+ ...record,
112
+ scan: current.scan,
113
+ source: projectSource(realRoot, record.source),
114
+ }),
115
+ );
116
+ const failed = new WeakMap<Promise<unknown>, string>();
117
+ const unhandled = (reason: unknown, promise: Promise<unknown>) => {
118
+ const code = failureCode(reason);
119
+ if (code === jobError.cancelled) {
120
+ return;
121
+ }
122
+ diagnostics.count += 1;
123
+ diagnostics.lastError = code;
124
+ const name = failureName(reason);
125
+ const fn = failed.get(promise);
126
+ records.record(current.task, {
127
+ kind: "exception",
128
+ code,
129
+ ...(name && { name }),
130
+ handled: false,
131
+ ...(fn && { function: fn }),
132
+ properties: {},
133
+ source: "",
134
+ scan: current.scan,
135
+ time: plcTime(),
136
+ });
137
+ if (typeof reason !== "number") {
138
+ log(`An async call failed and nothing caught it: ${String(reason)}`);
139
+ }
140
+ };
141
+ process.on("unhandledRejection", unhandled);
142
+
143
+ const program = await loadProgram({
144
+ sources: manifest.sources.map((source) => resolve(root, source)),
145
+ entries: Object.fromEntries(
146
+ Object.entries(compiler.programs).map(([key, entry]) => [
147
+ key,
148
+ { module: resolve(root, entry.module), export: entry.export },
149
+ ]),
150
+ ),
151
+ sdk: {
152
+ "@tsplc/compiler/clock": {
153
+ // Awaited code resumes between scans here, where no scan's time stands, so it reads the clock itself.
154
+ now: () => (current.scanning ? current.time : now()),
155
+ } satisfies SdkModule<typeof import("../../types/clock")>,
156
+ "@tsplc/compiler/retain": { persist, retain } satisfies SdkModule<
157
+ typeof import("../../types/retain")
158
+ >,
159
+ "@tsplc/compiler/telemetry": {
160
+ telemetry,
161
+ onTelemetry,
162
+ } satisfies SdkModule<typeof import("../../types/telemetry")>,
163
+ "@tsplc/compiler/async": createAsync(
164
+ { http, services: { routes: launch.services, transport } },
165
+ diagnostics,
166
+ ) satisfies SdkModule<typeof import("../../types/async")>,
167
+ "@tsplc/compiler/config": {
168
+ env: (name: string) => {
169
+ const value = env[name];
170
+ if (value === undefined) {
171
+ throw new Error(`${name} is not set.`);
172
+ }
173
+ return value;
174
+ },
175
+ } satisfies SdkModule<typeof import("../../types/config")>,
176
+ },
177
+ }).catch((cause: unknown) => {
178
+ throw new Error("The program failed to load in Bun.", { cause });
179
+ });
180
+ oneLaunchAtATime(program.classes, {
181
+ scanning: () => current.scanning,
182
+ diagnostics,
183
+ failed,
184
+ });
185
+
186
+ const storage = createStorage(manifest, program.binding);
187
+ storage.keepStoredValues();
188
+ const scalars = new Map<string, PublishedScalar>();
189
+ const bound = (global: (typeof globals.published)[number]) =>
190
+ publishedScalars(global).every(({ path }) => {
191
+ const scalar = storage.scalar(path) ?? slots?.scalar(path);
192
+ if (scalar) {
193
+ scalars.set(path, scalar);
194
+ }
195
+ return scalar !== undefined;
196
+ });
197
+ const published = globals.published.filter(bound);
198
+ const unbound = globals.published.filter(
199
+ (global) => !published.includes(global),
200
+ );
201
+ const retention = createRetention(
202
+ globals.retained,
203
+ storage.scalar,
204
+ join(root, runtimeDirectory, runtimeFiles.retain),
205
+ );
206
+ const restored = await retention.restore();
207
+ if ("restored" in restored) {
208
+ log(`Restored ${restored.restored} retained values.`);
209
+ } else if ("discarded" in restored) {
210
+ log(
211
+ `Retained values start from their initial values: ${restored.discarded}.`,
212
+ );
213
+ }
214
+
215
+ const server = await servePublishedGlobals({
216
+ host: runtimeEndpoint.host,
217
+ port: options.port,
218
+ device: controllerDeviceName(config, "run"),
219
+ globals: published,
220
+ scalar: (path) => {
221
+ const scalar = scalars.get(path);
222
+ if (!scalar) {
223
+ throw new Error(`${path} has no storage in the program.`);
224
+ }
225
+ return scalar;
226
+ },
227
+ certificateDirectory: join(
228
+ root,
229
+ runtimeDirectory,
230
+ runtimeFiles.certificates,
231
+ ),
232
+ }).catch((cause: unknown) => {
233
+ throw cause instanceof Error &&
234
+ "code" in cause &&
235
+ cause.code === "EADDRINUSE"
236
+ ? new Error(
237
+ `Port ${options.port} is taken: stop the other PLC first, such as the CODESYS runtime \`tsplc run\` starts.`,
238
+ )
239
+ : cause;
240
+ });
241
+
242
+ const timers = new Map<string, Timer>();
243
+ const stopped = { value: false };
244
+ const stopTasks = () => {
245
+ stopped.value = true;
246
+ for (const timer of timers.values()) {
247
+ clearTimeout(timer);
248
+ }
249
+ };
250
+ for (const task of tasks) {
251
+ const intervalMs =
252
+ Number(task.schedule.interval.nanoseconds) /
253
+ Number(nanosecondsPerMillisecond);
254
+ const entries = task.programs.flatMap((key) => {
255
+ const entry = program.programs.get(key);
256
+ return entry ? [entry] : [];
257
+ });
258
+ const state = { scan: 0, due: performance.now() };
259
+ const schedule = () => {
260
+ timers.set(
261
+ task.name,
262
+ setTimeout(scan, Math.max(0, state.due - performance.now())),
263
+ );
264
+ };
265
+ const scan = () => {
266
+ if (stopped.value) {
267
+ return;
268
+ }
269
+ state.scan += 1;
270
+ Object.assign(current, {
271
+ task: task.name,
272
+ scan: state.scan,
273
+ scanning: true,
274
+ time: now(),
275
+ });
276
+ try {
277
+ records.send(task.name, state.scan);
278
+ for (const entry of entries) {
279
+ entry();
280
+ }
281
+ } catch (error) {
282
+ stopTasks();
283
+ log(
284
+ `${task.name} stopped in scan ${state.scan}: the program threw, which stops the application as an exception stops it on CODESYS. Restart the runtime.\n${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
285
+ );
286
+ return;
287
+ } finally {
288
+ current.scanning = false;
289
+ }
290
+ // A late scan starts the next cycle at once rather than running the missed ones.
291
+ state.due = Math.max(state.due + intervalMs, performance.now());
292
+ schedule();
293
+ };
294
+ schedule();
295
+ log(
296
+ `${task.name} scans ${task.programs.join(", ")} every ${intervalMs} ms.`,
297
+ );
298
+ }
299
+ if (unbound.length) {
300
+ log(
301
+ `Not published, because the program has no storage for them: ${unbound
302
+ .map(({ list, name }) => `${list}.${name}`)
303
+ .join(", ")}.`,
304
+ );
305
+ }
306
+ log(
307
+ `${config.name} runs in Bun. OPC UA: ${server.endpoint} (${server.scalars} published values).`,
308
+ );
309
+ return {
310
+ endpoint: server.endpoint,
311
+ stop: async () => {
312
+ stopTasks();
313
+ stopTelemetry();
314
+ try {
315
+ await retention.save();
316
+ } finally {
317
+ await server.stop().catch((cause: unknown) => {
318
+ log(`The OPC UA server failed to stop cleanly: ${String(cause)}`);
319
+ });
320
+ process.off("unhandledRejection", unhandled);
321
+ }
322
+ },
323
+ };
324
+ };
@@ -0,0 +1,27 @@
1
+ import {
2
+ type Environment,
3
+ httpOptionsSchema,
4
+ type ResolvedTsplcConfig,
5
+ serverBaseUrl,
6
+ } from "@tsplc/config";
7
+ import { resolveHttpCredentials, routeBase } from "../codesys/endpoints";
8
+ import { ringSettings } from "../codesys/telemetry-settings";
9
+ import type { HttpSettings } from "./async";
10
+
11
+ /** The runtime's HTTP settings, server URL and telemetry ring, resolved as the PLC build resolves them. */
12
+ export const runtimeSettings = (
13
+ config: ResolvedTsplcConfig,
14
+ env: Environment,
15
+ ) => {
16
+ const httpOptions = config.codesys?.http ?? httpOptionsSchema.parse({});
17
+ const http: HttpSettings = {
18
+ credentials: resolveHttpCredentials(httpOptions.credentials, env),
19
+ timeoutMs: httpOptions.timeoutMs,
20
+ };
21
+ return {
22
+ http,
23
+ baseUrl: routeBase(serverBaseUrl(config, env) ?? "") || null,
24
+ telemetryCapacity: ringSettings(config.telemetry, config.debug?.trace)
25
+ .capacity,
26
+ };
27
+ };