@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,95 @@
1
+ import { identityDigest } from "@tsplc/compiler/ir";
2
+ import ts from "typescript";
3
+ import { modulePath } from "./lowering-key";
4
+
5
+ /**
6
+ * Names for what lowering generates, each a fixed function of the source node it stands for: its
7
+ * module, the declarations around it, and its ordinal among the nodes with the same key in the
8
+ * innermost one. An edit elsewhere then never renames it, so an online change finds its state
9
+ * where it left it; counting generated objects across the program renamed them all.
10
+ */
11
+ export class GeneratedNames {
12
+ constructor(private readonly root: string) {}
13
+
14
+ /** `base` followed by the digest of `node`'s identity. */
15
+ name(base: string, node: ts.Node): string {
16
+ return `${base}_${identityDigest(this.identity(node))}`;
17
+ }
18
+
19
+ private identity(node: ts.Node): string {
20
+ const source = node.getSourceFile();
21
+ const module = modulePath(this.root, source.fileName);
22
+ const scopes = enclosingDeclarations(node);
23
+ const scope = scopes.at(-1)?.node ?? source;
24
+ const key = nodeKey(node, source);
25
+ const ordinal = sameKey(scope, key, source).indexOf(node);
26
+ return [
27
+ module,
28
+ ...scopes.map((declaration) => declaration.name),
29
+ `${key}#${ordinal}`,
30
+ ].join("\0");
31
+ }
32
+ }
33
+
34
+ /** A call is told apart by its callee, a declaration by its name, anything else by its syntax. */
35
+ const nodeKey = (node: ts.Node, source: ts.SourceFile): string => {
36
+ if (ts.isCallExpression(node)) {
37
+ return `call ${node.expression.getText(source)}`;
38
+ }
39
+ const name = declarationName(node);
40
+ return name === undefined
41
+ ? ts.SyntaxKind[node.kind]
42
+ : `${ts.SyntaxKind[node.kind]} ${name}`;
43
+ };
44
+
45
+ /** The nodes under `scope` with `key`, in source order. */
46
+ const sameKey = (
47
+ scope: ts.Node,
48
+ key: string,
49
+ source: ts.SourceFile,
50
+ ): ts.Node[] => {
51
+ const found: ts.Node[] = [];
52
+ const visit = (node: ts.Node) => {
53
+ if (nodeKey(node, source) === key) {
54
+ found.push(node);
55
+ }
56
+ ts.forEachChild(node, visit);
57
+ };
58
+ ts.forEachChild(scope, visit);
59
+ return found;
60
+ };
61
+
62
+ const declarationName = (node: ts.Node): string | undefined => {
63
+ if (
64
+ (ts.isClassDeclaration(node) ||
65
+ ts.isFunctionDeclaration(node) ||
66
+ ts.isMethodDeclaration(node) ||
67
+ ts.isPropertyDeclaration(node) ||
68
+ ts.isGetAccessorDeclaration(node) ||
69
+ ts.isSetAccessorDeclaration(node) ||
70
+ ts.isVariableDeclaration(node) ||
71
+ ts.isInterfaceDeclaration(node) ||
72
+ ts.isTypeAliasDeclaration(node)) &&
73
+ node.name &&
74
+ (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name))
75
+ ) {
76
+ return node.name.text;
77
+ }
78
+ if (ts.isConstructorDeclaration(node)) {
79
+ return "constructor";
80
+ }
81
+ return undefined;
82
+ };
83
+
84
+ /** The named declarations around `node`, outermost first. */
85
+ const enclosingDeclarations = (
86
+ node: ts.Node,
87
+ ): { name: string; node: ts.Node }[] => {
88
+ const parent = node.parent;
89
+ if (!parent || ts.isSourceFile(parent)) {
90
+ return [];
91
+ }
92
+ const name = declarationName(parent);
93
+ const outer = enclosingDeclarations(parent);
94
+ return name === undefined ? outer : [...outer, { name, node: parent }];
95
+ };
@@ -0,0 +1,382 @@
1
+ import {
2
+ type Constant,
3
+ calendarLiteral,
4
+ defaultValue,
5
+ durationLiteral,
6
+ type Expression,
7
+ isRadixLiteral,
8
+ parseInteger,
9
+ } from "@tsplc/compiler/ir";
10
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
11
+ import { elementaryFunctions, type UnaryOperator } from "@tsplc/iec/arithmetic";
12
+ import ts from "typescript";
13
+ import type { ExpressionLowering } from "./expressions";
14
+ import { numericLiteral } from "./types";
15
+
16
+ type Conversion = Extract<Expression, { kind: "convert" }>["policy"];
17
+ type Arithmetic = Pick<
18
+ Extract<Expression, { kind: "binary" }>,
19
+ "operator" | "policy"
20
+ >;
21
+
22
+ /** The SDK's TIME constructors, such as `ms`, by the nanoseconds one unit of each is. */
23
+ export const durationScales: ReadonlyMap<string, bigint> = new Map([
24
+ ["ms", nanosecondsPerMillisecond],
25
+ ["seconds", 1000n * nanosecondsPerMillisecond],
26
+ ["minutes", 60_000n * nanosecondsPerMillisecond],
27
+ ]);
28
+ const calendarTypes = new Map<string, string>([
29
+ ["date", "DATE"],
30
+ ["timeOfDay", "TIME_OF_DAY"],
31
+ ["dateAndTime", "DATE_AND_TIME"],
32
+ ]);
33
+ /** The SDK's conversions, each named for the policy it applies. */
34
+ const conversions: readonly Conversion[] = ["exact", "wrap", "saturate"];
35
+ const isConversion = (name: string): name is Conversion =>
36
+ conversions.some((conversion) => conversion === name);
37
+ /** The SDK's one-operand math functions, each over the floating type its type argument names. */
38
+ const mathFunctions = new Map<string, UnaryOperator>([
39
+ ...elementaryFunctions.map((name): [string, UnaryOperator] => [name, name]),
40
+ ["trunc", "truncate"],
41
+ ]);
42
+
43
+ const arithmetic = new Map<string, Arithmetic>([
44
+ ["div", { operator: "divide" }],
45
+ ["expt", { operator: "power" }],
46
+ ["wrapAdd", { operator: "add", policy: "wrap" }],
47
+ ["wrapSubtract", { operator: "subtract", policy: "wrap" }],
48
+ ["wrapMultiply", { operator: "multiply", policy: "wrap" }],
49
+ ["saturatingAdd", { operator: "add", policy: "saturate" }],
50
+ ["saturatingSubtract", { operator: "subtract", policy: "saturate" }],
51
+ ["saturatingMultiply", { operator: "multiply", policy: "saturate" }],
52
+ ]);
53
+
54
+ /** The SDK calls whose value has the PLC type their type argument names, such as `wrap<INT>(x)`. */
55
+ export const typeArgumentIntrinsics: ReadonlySet<string> = new Set([
56
+ ...conversions,
57
+ ...mathFunctions.keys(),
58
+ ...arithmetic.keys(),
59
+ "defaultValue",
60
+ "copy",
61
+ ]);
62
+
63
+ /** A call to an SDK intrinsic such as `ms`, `wrap<T>` or `defaultValue<T>`; undefined for any other call. */
64
+ export function intrinsicExpression(
65
+ lowering: ExpressionLowering,
66
+ node: ts.CallExpression,
67
+ expected?: string,
68
+ ): Expression | undefined {
69
+ const name = lowering.sdkCall(node);
70
+ if (name === undefined) {
71
+ return undefined;
72
+ }
73
+ const scale = durationScales.get(name);
74
+ if (scale !== undefined) {
75
+ return timeConstant(lowering, node, "TIME", (argument) =>
76
+ durationConstant(lowering, argument, scale),
77
+ );
78
+ }
79
+ const calendar = calendarTypes.get(name);
80
+ if (calendar !== undefined) {
81
+ return timeConstant(lowering, node, calendar, (argument) =>
82
+ calendarConstant(lowering, argument, calendar),
83
+ );
84
+ }
85
+ if (isConversion(name)) {
86
+ return converted(lowering, node, name);
87
+ }
88
+ const operation = arithmetic.get(name);
89
+ if (operation !== undefined) {
90
+ return arithmeticExpression(lowering, node, operation);
91
+ }
92
+ const mathOperator = mathFunctions.get(name);
93
+ if (mathOperator !== undefined) {
94
+ return mathExpression(lowering, node, mathOperator);
95
+ }
96
+ switch (name) {
97
+ case "errorCode":
98
+ return errorCode(lowering, node);
99
+ case "now":
100
+ return now(lowering, node);
101
+ case "timeToMilliseconds":
102
+ return timeToMilliseconds(lowering, node);
103
+ case "defaultValue":
104
+ return defaultValueExpression(lowering, node);
105
+ case "copy":
106
+ return copyExpression(lowering, node, expected);
107
+ default:
108
+ return undefined;
109
+ }
110
+ }
111
+
112
+ function errorCode(
113
+ lowering: ExpressionLowering,
114
+ node: ts.CallExpression,
115
+ ): Expression {
116
+ const [reason, ...rest] = node.arguments;
117
+ if (!reason || rest.length) {
118
+ lowering.fail(node, "PLC1012", "errorCode requires one rejection reason.");
119
+ }
120
+ return lowering.expression(reason, "UDINT");
121
+ }
122
+
123
+ /** A TIME or calendar value from its one compile-time argument. */
124
+ function timeConstant(
125
+ lowering: ExpressionLowering,
126
+ node: ts.CallExpression,
127
+ type: string,
128
+ constant: (argument: ts.Expression) => Constant | undefined,
129
+ ): Expression {
130
+ const [argument, ...rest] = node.arguments;
131
+ if (!argument || rest.length || node.typeArguments?.length) {
132
+ lowering.fail(
133
+ node,
134
+ "PLC2001",
135
+ "Time constructors require one compile-time literal argument.",
136
+ );
137
+ }
138
+ const value = constant(argument);
139
+ if (!value) {
140
+ lowering.fail(
141
+ argument,
142
+ "PLC2002",
143
+ "Invalid time literal: require an exact supported domain value and millisecond TIME precision.",
144
+ );
145
+ }
146
+ return lowering.checked({
147
+ span: lowering.positions.node(node),
148
+ type,
149
+ kind: "constant",
150
+ value,
151
+ });
152
+ }
153
+
154
+ function durationConstant(
155
+ lowering: ExpressionLowering,
156
+ argument: ts.Expression,
157
+ scale: bigint,
158
+ ): Constant | undefined {
159
+ const text = durationText(lowering, argument);
160
+ return text === undefined ? undefined : literalDuration(text, scale);
161
+ }
162
+
163
+ /** The TIME value a numeric literal's text stands for in units of `scale` nanoseconds. */
164
+ export function literalDuration(
165
+ text: string,
166
+ scale: bigint,
167
+ ): Constant | undefined {
168
+ const decimal = isRadixLiteral(text) ? String(parseInteger(text)) : text;
169
+ return durationLiteral(decimal.replace(/n$/, ""), scale);
170
+ }
171
+
172
+ /** The literal as written, so its decimal spelling survives, or a folded integer constant. */
173
+ function durationText(
174
+ lowering: ExpressionLowering,
175
+ argument: ts.Expression,
176
+ ): string | undefined {
177
+ const literal = numericLiteral(argument);
178
+ if (literal !== undefined) {
179
+ return literal;
180
+ }
181
+ const folded = lowering.constant(lowering.expression(argument));
182
+ return folded?.kind === "integer" ? folded.value : undefined;
183
+ }
184
+
185
+ function calendarConstant(
186
+ lowering: ExpressionLowering,
187
+ argument: ts.Expression,
188
+ type: string,
189
+ ): Constant | undefined {
190
+ const layout = lowering.resolver.types.get(type);
191
+ return layout?.kind === "calendar" &&
192
+ (ts.isStringLiteral(argument) ||
193
+ ts.isNoSubstitutionTemplateLiteral(argument))
194
+ ? calendarLiteral(layout.domain, argument.text)
195
+ : undefined;
196
+ }
197
+
198
+ function now(
199
+ lowering: ExpressionLowering,
200
+ node: ts.CallExpression,
201
+ ): Expression {
202
+ if (node.arguments.length || node.typeArguments?.length) {
203
+ lowering.fail(node, "PLC2001", "now() takes no arguments.");
204
+ }
205
+ const span = lowering.positions.node(node);
206
+ return lowering.checked({
207
+ span,
208
+ type: "DINT",
209
+ kind: "unary",
210
+ operator: "clock",
211
+ operand: {
212
+ span,
213
+ type: "DINT",
214
+ kind: "constant",
215
+ value: { kind: "integer", value: "0" },
216
+ },
217
+ });
218
+ }
219
+
220
+ function timeToMilliseconds(
221
+ lowering: ExpressionLowering,
222
+ node: ts.CallExpression,
223
+ ): Expression {
224
+ const [time, ...rest] = node.arguments;
225
+ if (!time || rest.length || node.typeArguments?.length) {
226
+ lowering.fail(
227
+ node,
228
+ "PLC2001",
229
+ "timeToMilliseconds requires one TIME argument and no type arguments.",
230
+ );
231
+ }
232
+ return lowering.checked({
233
+ span: lowering.positions.node(node),
234
+ type: "UDINT",
235
+ kind: "unary",
236
+ operator: "timeToMilliseconds",
237
+ operand: lowering.expression(time),
238
+ });
239
+ }
240
+
241
+ function defaultValueExpression(
242
+ lowering: ExpressionLowering,
243
+ node: ts.CallExpression,
244
+ ): Expression {
245
+ const [layout, ...rest] = node.typeArguments ?? [];
246
+ if (node.arguments.length || !layout || rest.length) {
247
+ lowering.fail(
248
+ node,
249
+ "PLC2001",
250
+ "defaultValue requires exactly one concrete type and no value arguments.",
251
+ );
252
+ }
253
+ const type = lowering.type(layout);
254
+ if (!lowering.resolver.isValue(type)) {
255
+ lowering.fail(
256
+ node,
257
+ "PLC2001",
258
+ "defaultValue requires a fixed value layout, not an instance or borrow schema.",
259
+ );
260
+ }
261
+ if (type.io) {
262
+ lowering.fail(node, "PLC4002", "Default values cannot create logical I/O.");
263
+ }
264
+ return lowering.checked({
265
+ span: lowering.positions.node(node),
266
+ type: type.type,
267
+ kind: "constant",
268
+ value: defaultValue(type.type, lowering.resolver.types),
269
+ });
270
+ }
271
+
272
+ function copyExpression(
273
+ lowering: ExpressionLowering,
274
+ node: ts.CallExpression,
275
+ expected: string | undefined,
276
+ ): Expression {
277
+ const [value, ...rest] = node.arguments;
278
+ if (
279
+ !value ||
280
+ rest.length ||
281
+ (node.typeArguments && node.typeArguments.length !== 1)
282
+ ) {
283
+ lowering.fail(node, "PLC2001", "copy requires one fixed aggregate value.");
284
+ }
285
+ const layout = node.typeArguments?.[0];
286
+ const operand = lowering.expression(
287
+ value,
288
+ layout ? lowering.type(layout).type : expected,
289
+ );
290
+ return lowering.checked({
291
+ span: lowering.positions.node(node),
292
+ type: operand.type,
293
+ kind: "copy",
294
+ operand,
295
+ });
296
+ }
297
+
298
+ /** The explicit PLC type argument a numeric conversion or arithmetic operation works in. */
299
+ function operationType(
300
+ lowering: ExpressionLowering,
301
+ node: ts.CallExpression,
302
+ ): string {
303
+ const [argument, ...rest] = node.typeArguments ?? [];
304
+ if (!argument || rest.length) {
305
+ lowering.fail(
306
+ node,
307
+ "PLC2001",
308
+ "Numeric SDK operations require one explicit PLC type argument.",
309
+ );
310
+ }
311
+ const target = lowering.type(argument);
312
+ if (target.io) {
313
+ lowering.fail(
314
+ argument,
315
+ "PLC2001",
316
+ "I/O wrappers cannot select an operation type.",
317
+ );
318
+ }
319
+ return target.type;
320
+ }
321
+
322
+ function converted(
323
+ lowering: ExpressionLowering,
324
+ node: ts.CallExpression,
325
+ policy: Conversion,
326
+ ): Expression {
327
+ const type = operationType(lowering, node);
328
+ const [operand, ...rest] = node.arguments;
329
+ if (!operand || rest.length) {
330
+ lowering.fail(node, "PLC2001", "Conversion needs exactly one operand.");
331
+ }
332
+ return lowering.checked({
333
+ span: lowering.positions.node(node),
334
+ type,
335
+ kind: "convert",
336
+ policy,
337
+ operand: lowering.expression(operand),
338
+ });
339
+ }
340
+
341
+ function mathExpression(
342
+ lowering: ExpressionLowering,
343
+ node: ts.CallExpression,
344
+ operator: UnaryOperator,
345
+ ): Expression {
346
+ const type = operationType(lowering, node);
347
+ const [operand, ...rest] = node.arguments;
348
+ if (!operand || rest.length) {
349
+ lowering.fail(node, "PLC2001", "A math function takes one operand.");
350
+ }
351
+ return lowering.checked({
352
+ span: lowering.positions.node(node),
353
+ type,
354
+ kind: "unary",
355
+ operator,
356
+ operand: lowering.expression(operand, type),
357
+ });
358
+ }
359
+
360
+ function arithmeticExpression(
361
+ lowering: ExpressionLowering,
362
+ node: ts.CallExpression,
363
+ operation: Arithmetic,
364
+ ): Expression {
365
+ const type = operationType(lowering, node);
366
+ const [left, right, ...rest] = node.arguments;
367
+ if (!left || !right || rest.length) {
368
+ lowering.fail(
369
+ node,
370
+ "PLC2001",
371
+ "Arithmetic SDK operation needs two operands.",
372
+ );
373
+ }
374
+ return lowering.checked({
375
+ span: lowering.positions.node(node),
376
+ type,
377
+ kind: "binary",
378
+ ...operation,
379
+ left: lowering.expression(left, type),
380
+ right: lowering.expression(right, type),
381
+ });
382
+ }
@@ -0,0 +1,23 @@
1
+ import { relative, resolve } from "node:path";
2
+
3
+ /** A file's path from the project root, with forward slashes, as generated names, digests and declaration ids spell it. */
4
+ export const modulePath = (projectRoot: string, file: string): string =>
5
+ relative(projectRoot, file).replace(/\\/g, "/");
6
+
7
+ /** The key a lowering pass records what it learned about a module's declaration under. */
8
+ export const loweringKey = (file: string, name: string): string =>
9
+ `${file}:${name}`;
10
+
11
+ /** The lowering key of a verified declaration, whose id begins `<modulePath>:<start>:<name>`. */
12
+ export const declarationKey = (
13
+ root: string,
14
+ declaration: { id: string; name: string },
15
+ ): string =>
16
+ loweringKey(
17
+ resolve(root, declaration.id.slice(0, declaration.id.indexOf(":"))),
18
+ declaration.name,
19
+ );
20
+
21
+ /** The lowering key of a verified type, which carries its name only in its id. */
22
+ export const typeKey = (root: string, id: string): string =>
23
+ declarationKey(root, { id, name: id.slice(id.lastIndexOf(":") + 1) });
@@ -0,0 +1,156 @@
1
+ import { dirname, relative } from "node:path";
2
+ import ts from "typescript";
3
+ import { namesSdk, symbolAt } from "./sdk";
4
+
5
+ /** The quoted specifier an import generated into `importer` uses to reach `target`. */
6
+ export const importSpecifier = (importer: string, target: string): string => {
7
+ const path = relative(dirname(importer), target).replaceAll("\\", "/");
8
+ // A file beside the importer may itself start with a dot, as a generated `.tsplc-services.ts` does.
9
+ return JSON.stringify(/^\.\.?\//.test(path) ? path : `./${path}`);
10
+ };
11
+
12
+ /**
13
+ * Whether an import or re-export loads its module when the importer runs: not when it is
14
+ * type-only, nor when every name it lists is a type.
15
+ */
16
+ export const runtimeImport = (
17
+ statement: ts.ImportDeclaration | ts.ExportDeclaration,
18
+ checker: ts.TypeChecker,
19
+ ): boolean => {
20
+ const typeOnly = ts.isImportDeclaration(statement)
21
+ ? statement.importClause?.isTypeOnly
22
+ : statement.isTypeOnly;
23
+ if (typeOnly) {
24
+ return false;
25
+ }
26
+ const bindings = ts.isImportDeclaration(statement)
27
+ ? statement.importClause?.namedBindings
28
+ : statement.exportClause;
29
+ const defaultName = ts.isImportDeclaration(statement)
30
+ ? statement.importClause?.name
31
+ : undefined;
32
+ const namesOnlyTypes =
33
+ bindings &&
34
+ (ts.isNamedImports(bindings) || ts.isNamedExports(bindings)) &&
35
+ bindings.elements.length > 0 &&
36
+ bindings.elements.every((binding) => {
37
+ const symbol = symbolAt(checker, binding.name);
38
+ return (
39
+ binding.isTypeOnly ||
40
+ (symbol !== undefined && !(symbol.flags & ts.SymbolFlags.Value))
41
+ );
42
+ });
43
+ return !namesOnlyTypes || defaultName !== undefined;
44
+ };
45
+
46
+ /** `Block` in a `FixedArray<Block, ...>` annotation, where `namesFixedArray` tells whether a reference names `FixedArray`. */
47
+ const fixedArrayElement = (
48
+ node: ts.Node,
49
+ namesFixedArray: (name: ts.EntityName) => boolean,
50
+ ): ts.TypeReferenceNode | undefined => {
51
+ if (!ts.isTypeReferenceNode(node) || !namesFixedArray(node.typeName)) {
52
+ return undefined;
53
+ }
54
+ const [element] = node.typeArguments ?? [];
55
+ return element && ts.isTypeReferenceNode(element) ? element : undefined;
56
+ };
57
+
58
+ /** `Block` in a `FixedArray<Block, ...>` annotation, whose instances the array allocates when it names a block class. */
59
+ export const blockArrayElement = (
60
+ node: ts.TypeNode,
61
+ checker: ts.TypeChecker,
62
+ sdk: string,
63
+ ): ts.TypeReferenceNode | undefined =>
64
+ fixedArrayElement(node, (name) => namesSdk(checker, sdk, name, "FixedArray"));
65
+
66
+ /** Runtime imports define execution; type-only imports provide layouts without allocating state. */
67
+ export const runtimeSources = (
68
+ program: ts.Program,
69
+ ): readonly ts.SourceFile[] => {
70
+ const checker = program.getTypeChecker();
71
+ const visited = new Set<ts.SourceFile>();
72
+ // A block array allocates through its type, so its block's module runs even when type-imported.
73
+ const visitBlockArrays = (node: ts.Node): void => {
74
+ const element = fixedArrayElement(
75
+ node,
76
+ (name) => name.getText() === "FixedArray",
77
+ );
78
+ const block =
79
+ element &&
80
+ symbolAt(checker, element.typeName)?.declarations?.find(
81
+ ts.isClassDeclaration,
82
+ );
83
+ if (block) {
84
+ visit(block.getSourceFile());
85
+ }
86
+ ts.forEachChild(node, visitBlockArrays);
87
+ };
88
+ const visit = (source: ts.SourceFile): void => {
89
+ if (visited.has(source)) {
90
+ return;
91
+ }
92
+ visited.add(source);
93
+ if (source.isDeclarationFile) {
94
+ return;
95
+ }
96
+ visitBlockArrays(source);
97
+ for (const statement of source.statements) {
98
+ if (
99
+ (ts.isImportDeclaration(statement) ||
100
+ ts.isExportDeclaration(statement)) &&
101
+ statement.moduleSpecifier &&
102
+ runtimeImport(statement, checker)
103
+ ) {
104
+ const target = checker
105
+ .getSymbolAtLocation(statement.moduleSpecifier)
106
+ ?.declarations?.find(ts.isSourceFile);
107
+ if (target) {
108
+ visit(target);
109
+ }
110
+ }
111
+ }
112
+ };
113
+ for (const file of program.getRootFileNames()) {
114
+ const source = program.getSourceFile(file);
115
+ if (source) {
116
+ visit(source);
117
+ }
118
+ }
119
+ return program.getSourceFiles().filter((source) => visited.has(source));
120
+ };
121
+
122
+ /** The program's runtime sources the compiler lowers: its own TypeScript, not declaration files. */
123
+ export const plcSources = (program: ts.Program): readonly ts.SourceFile[] =>
124
+ runtimeSources(program).filter((source) => !source.isDeclarationFile);
125
+
126
+ /** A named top-level function or class method. */
127
+ export type NamedRoutine = (ts.FunctionDeclaration | ts.MethodDeclaration) & {
128
+ readonly name: ts.PropertyName;
129
+ };
130
+
131
+ const isNamedRoutine = (node: ts.Node): node is NamedRoutine =>
132
+ (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) &&
133
+ node.name !== undefined;
134
+
135
+ /** The named top-level functions and class methods of `sources`, by symbol. */
136
+ export const namedRoutines = (
137
+ sources: readonly ts.SourceFile[],
138
+ checker: ts.TypeChecker,
139
+ ): ReadonlyMap<ts.Symbol, NamedRoutine> => {
140
+ const routines = new Map<ts.Symbol, NamedRoutine>();
141
+ for (const source of sources) {
142
+ for (const statement of source.statements) {
143
+ const candidates = ts.isClassDeclaration(statement)
144
+ ? statement.members.filter(ts.isMethodDeclaration)
145
+ : [statement];
146
+ for (const candidate of candidates) {
147
+ const symbol =
148
+ isNamedRoutine(candidate) && symbolAt(checker, candidate.name);
149
+ if (symbol) {
150
+ routines.set(symbol, candidate);
151
+ }
152
+ }
153
+ }
154
+ }
155
+ return routines;
156
+ };