@tsplc/compiler 0.2.17 → 0.2.18

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -1,17 +1,27 @@
1
1
  import ts from "typescript";
2
- import { dirname, join, relative, resolve } from "node:path";
2
+ import { dirname, join, resolve } from "node:path";
3
3
  import {
4
- error,
5
- type Constant,
6
- type Diagnostic,
7
- type SourceSpan,
8
- type TypeId,
4
+ error,
5
+ type Constant,
6
+ type Diagnostic,
7
+ type SourceSpan,
8
+ type TypeId,
9
9
  } from "@tsplc/compiler/ir";
10
10
  import { runtimeSources } from "../module-graph.ts";
11
- import { copied, from, joined, type Mapped, type Positions } from "../positions.ts";
11
+ import { inSdk, namesSdk } from "../sdk.ts";
12
+ import {
13
+ copied,
14
+ from,
15
+ joined,
16
+ type Mapped,
17
+ type Positions,
18
+ } from "../positions.ts";
12
19
  import { captureGraph, type CapturedValue } from "./graph.ts";
20
+ import { importPath } from "./imports.ts";
13
21
  import { Model, type Root } from "./model.ts";
14
- import { closingBrace, setterName, Specializer, SpecializeError } from "./specialize.ts";
22
+ import { closingBrace, Specializer } from "./specialize.ts";
23
+ import { setterName } from "./storage.ts";
24
+ import { SpecializeError } from "./values.ts";
15
25
 
16
26
  /** Directory of the modules elaboration generates, beside the entry module. */
17
27
  const generatedDirectory = ".tsplc";
@@ -20,101 +30,138 @@ const generatedDirectory = ".tsplc";
20
30
  * A module the compiled program keeps as written: only types, enums, constants and the service
21
31
  * client. Everything else is plain TypeScript that elaboration compiles from its setup graph.
22
32
  */
23
- const keptModule = (source: ts.SourceFile, sdk: string): boolean =>
24
- source.statements.every((statement) => {
25
- if (
26
- ts.isImportDeclaration(statement) ||
27
- ts.isExportDeclaration(statement) ||
28
- ts.isInterfaceDeclaration(statement) ||
29
- ts.isTypeAliasDeclaration(statement) ||
30
- ts.isEnumDeclaration(statement)
31
- )
32
- return true;
33
- if (!ts.isVariableStatement(statement)) return false;
34
- return statement.declarationList.declarations.every(
35
- (declaration) => declaration.initializer && constantInitializer(declaration.initializer, sdk),
36
- );
37
- });
33
+ const keptModule = (
34
+ source: ts.SourceFile,
35
+ checker: ts.TypeChecker,
36
+ sdk: string,
37
+ ): boolean =>
38
+ source.statements.every((statement) => {
39
+ if (
40
+ ts.isImportDeclaration(statement) ||
41
+ ts.isExportDeclaration(statement) ||
42
+ ts.isInterfaceDeclaration(statement) ||
43
+ ts.isTypeAliasDeclaration(statement) ||
44
+ ts.isEnumDeclaration(statement)
45
+ ) {
46
+ return true;
47
+ }
48
+ if (!ts.isVariableStatement(statement)) {
49
+ return false;
50
+ }
51
+ return statement.declarationList.declarations.every(
52
+ (declaration) =>
53
+ declaration.initializer &&
54
+ constantInitializer(declaration.initializer, checker, sdk),
55
+ );
56
+ });
38
57
 
