@tsplc/compiler 0.0.0-stage → 0.2.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 (80) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -2
  3. package/backends/codesys/config.ts +54 -0
  4. package/backends/codesys/emit.ts +1063 -0
  5. package/backends/codesys/engineering.ts +88 -0
  6. package/backends/codesys/http.ts +598 -0
  7. package/backends/codesys/index.ts +12 -0
  8. package/backends/codesys/io-paths.ts +103 -0
  9. package/backends/codesys/names.ts +76 -0
  10. package/backends/codesys/numeric.ts +356 -0
  11. package/backends/codesys/plan.ts +512 -0
  12. package/backends/codesys/publication.ts +59 -0
  13. package/backends/codesys/storage.ts +63 -0
  14. package/backends/codesys/task-access.ts +118 -0
  15. package/backends/codesys/types.ts +178 -0
  16. package/backends/codesys/vendor.ts +108 -0
  17. package/dist/cli.js +1396 -0
  18. package/dist/cli.js.map +16 -0
  19. package/dist/clock.js +8 -0
  20. package/dist/clock.js.map +10 -0
  21. package/dist/codesys.js +2587 -0
  22. package/dist/codesys.js.map +22 -0
  23. package/dist/elaborate-capture.js +118 -0
  24. package/dist/elaborate-capture.js.map +10 -0
  25. package/dist/index.js +6859 -0
  26. package/dist/index.js.map +25 -0
  27. package/dist/ir.js +1888 -0
  28. package/dist/ir.js.map +22 -0
  29. package/dist/math.js +24 -0
  30. package/dist/math.js.map +10 -0
  31. package/dist/project.js +429 -0
  32. package/dist/project.js.map +11 -0
  33. package/ir/aggregates.ts +333 -0
  34. package/ir/allocation.ts +74 -0
  35. package/ir/core-model.ts +116 -0
  36. package/ir/core.ts +63 -0
  37. package/ir/declarations.ts +201 -0
  38. package/ir/diagnostics.ts +43 -0
  39. package/ir/domains.ts +96 -0
  40. package/ir/index.ts +7 -0
  41. package/ir/link.ts +176 -0
  42. package/ir/model.ts +268 -0
  43. package/ir/normalization-error.ts +10 -0
  44. package/ir/routine.ts +826 -0
  45. package/ir/scalars.ts +675 -0
  46. package/ir/types.ts +70 -0
  47. package/package.json +106 -4
  48. package/project/artifacts.ts +277 -0
  49. package/project/cli.ts +305 -0
  50. package/project/index.ts +1 -0
  51. package/project/plant.ts +437 -0
  52. package/project/project.ts +312 -0
  53. package/project/server.ts +83 -0
  54. package/src/frontend/async.ts +1060 -0
  55. package/src/frontend/blocks.ts +419 -0
  56. package/src/frontend/configuration.ts +167 -0
  57. package/src/frontend/const-functions.ts +153 -0
  58. package/src/frontend/cooperative.ts +75 -0
  59. package/src/frontend/elaborate/capture.ts +138 -0
  60. package/src/frontend/elaborate/graph.ts +94 -0
  61. package/src/frontend/elaborate/index.ts +302 -0
  62. package/src/frontend/elaborate/layouts.ts +390 -0
  63. package/src/frontend/elaborate/model.ts +177 -0
  64. package/src/frontend/elaborate/specialize.ts +2280 -0
  65. package/src/frontend/exposure.ts +147 -0
  66. package/src/frontend/module-graph.ts +63 -0
  67. package/src/frontend/promises.ts +751 -0
  68. package/src/frontend/services.ts +435 -0
  69. package/src/frontend/types.ts +578 -0
  70. package/src/frontend/typescript.ts +2442 -0
  71. package/src/index.ts +7 -0
  72. package/stdlib/clock.ts +2 -0
  73. package/stdlib/math.ts +19 -0
  74. package/types/async.d.ts +81 -0
  75. package/types/clock.d.ts +4 -0
  76. package/types/config.d.ts +2 -0
  77. package/types/data-types.d.ts +31 -0
  78. package/types/globals.d.ts +40 -0
  79. package/types/index.d.ts +111 -0
  80. package/types/plc.d.ts +5 -0