39
- const constantInitializer = (node: ts.Expression, sdk: string): boolean => {
40
- if (
41
- ts.isNumericLiteral(node) ||
42
- ts.isStringLiteral(node) ||
43
- ts.isNoSubstitutionTemplateLiteral(node) ||
44
- ts.isBigIntLiteral(node) ||
45
- node.kind === ts.SyntaxKind.TrueKeyword ||
46
- node.kind === ts.SyntaxKind.FalseKeyword
47
- )
48
- return true;
49
- if (ts.isPrefixUnaryExpression(node)) return constantInitializer(node.operand, sdk);
50
- if (
51
- ts.isAsExpression(node) ||
52
- ts.isSatisfiesExpression(node) ||
53
- ts.isParenthesizedExpression(node)
54
- )
55
- return constantInitializer(node.expression, sdk);
56
- if (ts.isPropertyAccessExpression(node)) return ts.isIdentifier(node.expression);
57
- if (ts.isIdentifier(node)) return true;
58
- if (ts.isObjectLiteralExpression(node))
59
- return node.properties.every(
60
- (property) =>
61
- (ts.isPropertyAssignment(property) && constantInitializer(property.initializer, sdk)) ||
62
- ts.isShorthandPropertyAssignment(property),
63
- );
64
- if (ts.isArrayLiteralExpression(node))
65
- return node.elements.every((element) => constantInitializer(element, sdk));
66
- if (ts.isCallExpression(node))
67
- return ts.isIdentifier(node.expression) && node.expression.text === "createServiceClient";
68
- return false;
58
+ const constantInitializer = (
59
+ node: ts.Expression,
60
+ checker: ts.TypeChecker,
61
+ sdk: string,
62
+ ): boolean => {
63
+ if (
64
+ ts.isNumericLiteral(node) ||
65
+ ts.isStringLiteral(node) ||
66
+ ts.isNoSubstitutionTemplateLiteral(node) ||
67
+ ts.isBigIntLiteral(node) ||
68
+ node.kind === ts.SyntaxKind.TrueKeyword ||
69
+ node.kind === ts.SyntaxKind.FalseKeyword
70
+ ) {
71
+ return true;
72
+ }
73
+ if (ts.isPrefixUnaryExpression(node)) {
74
+ return constantInitializer(node.operand, checker, sdk);
75
+ }
76
+ if (
77
+ ts.isAsExpression(node) ||
78
+ ts.isSatisfiesExpression(node) ||
79
+ ts.isParenthesizedExpression(node)
80
+ ) {
81
+ return constantInitializer(node.expression, checker, sdk);
82
+ }
83
+ if (ts.isPropertyAccessExpression(node)) {
84
+ return ts.isIdentifier(node.expression);
85
+ }
86
+ if (ts.isIdentifier(node)) {
87
+ return true;
88
+ }
89
+ if (ts.isObjectLiteralExpression(node)) {
90
+ return node.properties.every(
91
+ (property) =>
92
+ (ts.isPropertyAssignment(property) &&
93
+ constantInitializer(property.initializer, checker, sdk)) ||
94
+ ts.isShorthandPropertyAssignment(property),
95
+ );
96
+ }
97
+ if (ts.isArrayLiteralExpression(node)) {
98
+ return node.elements.every((element) =>
99
+ constantInitializer(element, checker, sdk),
100
+ );
101
+ }
102
+ if (ts.isCallExpression(node)) {
103
+ return namesSdk(checker, sdk, node.expression, "createServiceClient");
104
+ }
105
+ return false;
69
106
  };
70
107
 
71
108
  /** Whether the program is plain TypeScript: classes with constructors, or setup code building state. */
72
- const needsElaboration = (sources: readonly ts.SourceFile[], sdk: string): boolean =>
73
- sources.some(
74
- (source) =>
75
- !source.isDeclarationFile &&
76
- !source.fileName.startsWith(`${dirname(sdk)}/`) &&
77
- !keptModule(source, sdk) &&
78
- source.statements.some(
79
- (statement) =>
80
- ts.isClassDeclaration(statement) &&
81
- !statement.heritageClauses?.some((clause) =>
82
- clause.types.some((type) => type.expression.getText().startsWith("FunctionBlock")),
83
- ),
84
- ),
85
- );
86
-
87
- const importPath = (from: string, to: string): string => {
88
- const path = relative(dirname(from), to)
89
- .replace(/\\/g, "/")
90
- .replace(/\.tsx?$/, "");
91
- return path.startsWith("./") || path.startsWith("../") ? path : `./${path}`;
92
- };
109
+ const needsElaboration = (
110
+ sources: readonly ts.SourceFile[],
111
+ kept: (file: string) => boolean,
112
+ ): boolean =>
113
+ sources.some(
114
+ (source) =>
115
+ !kept(source.fileName) &&
116
+ source.statements.some(
117
+ (statement) =>
118
+ ts.isClassDeclaration(statement) &&
119
+ !statement.heritageClauses?.some((clause) =>
120
+ clause.types.some((type) =>
121
+ type.expression.getText().startsWith("FunctionBlock"),
122
+ ),
123
+ ),
124
+ ),
125
+ );
93
126
 
94
- type Folded = { path: string; value: Constant; type?: TypeId; span: SourceSpan };
127
+ interface Folded {
128
+ path: string;
129
+ value: Constant;
130
+ type?: TypeId;
131
+ span: SourceSpan;
132
+ }
95
133
 
96
134
  /**
97
135
  * A folded primitive as a PLC constant, with its scalar type: the IEC width its declaration
98
136
  * names, or the one a TypeScript number of that value gets. Strings, often enum members, have none.
99
137
  */
100
138
  const constant = (
101
- value: CapturedValue,
102
- iec: string | undefined,
139
+ value: CapturedValue,
140
+ iec: string | undefined,
103
141
  ): Pick<Folded, "value" | "type"> | undefined => {
104
- switch (value.kind) {
105
- case "number":
106
- return Number.isInteger(value.value)
107
- ? { value: { kind: "integer", value: String(value.value) }, type: iec ?? "DINT" }
108
- : { value: { kind: "float", value: value.value }, type: iec ?? "LREAL" };
109
- case "bigint":
110
- return { value: { kind: "integer", value: value.value }, type: iec ?? "LINT" };
111
- case "boolean":
112
- return { value: { kind: "bool", value: value.value }, type: "BOOL" };
113
- case "string":
114
- return { value: { kind: "string", value: value.value } };
115
- default:
116
- return undefined;
117
- }
142
+ switch (value.kind) {
143
+ case "number":
144
+ return Number.isInteger(value.value)
145
+ ? {
146
+ value: { kind: "integer", value: String(value.value) },
147
+ type: iec ?? "DINT",
148
+ }
149
+ : {
150
+ value: { kind: "float", value: value.value },
151
+ type: iec ?? "LREAL",
152
+ };
153
+ case "bigint":
154
+ return {
155
+ value: { kind: "integer", value: value.value },
156
+ type: iec ?? "LINT",
157
+ };
158
+ case "boolean":
159
+ return { value: { kind: "bool", value: value.value }, type: "BOOL" };
160
+ case "string":
161
+ return { value: { kind: "string", value: value.value } };
162
+ default:
163
+ return undefined;
164
+ }
118
165
  };
119
166
 
120
167
  /**
@@ -122,255 +169,312 @@ const constant = (
122
169
  * the objects setup built. The result is tsPLC dialect source the rest of the compiler reads.
123
170
  */
124
171
  export const lowerElaboration = (
125
- program: ts.Program,
126
- sdk: string,
127
- entries: Readonly<Record<string, { module: string; export: string }>>,
128
- root: string,
129
- positions: Positions,
172
+ program: ts.Program,
173
+ sdk: string,
174
+ entries: Readonly<Record<string, { module: string; export: string }>>,
175
+ root: string,
176
+ positions: Positions,
130
177
  ): {
131
- sources: Map<string, Mapped>;
132
- diagnostics: Diagnostic[];
133
- /** Routines specialized from class methods, by `<entry file>:<routine>`. */
134
- origins: Map<string, { name: string; instance?: string }>;
135
- folded: Folded[];
136
- /** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
137
- literals: Map<string, Record<string, string>>;
178
+ sources: Map<string, Mapped>;
179
+ diagnostics: Diagnostic[];
180
+ /** Routines specialized from class methods, by `<entry file>:<routine>`. */
181
+ origins: Map<string, { name: string; instance?: string }>;
182
+ folded: Folded[];
183
+ /** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
184
+ literals: Map<string, Record<string, string>>;
138
185
  } => {
139
- const sources = new Map<string, Mapped>();
140
- const diagnostics: Diagnostic[] = [];
141
- const origins = new Map<string, { name: string; instance?: string }>();
142
- const folded: Folded[] = [];
143
- const literals = new Map<string, Record<string, string>>();
144
- const result = { sources, diagnostics, origins, folded, literals };
145
- const runtime = runtimeSources(program).filter(
146
- (source) => !source.isDeclarationFile && !source.fileName.startsWith(`${dirname(sdk)}/`),
147
- );
148
- if (!needsElaboration(runtime, sdk)) return result;
149
- const programEntries = Object.values(entries);
150
- if (programEntries.length !== 1) {
151
- diagnostics.push(error("PLC1001", "A plain TypeScript program has one entry function."));
152
- return result;
153
- }
154
- const [entry] = programEntries as [{ module: string; export: string }];
155
- const entryFile = resolve(root, entry.module).replace(/\\/g, "/");
156
- const entrySource = program.getSourceFile(entryFile);
157
- if (!entrySource) {
158
- diagnostics.push(error("PLC1001", `${entry.module} is not part of the program.`));
159
- return result;
160
- }
161
- const checker = program.getTypeChecker();
162
- const kept = new Set(
163
- runtime.filter((source) => keptModule(source, sdk)).map((source) => source.fileName),
164
- );
165
- const isKept = (file: string) => kept.has(file);
166
- const directory = join(dirname(entryFile), generatedDirectory).replace(/\\/g, "/");
167
- const rootModule = (item: Root) => `${directory}/${item.name}.ts`;
186
+ const sources = new Map<string, Mapped>();
187
+ const diagnostics: Diagnostic[] = [];
188
+ const origins = new Map<string, { name: string; instance?: string }>();
189
+ const folded: Folded[] = [];
190
+ const literals = new Map<string, Record<string, string>>();
191
+ const result = { sources, diagnostics, origins, folded, literals };
192
+ const runtime = runtimeSources(program).filter(
193
+ (source) => !source.isDeclarationFile && !inSdk(sdk, source.fileName),
194
+ );
195
+ const checker = program.getTypeChecker();
196
+ const kept = new Set(
197
+ runtime
198
+ .filter((source) => keptModule(source, checker, sdk))
199
+ .map((source) => source.fileName),
200
+ );
201
+ const isKept = (file: string) => kept.has(file);
202
+ if (!needsElaboration(runtime, isKept)) {
203
+ return result;
204
+ }
205
+ const [entry, ...otherEntries] = Object.values(entries);
206
+ if (!entry || otherEntries.length) {
207
+ diagnostics.push(
208
+ error("PLC1001", "A plain TypeScript program has one entry function."),
209
+ );
210
+ return result;
211
+ }
212
+ const entryFile = resolve(root, entry.module).replace(/\\/g, "/");
213
+ const entrySource = program.getSourceFile(entryFile);
214
+ if (!entrySource) {
215
+ diagnostics.push(
216
+ error("PLC1001", `${entry.module} is not part of the program.`),
217
+ );
218
+ return result;
219
+ }
220
+ const directory = join(dirname(entryFile), generatedDirectory).replace(
221
+ /\\/g,
222
+ "/",
223
+ );
224
+ const rootModule = (item: Root) => `${directory}/${item.name}.ts`;
168
225
 
169
- try {
170
- const graph = captureGraph(entryFile, runtime);
171
- const model = new Model(graph, checker, program, entryFile);
172
- const specializer = new Specializer(model, checker, runtime, isKept, rootModule);
173
- const main = findEntry(entrySource, entry.export);
174
- const body = specializer.entry(main);
226
+ try {
227
+ const graph = captureGraph(entryFile, runtime);
228
+ const model = new Model(graph, checker, program, entryFile);
229
+ const specializer = new Specializer(
230
+ model,
231
+ checker,
232
+ sdk,
233
+ runtime,
234
+ isKept,
235
+ rootModule,
236
+ );
237
+ const main = findEntry(entrySource, entry.export);
238
+ const body = specializer.entry(main);
175
239
 
176
- // Exported data the hardware, HMI and server address is stored whether or not code reads it.
177
- for (const item of model.roots)
178
- if (item.exported && !isKept(item.file) && item.file === entryFile) specializer.use(item);
240
+ // Exported data the hardware, HMI and server address is stored whether or not code reads it.
241
+ for (const item of model.roots) {
242
+ if (item.exported && !isKept(item.file) && item.file === entryFile) {
243
+ specializer.storage.use(item);
244
+ }
245
+ }
179
246
 
180
- const typesFile = `${directory}/types.ts`;
181
- const storage = new Map<Root, Mapped[]>();
182
- for (const item of specializer.roots) {
183
- const value = model.rootValues.get(item)!;
184
- const node = model.node(value)!;
185
- const lines: Mapped[] = [];
186
- // Other modules can't assign an imported binding, so each global comes with a setter.
187
- const global = (
188
- name: string,
189
- layout: string,
190
- initial: string,
191
- declaration: ts.Node = item.declaration,
192
- ) =>
193
- lines.push(
194
- from(declaration, `export let ${name}: ${layout} = ${initial};`),
195
- from(
196
- declaration,
197
- `export function ${setterName(name)}(value: ${layout}): void { ${name} = value; }`,
198
- ),
199
- );
200
- if (specializer.flattened(item)) {
201
- const captured = node.captured;
202
- if (captured.kind === "instance") {
203
- const declaration = model.classOf(node);
204
- for (const [name, layout] of specializer.instanceFields(node))
205
- global(
206
- name,
207
- layout,
208
- specializer.instanceFieldInitializer(node, name, layout),
209
- model.member(declaration, name),
210
- );
211
- } else if (captured.kind === "object") {
212
- for (const [name, field] of Object.entries(captured.fields)) {
213
- const inner = model.node(field);
214
- const declared = node.type && model.fieldType(node.type, name, captured);
215
- if (!declared) continue;
216
- const stored = item.exported || specializer.stored(node, name);
217
- if (!stored && !inner) continue;
218
- const layout =
219
- inner && !item.exported
220
- ? specializer.storageType(inner)
221
- : specializer.layouts.declaredText(
222
- node.type?.getProperty(name)?.valueDeclaration,
223
- declared,
224
- field,
225
- name.charAt(0).toUpperCase() + name.slice(1),
226
- );
227
- if (!layout) continue;
228
- global(
229
- name,
230
- layout,
231
- specializer.valueText(field, declared, layout),
232
- node.type?.getProperty(name)?.valueDeclaration,
233
- );
234
- }
235
- }
236
- } else {
237
- const declared = checker.getTypeAtLocation(item.declaration.name);
238
- const layout = specializer.layouts.declaredText(item.declaration, declared, value);
239
- global(item.name, layout, specializer.valueText(value, declared, layout));
240
- }
241
- storage.set(item, lines);
242
- }
247
+ // Writing the globals declares the types they use, so they come before the types module.
248
+ const globals = new Map<Root, Mapped[]>();
249
+ for (const item of specializer.storage.roots) {
250
+ globals.set(item, storageGlobals(specializer, item));
251
+ }
252
+ const typesFile = `${directory}/types.ts`;
253
+ const typeImports = (file: string) => [
254
+ ...specializer.layouts.imports.lines(file, "import"),
255
+ ...specializer.layouts.typeImports.lines(file, "import type"),
256
+ ];
257
+ const enums = specializer.layouts.enumNames;
258
+ const interfaces = [...specializer.layouts.declarations.keys()].filter(
259
+ (name) => !enums.includes(name),
260
+ );
261
+ const importTypes = (file: string) => [
262
+ ...(enums.length
263
+ ? [
264
+ `import { ${enums.join(", ")} } from "${importPath(file, typesFile)}";`,
265
+ ]
266
+ : []),
267
+ ...(interfaces.length
268
+ ? [
269
+ `import type { ${interfaces.join(", ")} } from "${importPath(file, typesFile)}";`,
270
+ ]
271
+ : []),
272
+ ];
273
+ sources.set(
274
+ typesFile,
275
+ joined(
276
+ [
277
+ ...typeImports(typesFile),
278
+ ...specializer.layouts.declarations.values(),
279
+ ],
280
+ "\n",
281
+ ),
282
+ );
283
+ for (const [item, lines] of globals) {
284
+ const file = rootModule(item);
285
+ const imports = [...typeImports(file), ...importTypes(file)];
286
+ sources.set(
287
+ file,
288
+ joined(
289
+ [...imports.map((line) => from(item.declaration, line)), ...lines],
290
+ "\n",
291
+ ),
292
+ );
293
+ }
294
+
295
+ const header = [
296
+ ...typeImports(entryFile),
297
+ ...importTypes(entryFile),
298
+ ...specializer.imports.lines(entryFile),
299
+ ];
300
+ sources.set(
301
+ entryFile,
302
+ joined(
303
+ [
304
+ ...header.map((line) => from(main, line)),
305
+ ...specializer.expressions.tableDeclarations,
306
+ ...specializer.routines,
307
+ from(main, `export function ${entry.export}(): void {`),
308
+ ...body,
309
+ from(closingBrace(main), "}"),
310
+ ],
311
+ "\n",
312
+ ),
313
+ );
314
+ for (const [name, origin] of specializer.origins) {
315
+ origins.set(`${entryFile}:${name}`, origin);
316
+ }
317
+ for (const { name, members } of specializer.layouts.literalEnums) {
318
+ literals.set(`${typesFile}:${name}`, members);
319
+ }
320
+ for (const item of specializer.storage.folded()) {
321
+ const known = constant(item.value, item.iec);
322
+ if (known) {
323
+ folded.push({
324
+ path: item.path,
325
+ ...known,
326
+ span: positions.node(item.declaration),
327
+ });
328
+ }
329
+ }
330
+ // The plain modules now live in the generated code; keep only their types for type importers.
331
+ for (const source of runtime) {
332
+ if (source.fileName !== entryFile && !isKept(source.fileName)) {
333
+ sources.set(source.fileName, typesOnly(source));
334
+ }
335
+ }
336
+ } catch (cause) {
337
+ diagnostics.push(failure(cause, positions));
338
+ }
339
+ return result;
340
+ };
341
+
342
+ /**
343
+ * The globals of a root's storage module: one per stored field of a record or instance, or the
344
+ * root itself. Other modules can't assign an imported binding, so each global comes with a setter.
345
+ */
346
+ const storageGlobals = (specializer: Specializer, item: Root): Mapped[] => {
347
+ const { model, checker, layouts, storage, initializers } = specializer;
348
+ const lines: Mapped[] = [];
349
+ const global = (
350
+ name: string,
351
+ layout: string,
352
+ initial: string,
353
+ declaration: ts.Node | undefined,
354
+ ) => {
355
+ const origin = declaration ?? item.declaration;
356
+ lines.push(
357
+ from(origin, `export let ${name}: ${layout} = ${initial};`),
358
+ from(
359
+ origin,
360
+ `export function ${setterName(name)}(value: ${layout}): void { ${name} = value; }`,
361
+ ),
362
+ );
363
+ };
364
+ const node = model.node(item.value);
365
+ if (!node || !storage.flattened(item)) {
366
+ const declared = checker.getTypeAtLocation(item.declaration.name);
367
+ const layout = layouts.declaredText(item.declaration, declared, item.value);
368
+ global(
369
+ item.name,
370
+ layout,
371
+ initializers.valueText(item.value, declared, layout),
372
+ item.declaration,
373
+ );
374
+ return lines;
375
+ }
376
+ const captured = node.captured;
377
+ if (captured.kind === "instance") {
378
+ const declaration = model.classOf(node);
379
+ for (const [name, layout] of storage.instanceFields(node)) {
380
+ global(
381
+ name,
382
+ layout,
383
+ initializers.instanceFieldInitializer(node, name, layout),
384
+ model.member(declaration, name),
385
+ );
386
+ }
387
+ } else if (captured.kind === "object") {
388
+ for (const [name, field] of Object.entries(captured.fields)) {
389
+ const inner = model.node(field);
390
+ const declared = model.capturedFieldType(node, name);
391
+ if (!declared) {
392
+ continue;
393
+ }
394
+ const stored = item.exported || storage.stored(node, name);
395
+ if (!stored && !inner) {
396
+ continue;
397
+ }
398
+ const property = node.type?.getProperty(name)?.valueDeclaration;
399
+ const layout =
400
+ inner && !item.exported
401
+ ? storage.storageType(inner)
402
+ : layouts.declaredText(
403
+ property,
404
+ declared,
405
+ field,
406
+ name.charAt(0).toUpperCase() + name.slice(1),
407
+ );
408
+ if (!layout) {
409
+ continue;
410
+ }
411
+ global(
412
+ name,
413
+ layout,
414
+ initializers.valueText(field, declared, layout),
415
+ property,
416
+ );
417
+ }
418
+ }
419
+ return lines;
420
+ };
243
421
 
244
- const typeImports = (file: string) => [
245
- ...[...specializer.layouts.imports].map(
246
- ([module, names]) =>
247
- `import { ${[...names].join(", ")} } from "${importPath(file, module)}";`,
248
- ),
249
- ...[...specializer.layouts.typeImports].map(
250
- ([module, names]) =>
251
- `import type { ${[...names].join(", ")} } from "${importPath(file, module)}";`,
252
- ),
253
- ];
254
- const enums = specializer.layouts.enumNames;
255
- const interfaces = [...specializer.layouts.declarations.keys()].filter(
256
- (name) => !enums.includes(name),
257
- );
258
- const importTypes = (file: string) => [
259
- ...(enums.length
260
- ? [`import { ${enums.join(", ")} } from "${importPath(file, typesFile)}";`]
261
- : []),
262
- ...(interfaces.length
263
- ? [`import type { ${interfaces.join(", ")} } from "${importPath(file, typesFile)}";`]
264
- : []),
265
- ];
266
- sources.set(
267
- typesFile,
268
- joined([...typeImports(typesFile), ...specializer.layouts.declarations.values()], "\n"),
269
- );
270
- for (const [item, lines] of storage) {
271
- const file = rootModule(item);
272
- const imports = [...typeImports(file), ...importTypes(file)];
273
- sources.set(
274
- file,
275
- joined([...imports.map((line) => from(item.declaration, line)), ...lines], "\n"),
276
- );
277
- }
422
+ /** A plain module reduced to the types other modules may import from it. */
423
+ const typesOnly = (source: ts.SourceFile): Mapped =>
424
+ joined(
425
+ [
426
+ ...source.statements
427
+ .filter(
428
+ (statement) =>
429
+ ts.isInterfaceDeclaration(statement) ||
430
+ ts.isTypeAliasDeclaration(statement) ||
431
+ (ts.isImportDeclaration(statement) &&
432
+ statement.importClause?.isTypeOnly),
433
+ )
434
+ .map(copied),
435
+ "export {};",
436
+ ],
437
+ "\n",
438
+ );
278
439
 
279
- const header = [
280
- ...typeImports(entryFile),
281
- ...importTypes(entryFile),
282
- ...[...specializer.namespaces].map(
283
- ([name, file]) => `import * as ${name} from "${importPath(entryFile, file)}";`,
284
- ),
285
- ...[...specializer.imports].map(
286
- ([file, names]) =>
287
- `import { ${[...names].join(", ")} } from "${importPath(entryFile, file)}";`,
288
- ),
289
- ...(specializer.sdkImports.size
290
- ? [`import { ${[...specializer.sdkImports].join(", ")} } from "@tsplc/compiler/clock";`]
291
- : []),
292
- ...(specializer.telemetryImport
293
- ? [`import { telemetry } from "@tsplc/compiler/telemetry";`]
294
- : []),
295
- ...(specializer.typeImports.size
296
- ? [`import { ${[...specializer.typeImports].join(", ")} } from "@tsplc/compiler/types";`]
297
- : []),
298
- ];
299
- sources.set(
300
- entryFile,
301
- joined(
302
- [
303
- ...header.map((line) => from(main, line)),
304
- ...specializer.tableDeclarations,
305
- ...specializer.routines,
306
- from(main, `export function ${entry.export}(): void {`),
307
- ...body,
308
- from(closingBrace(main), "}"),
309
- ],
310
- "\n",
311
- ),
312
- );
313
- for (const [name, origin] of specializer.origins) origins.set(`${entryFile}:${name}`, origin);
314
- for (const { name, members } of specializer.layouts.literalEnums)
315
- literals.set(`${typesFile}:${name}`, members);
316
- for (const item of specializer.folded()) {
317
- const known = constant(item.value, item.iec);
318
- if (known) folded.push({ path: item.path, ...known, span: positions.node(item.declaration) });
319
- }
320
- // The plain modules now live in the generated code; keep only their types for type importers.
321
- for (const source of runtime)
322
- if (source.fileName !== entryFile && !isKept(source.fileName))
323
- sources.set(
324
- source.fileName,
325
- joined(
326
- [
327
- ...source.statements
328
- .filter(
329
- (statement) =>
330
- ts.isInterfaceDeclaration(statement) ||
331
- ts.isTypeAliasDeclaration(statement) ||
332
- (ts.isImportDeclaration(statement) && statement.importClause?.isTypeOnly),
333
- )
334
- .map(copied),
335
- "export {};",
336
- ],
337
- "\n",
338
- ),
339
- );
340
- } catch (cause) {
341
- if (cause instanceof SpecializeError)
342
- diagnostics.push(error("PLC1010", cause.message, positions.node(cause.node)));
343
- else
344
- diagnostics.push(
345
- error(
346
- "PLC1010",
347
- cause instanceof Error
348
- ? process.env.TSPLC_DEBUG
349
- ? String(cause.stack)
350
- : cause.message
351
- : String(cause),
352
- ),
353
- );
354
- }
355
- return result;
440
+ /** An elaboration failure as a diagnostic, at the node specialization stopped at when it knows one. */
441
+ const failure = (cause: unknown, positions: Positions): Diagnostic => {
442
+ if (cause instanceof SpecializeError) {
443
+ return error("PLC1010", cause.message, positions.node(cause.node));
444
+ }
445
+ if (!(cause instanceof Error)) {
446
+ return error("PLC1010", String(cause));
447
+ }
448
+ return error(
449
+ "PLC1010",
450
+ process.env.TSPLC_DEBUG ? String(cause.stack) : cause.message,
451
+ );
356
452
  };
357
453
 
358
454
  const findEntry = (
359
- source: ts.SourceFile,
360
- name: string,
455
+ source: ts.SourceFile,
456
+ name: string,
361
457
  ): ts.FunctionDeclaration | ts.ArrowFunction => {
362
- for (const statement of source.statements) {
363
- if (ts.isFunctionDeclaration(statement) && statement.name?.text === name && statement.body)
364
- return statement;
365
- if (ts.isVariableStatement(statement))
366
- for (const declaration of statement.declarationList.declarations)
367
- if (
368
- ts.isIdentifier(declaration.name) &&
369
- declaration.name.text === name &&
370
- declaration.initializer &&
371
- ts.isArrowFunction(declaration.initializer)
372
- )
373
- return declaration.initializer;
374
- }
375
- throw new Error(`${source.fileName} exports no function ${name}.`);
458
+ for (const statement of source.statements) {
459
+ if (
460
+ ts.isFunctionDeclaration(statement) &&
461
+ statement.name?.text === name &&
462
+ statement.body
463
+ ) {
464
+ return statement;
465
+ }
466
+ if (ts.isVariableStatement(statement)) {
467
+ for (const declaration of statement.declarationList.declarations) {
468
+ if (
469
+ ts.isIdentifier(declaration.name) &&
470
+ declaration.name.text === name &&
471
+ declaration.initializer &&
472
+ ts.isArrowFunction(declaration.initializer)
473
+ ) {
474
+ return declaration.initializer;
475
+ }
476
+ }
477
+ }
478
+ }
479
+ throw new Error(`${source.fileName} exports no function ${name}.`);
376
480
  };