@@ -0,0 +1,312 @@
1
+ import { copyFile, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import {
4
+ buildCodesys,
5
+ codesysBuildConfig,
6
+ type CodesysPlan,
7
+ diagnoseCodesys,
8
+ emitCodesys,
9
+ ioTargets,
10
+ publicationSelectors,
11
+ planCodesys,
12
+ } from "@tsplc/compiler/codesys";
13
+ import { analyze, checkHostConfig } from "@tsplc/compiler";
14
+ import {
15
+ type Controller,
16
+ type BuildTarget,
17
+ type NormalizedConfig,
18
+ type ResolvedTsplcConfig,
19
+ compilerConfig,
20
+ loadTsplcConfig,
21
+ } from "@tsplc/config";
22
+ import { deviceTree, type ProjectTargets, loadHardware, resolveIo } from "@tsplc/typegen";
23
+ import { installLibraries } from "@tsplc/build";
24
+ import { type Diagnostic, hasErrors, normalizeModule } from "@tsplc/compiler/ir";
25
+ import { cleanArtifacts, engineeringDirectory, owned, publishArtifacts } from "./artifacts.ts";
26
+
27
+ const failure = (origin: Diagnostic["origin"], code: string, cause: unknown): Diagnostic => ({
28
+ origin,
29
+ code,
30
+ severity: "error",
31
+ message: cause instanceof Error ? cause.message : String(cause),
32
+ });
33
+
34
+ type LoadedConfig = Awaited<ReturnType<typeof loadTsplcConfig>>;
35
+
36
+ async function loadProject(
37
+ file: string,
38
+ loaded?: LoadedConfig,
39
+ buildTarget?: BuildTarget,
40
+ ): Promise<{
41
+ config?: NormalizedConfig;
42
+ configFile: string;
43
+ shared?: ResolvedTsplcConfig;
44
+ diagnostics: readonly Diagnostic[];
45
+ }> {
46
+ let configFile = resolve(file);
47
+ try {
48
+ configFile = await realpath(configFile);
49
+ const diagnostics = checkHostConfig(configFile);
50
+ if (hasErrors(diagnostics)) return { configFile, diagnostics };
51
+ const shared = (loaded ?? (await loadTsplcConfig(configFile))).config;
52
+ const root = dirname(configFile);
53
+
54
+ const config = compilerConfig(
55
+ shared,
56
+ resolveIo(shared, await loadHardware(shared, root)),
57
+ buildTarget,
58
+ );
59
+ return {
60
+ configFile,
61
+ shared,
62
+ config: { ...config, ...sourceInput(config, root) },
63
+ diagnostics,
64
+ };
65
+ } catch (cause) {
66
+ return { configFile, diagnostics: [failure("config", "PLC5003", cause)] };
67
+ }
68
+ }
69
+
70
+ /** The analyzer's entry points, resolved against the config file's directory. */
71
+ function sourceInput(
72
+ compiler: { tsconfig: string; programs: Record<string, { module: string; export: string }> },
73
+ root: string,
74
+ ) {
75
+ return {
76
+ tsconfig: resolve(root, compiler.tsconfig),
77
+ programs: Object.fromEntries(
78
+ Object.entries(compiler.programs).map(([name, entry]) => [
79
+ name,
80
+ { ...entry, module: resolve(root, entry.module) },
81
+ ]),
82
+ ),
83
+ };
84
+ }
85
+
86
+ /**
87
+ * I/O keys and publication selectors from analyzed PLC source. It ignores the
88
+ * config's own type errors, so a typo cannot switch off the types that flag it;
89
+ * it is undefined only while the source itself fails analysis.
90
+ */
91
+ export async function projectTargets(
92
+ file = "tsplc.config.ts",
93
+ options: { loaded?: LoadedConfig } = {},
94
+ ): Promise<ProjectTargets | undefined> {
95
+ const configFile = await realpath(resolve(file));
96
+ const { config } = options.loaded ?? (await loadTsplcConfig(configFile));
97
+ if (!config.compiler) return undefined;
98
+ const source = analyze({
99
+ ...sourceInput(config.compiler, dirname(configFile)),
100
+ services: config.server,
101
+ });
102
+ const core = source.module && normalizeModule(source.module).core;
103
+ return core ? { io: ioTargets(core), publication: publicationSelectors(core) } : undefined;
104
+ }
105
+
106
+ export async function checkProject(
107
+ file = "tsplc.config.ts",
108
+ options: { loaded?: LoadedConfig; buildTarget?: BuildTarget } = {},
109
+ ): Promise<{
110
+ configFile: string;
111
+ config?: NormalizedConfig;
112
+ shared?: ResolvedTsplcConfig;
113
+ plan?: CodesysPlan;
114
+ diagnostics: readonly Diagnostic[];
115
+ }> {
116
+ const loaded = await loadProject(file, options.loaded, options.buildTarget);
117
+ if (!loaded.config) {
118
+ return loaded;
119
+ }
120
+
121
+ const config = loaded.config;
122
+ if (config.target.kind !== "codesys") {
123
+ return {
124
+ ...loaded,
125
+ diagnostics: [failure("backend", "PLC7001", `Unsupported target: ${config.target.kind}`)],
126
+ };
127
+ }
128
+
129
+ const source = analyze({
130
+ tsconfig: config.tsconfig,
131
+ programs: config.programs,
132
+ services: loaded.shared?.server,
133
+ });
134
+ if (!source.module) {
135
+ return { ...loaded, diagnostics: source.diagnostics };
136
+ }
137
+ const normalized = normalizeModule(source.module);
138
+ if (!normalized.core) {
139
+ return { ...loaded, diagnostics: normalized.diagnostics };
140
+ }
141
+
142
+ const tasks = config.tasks.map((task) => ({
143
+ name: task.name,
144
+ intervalNanoseconds: task.schedule.interval.nanoseconds,
145
+ priority: task.priority,
146
+ programs: task.programs,
147
+ }));
148
+ const planned = planCodesys(normalized.core, { tasks }, config.target.options);
149
+ return {
150
+ ...loaded,
151
+ ...planned,
152
+ diagnostics: [
153
+ ...loaded.diagnostics,
154
+ ...source.diagnostics,
155
+ ...normalized.diagnostics,
156
+ ...planned.diagnostics,
157
+ ],
158
+ };
159
+ }
160
+
161
+ /** The installed libraries and fieldbus device tree a CODESYS project of this program needs. */
162
+ async function engineeringInputs(
163
+ shared: ResolvedTsplcConfig,
164
+ configFile: string,
165
+ bundle: Pick<ReturnType<typeof emitCodesys>, "ioMappings">,
166
+ frozen?: boolean,
167
+ ) {
168
+ const root = dirname(configFile);
169
+ const tree = await deviceTree(shared, await loadHardware(shared, root));
170
+ return {
171
+ libraries: await installLibraries(shared.dependencies, root, { frozen }),
172
+ // The emitted names locate mapped IO; the tree maps their channels.
173
+ deviceTree: tree && {
174
+ ...tree,
175
+ mappings: bundle.ioMappings.map(({ address, variable }) => ({ address, variable })),
176
+ },
177
+ };
178
+ }
179
+
180
+ export async function buildProject(
181
+ file = "tsplc.config.ts",
182
+ options: {
183
+ emitOnly?: boolean;
184
+ frozenLockfile?: boolean;
185
+ loaded?: LoadedConfig;
186
+ controller?: Controller;
187
+ buildTarget?: BuildTarget;
188
+ /** Resolve libraries and the device tree into `controllerConfig` even when only emitting. */
189
+ forController?: boolean;
190
+ } = {},
191
+ ): Promise<{
192
+ directory?: string;
193
+ status?: "emitted" | "vendor-compiled";
194
+ controllerConfig?: ReturnType<typeof codesysBuildConfig>;
195
+ diagnostics: readonly Diagnostic[];
196
+ }> {
197
+ let staging: string | undefined;
198
+ try {
199
+ const configFile = await realpath(resolve(file));
200
+ // Withdraw the previous success receipt before checking the new source.
201
+ // Old artifacts remain owned and intact until publication succeeds.
202
+ const previous = await owned(configFile, true);
203
+ if (previous.unknown.length) {
204
+ throw new Error(`Output contains unrelated files: ${previous.unknown.join(", ")}`);
205
+ }
206
+
207
+ const checked = await checkProject(configFile, {
208
+ loaded: options.loaded,
209
+ buildTarget: options.buildTarget,
210
+ });
211
+ if (!checked.plan || !checked.config) {
212
+ return { diagnostics: checked.diagnostics };
213
+ }
214
+ const bundle = emitCodesys(checked.plan);
215
+ if (hasErrors(bundle.diagnostics)) {
216
+ return { diagnostics: bundle.diagnostics };
217
+ }
218
+ const shared = checked.shared;
219
+ const engineering =
220
+ shared && (!options.emitOnly || options.forController)
221
+ ? await engineeringInputs(shared, configFile, bundle, options.frozenLockfile)
222
+ : undefined;
223
+ const controllerConfig = shared?.build
224
+ ? codesysBuildConfig(checked.plan, bundle, {
225
+ configFile,
226
+ sourceDir: join(previous.output, "st"),
227
+ outDir: resolve(dirname(configFile), shared.build.outDir),
228
+ controller: options.controller,
229
+ ...engineering,
230
+ })
231
+ : undefined;
232
+
233
+ await mkdir(previous.root, { recursive: true });
234
+ staging = await mkdtemp(join(previous.root, "stage-"));
235
+ const artifacts = [
236
+ ...bundle.artifacts,
237
+ { path: "mappings.json", content: `${JSON.stringify(bundle.mappings, null, 2)}\n` },
238
+ { path: "io-symbols.json", content: `${JSON.stringify(bundle.ioSymbols, null, 2)}\n` },
239
+ { path: "publication.json", content: `${JSON.stringify(bundle.publication, null, 2)}\n` },
240
+ { path: "config.json", content: `${JSON.stringify(checked.config, null, 2)}\n` },
241
+ ];
242
+ for (const artifact of artifacts) {
243
+ const path = join(staging, "st", artifact.path);
244
+ await mkdir(dirname(path), { recursive: true });
245
+ await writeFile(path, artifact.content);
246
+ }
247
+
248
+ let vendor: Awaited<ReturnType<typeof buildCodesys>> | undefined;
249
+ if (!options.emitOnly) {
250
+ // The engineering cache has its own ownership marker and survives clean.
251
+ const outDir = shared?.build
252
+ ? resolve(dirname(configFile), shared.build.outDir ?? "build")
253
+ : join(previous.root, "engineering");
254
+ await engineeringDirectory(outDir, configFile);
255
+ try {
256
+ vendor = await buildCodesys(checked.plan, bundle, {
257
+ configFile,
258
+ sourceDir: join(staging, "st"),
259
+ outDir,
260
+ controller: options.controller,
261
+ ...engineering,
262
+ });
263
+ } catch (cause) {
264
+ return { diagnostics: diagnoseCodesys(cause, bundle) };
265
+ }
266
+
267
+ const vendorArtifacts = [
268
+ ["Application.project", vendor.project],
269
+ ["Application.app", vendor.output],
270
+ ["Application.crc", vendor.checksum],
271
+ ] as const;
272
+ for (const [name, path] of vendorArtifacts) {
273
+ if (!path) continue;
274
+ const destination = join(staging, "vendor", name);
275
+ await mkdir(dirname(destination), { recursive: true });
276
+ await copyFile(path, destination);
277
+ }
278
+ }
279
+
280
+ const status = vendor ? "vendor-compiled" : "emitted";
281
+ await publishArtifacts(staging, previous, {
282
+ configFile,
283
+ status,
284
+ ...(vendor && { vendor: { application: vendor.application, tasks: vendor.tasks } }),
285
+ });
286
+ // Publication moved this directory into place; it is no longer staging.
287
+ staging = undefined;
288
+ return {
289
+ directory: previous.output,
290
+ status,
291
+ ...(controllerConfig && { controllerConfig }),
292
+ diagnostics: [...checked.diagnostics, ...bundle.diagnostics],
293
+ };
294
+ } catch (cause) {
295
+ return { diagnostics: [failure("config", "PLC5004", cause)] };
296
+ } finally {
297
+ if (staging) {
298
+ await rm(staging, { recursive: true, force: true });
299
+ }
300
+ }
301
+ }
302
+
303
+ export async function cleanProject(file = "tsplc.config.ts"): Promise<{
304
+ diagnostics: readonly Diagnostic[];
305
+ }> {
306
+ try {
307
+ await cleanArtifacts(await realpath(resolve(file)));
308
+ return { diagnostics: [] };
309
+ } catch (cause) {
310
+ return { diagnostics: [failure("config", "PLC5004", cause)] };
311
+ }
312
+ }
@@ -0,0 +1,83 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdtemp, mkdir, rm, rename } from "node:fs/promises";
3
+ import { dirname, resolve, join } from "node:path";
4
+ import { createRequire } from "node:module";
5
+ import ts from "typescript";
6
+ import type { ResolvedTsplcConfig } from "@tsplc/config";
7
+ import { typeCheckOnly } from "@tsplc/compiler";
8
+
9
+ export const resolveServerModule = (root: string, name: string) =>
10
+ name.startsWith(".") || name.startsWith("/") || existsSync(resolve(root, name))
11
+ ? resolve(root, name)
12
+ : createRequire(join(root, "package.json")).resolve(name);
13
+
14
+ const kebabCase = (name: string) =>
15
+ name
16
+ .replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4")
17
+ .replace(/[^A-Za-z0-9]+/g, "-")
18
+ .replace(/^-|-$/g, "")
19
+ .toLowerCase();
20
+
21
+ /** Compiles the host entry, which starts its own listener, into `build/server/<name>-services`. */
22
+ export const buildServer = async (config: ResolvedTsplcConfig, root: string) => {
23
+ const settings = config.server;
24
+ if (!settings?.runtime) throw new Error("Configure server.runtime to build an executable.");
25
+ const runtime = settings.runtime;
26
+ const entry = resolveServerModule(root, runtime.entry);
27
+ const windows = runtime.target
28
+ ? runtime.target.includes("windows")
29
+ : process.platform === "win32";
30
+ const outFile = resolve(
31
+ root,
32
+ "build/server",
33
+ `${kebabCase(config.name)}-services${windows ? ".exe" : ""}`,
34
+ );
35
+ const tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);
36
+ if (!tsconfig) throw new Error("Server entry requires a tsconfig.json.");
37
+ const read = ts.readConfigFile(tsconfig, ts.sys.readFile);
38
+ if (read.error) throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, "\n"));
39
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(tsconfig));
40
+ const program = ts.createProgram({
41
+ rootNames: [entry, ...parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file))],
42
+ options: { ...parsed.options, ...typeCheckOnly },
43
+ projectReferences: parsed.projectReferences,
44
+ });
45
+ const diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];
46
+ if (diagnostics.length)
47
+ throw new Error(
48
+ ts.formatDiagnosticsWithColorAndContext(diagnostics, {
49
+ getCanonicalFileName: (path) => path,
50
+ getCurrentDirectory: () => root,
51
+ getNewLine: () => "\n",
52
+ }),
53
+ );
54
+ await mkdir(dirname(outFile), { recursive: true });
55
+ // Compile beside the output so dependency resolution starts from the owning project.
56
+ const staging = await mkdtemp(join(dirname(outFile), ".tsplc-server-"));
57
+ try {
58
+ const binary = join(staging, "server");
59
+ const result = await Bun.build({
60
+ entrypoints: [entry],
61
+ env: "disable",
62
+ compile: {
63
+ outfile: binary,
64
+ ...(runtime.target ? { target: runtime.target } : {}),
65
+ autoloadDotenv: false,
66
+ autoloadBunfig: false,
67
+ autoloadTsconfig: false,
68
+ autoloadPackageJson: false,
69
+ },
70
+ });
71
+ if (!result.success) throw new AggregateError(result.logs, "Server executable build failed.");
72
+ // Bun names a Windows executable itself.
73
+ await rename(windows ? `${binary}.exe` : binary, outFile);
74
+ return {
75
+ server: {
76
+ executable: outFile,
77
+ target: runtime.target ?? `bun-${process.platform}-${process.arch}`,
78
+ },
79
+ };
80
+ } finally {
81
+ await rm(staging, { recursive: true, force: true });
82
+ }
83
+ };