@tsplc/tmp-compiler 0.0.0-stage → 0.6.3

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 (185) 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 +6563 -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 +16198 -0
  12. package/dist/index.js.map +62 -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 +1090 -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-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,872 @@
1
+ import ts from "typescript";
2
+ import {
3
+ cooperativeTasksAlias,
4
+ copyValue,
5
+ errorCodeAlias,
6
+ } from "./cooperative";
7
+ import { typeArgumentIntrinsics } from "./intrinsics";
8
+ import type { Callable, PromiseContext } from "./promises";
9
+ import { holdsBorrow, valueSymbol } from "./sdk";
10
+ import { backgroundJob } from "./tasks";
11
+ import {
12
+ calleeName,
13
+ hasModifier,
14
+ isAggregateType,
15
+ isPropertyName,
16
+ namedRecordText,
17
+ promisedType,
18
+ } from "./types";
19
+
20
+ type Handler = ts.ArrowFunction | ts.FunctionExpression | Callable;
21
+
22
+ const linkKinds = ["then", "catch"] as const;
23
+
24
+ /** A `.then(fulfilled, rejected)` or `.catch(rejected)` link of a chain. */
25
+ interface ChainLink {
26
+ kind: (typeof linkKinds)[number];
27
+ handlers: readonly ts.Expression[];
28
+ }
29
+
30
+ /** An async operation and the links chained onto it. */
31
+ export interface Chain {
32
+ root: ts.CallExpression;
33
+ links: ChainLink[];
34
+ }
35
+
36
+ /** A value a generated helper takes: a root call argument or a captured const. */
37
+ interface HelperParameter {
38
+ name: string;
39
+ type: string;
40
+ expression: string;
41
+ }
42
+
43
+ /** A callback as the chain calls it on an input, with the type it resolves to. */
44
+ interface Callback {
45
+ call: (input: string) => string;
46
+ type: string;
47
+ aggregate: boolean;
48
+ }
49
+
50
+ /** A step of the chain: the helper that runs it, with the type it resolves to. */
51
+ interface Step {
52
+ helper: string;
53
+ type: string;
54
+ aggregate: boolean;
55
+ }
56
+
57
+ const asyncRoutine = (context: PromiseContext, node: ts.Node) => {
58
+ const symbol = context.symbol(node);
59
+ const fn = symbol && context.routines.get(symbol);
60
+ return fn && hasModifier(fn, ts.SyntaxKind.AsyncKeyword) ? fn : undefined;
61
+ };
62
+
63
+ /** The async routine a `backgroundTasks.define` job runs. */
64
+ const job = (context: PromiseContext, node: ts.Node) => {
65
+ const [work] = backgroundJob(context, context.symbol(node))?.arguments ?? [];
66
+ return work && asyncRoutine(context, work);
67
+ };
68
+
69
+ /** The async routine a call runs, directly or as a background job. */
70
+ const operation = (context: PromiseContext, call: ts.CallExpression) => {
71
+ const callee = calleeName(call.expression);
72
+ return callee && (asyncRoutine(context, callee) ?? job(context, callee));
73
+ };
74
+
75
+ const isSdk = (
76
+ context: PromiseContext,
77
+ call: ts.CallExpression,
78
+ name: string,
79
+ ) => {
80
+ const callee = calleeName(call.expression);
81
+ return callee !== undefined && context.namesSdk(callee, name);
82
+ };
83
+
84
+ /** The link a `.then` or `.catch` call adds, and the expression it is chained onto. */
85
+ const linkOf = (call: ts.CallExpression) => {
86
+ const callee = call.expression;
87
+ if (!ts.isPropertyAccessExpression(callee)) {
88
+ return;
89
+ }
90
+ const kind = linkKinds.find((link) => link === callee.name.text);
91
+ return kind && { kind, target: callee.expression };
92
+ };
93
+
94
+ /** An inline callback of a `.then` or `.catch` link, which promise lowering runs as a coroutine. */
95
+ export const promiseCallback = (node: ts.Node): boolean =>
96
+ (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) &&
97
+ ts.isCallExpression(node.parent) &&
98
+ linkOf(node.parent) !== undefined;
99
+
100
+ /** The chain an expression is: an async call or SDK sleep or fetch, with its links. */
101
+ export const chainOf = (
102
+ context: PromiseContext,
103
+ expression: ts.Expression,
104
+ ): Chain | undefined => {
105
+ if (!ts.isCallExpression(expression)) {
106
+ return;
107
+ }
108
+ const link = linkOf(expression);
109
+ if (link) {
110
+ const prefix = chainOf(context, link.target);
111
+ if (!prefix) {
112
+ return;
113
+ }
114
+ return {
115
+ root: prefix.root,
116
+ links: [
117
+ ...prefix.links,
118
+ { kind: link.kind, handlers: expression.arguments },
119
+ ],
120
+ };
121
+ }
122
+ if (
123
+ operation(context, expression) ||
124
+ isSdk(context, expression, "sleep") ||
125
+ isSdk(context, expression, "fetch")
126
+ ) {
127
+ return { root: expression, links: [] };
128
+ }
129
+ };
130
+
131
+ /**
132
+ * Replaces a chain with named helper coroutines, one for the operation and one per link.
133
+ * A detached chain becomes a cooperative site its owner starts; otherwise the expression
134
+ * becomes a call to the last helper.
135
+ */
136
+ export const lowerChain = (
137
+ context: PromiseContext,
138
+ expression: ts.Expression,
139
+ chain: Chain,
140
+ owner: Callable,
141
+ { detached }: { detached: boolean },
142
+ ): string =>
143
+ new PromiseChain(context, expression, chain, owner).lower({ detached });
144
+
145
+ const isAggregate = (type: ts.Type | undefined) =>
146
+ type !== undefined && isAggregateType(type);
147
+
148
+ const helperFinish = (
149
+ call: string,
150
+ type: string,
151
+ { discard }: { discard: boolean },
152
+ ) =>
153
+ type === "void" || discard
154
+ ? `await ${call};return;`
155
+ : `return await ${call};`;
156
+
157
+ /** One chain being lowered: its captures, root operation and helpers. */
158
+ class PromiseChain {
159
+ private readonly source: ts.SourceFile;
160
+ /** The class that owns the helpers when the chain is in a method; otherwise the module does. */
161
+ private readonly classOwner: ts.ClassDeclaration | undefined;
162
+ private readonly captures = new Map<
163
+ ts.Symbol,
164
+ { name: string; type: string; argument: string }
165
+ >();
166
+ private readonly captureNames: ReadonlyMap<ts.Symbol, string>;
167
+ private readonly params: HelperParameter[];
168
+ private readonly signature: string;
169
+ private readonly args: string;
170
+ private readonly rootInvocation: string;
171
+ private readonly rootType: string;
172
+
173
+ constructor(
174
+ private readonly context: PromiseContext,
175
+ private readonly expression: ts.Expression,
176
+ private readonly chain: Chain,
177
+ private readonly owner: Callable,
178
+ ) {
179
+ this.source = expression.getSourceFile();
180
+ this.classOwner =
181
+ ts.isMethodDeclaration(owner) && ts.isClassDeclaration(owner.parent)
182
+ ? owner.parent
183
+ : undefined;
184
+ context.ensureImports(this.source, expression);
185
+ context.useDiagnostics(expression);
186
+ for (const link of chain.links) {
187
+ for (const value of link.handlers) {
188
+ if (ts.isArrowFunction(value) || ts.isFunctionExpression(value)) {
189
+ this.collectCaptures(value);
190
+ }
191
+ }
192
+ }
193
+ this.captureNames = new Map(
194
+ [...this.captures].map(([key, value]) => [key, value.name]),
195
+ );
196
+ const root = this.rootCall();
197
+ this.rootInvocation = root.invocation;
198
+ this.rootType = root.type;
199
+ this.params = [
200
+ ...root.arguments,
201
+ ...[...this.captures.values()].map((value) => ({
202
+ name: value.name,
203
+ type: value.type,
204
+ expression: value.argument,
205
+ })),
206
+ ];
207
+ this.signature = this.params
208
+ .map((value) => `${value.name}:${value.type}`)
209
+ .join(",");
210
+ this.args = this.params.map((value) => value.name).join(",");
211
+ }
212
+
213
+ /** The routine's const locals and parameters a callback reads become helper parameters. */
214
+ private collectCaptures(handler: ts.ArrowFunction | ts.FunctionExpression) {
215
+ const visit = (node: ts.Node): void => {
216
+ if (ts.isIdentifier(node) && !isPropertyName(node)) {
217
+ this.capture(node);
218
+ }
219
+ ts.forEachChild(node, visit);
220
+ };
221
+ visit(handler.body);
222
+ }
223
+
224
+ private capture(node: ts.Identifier): void {
225
+ const { context } = this;
226
+ const key = valueSymbol(context.checker, node);
227
+ const declaration = key?.valueDeclaration;
228
+ if (
229
+ !key ||
230
+ !declaration ||
231
+ !(ts.isVariableDeclaration(declaration) || ts.isParameter(declaration)) ||
232
+ ts.findAncestor(declaration.parent, ts.isFunctionLike) !== this.owner ||
233
+ this.captures.has(key)
234
+ ) {
235
+ return;
236
+ }
237
+ if (
238
+ ts.isVariableDeclaration(declaration) &&
239
+ (!ts.isVariableDeclarationList(declaration.parent) ||
240
+ !(declaration.parent.flags & ts.NodeFlags.Const))
241
+ ) {
242
+ this.context.fail(
243
+ node,
244
+ "Continuation captures must be const values; store mutable state on the controller instead.",
245
+ );
246
+ }
247
+ if (!declaration.type) {
248
+ this.context.fail(
249
+ node,
250
+ "Annotate a captured value with its concrete PLC type.",
251
+ );
252
+ }
253
+ if (holdsBorrow(context, declaration.type)) {
254
+ this.context.fail(
255
+ node,
256
+ "A continuation cannot capture borrowed InOut storage; capture values or use controller state.",
257
+ );
258
+ }
259
+ this.captures.set(key, {
260
+ name: `capture${this.captures.size}`,
261
+ type: context.typeText(declaration.type, this.source),
262
+ argument: node.text,
263
+ });
264
+ }
265
+
266
+ /** The root operation's arguments, the call that runs it, and the type it resolves to. */
267
+ private rootCall(): {
268
+ arguments: HelperParameter[];
269
+ invocation: string;
270
+ type: string;
271
+ } {
272
+ const { context, source } = this;
273
+ const { root } = this.chain;
274
+ const fn = operation(context, root);
275
+ if (fn) {
276
+ const promised = fn.type && promisedType(fn.type);
277
+ if (!promised) {
278
+ this.context.fail(
279
+ fn,
280
+ "Async calls need an explicit Promise<T> result.",
281
+ );
282
+ }
283
+ const type = context.typeText(promised, source);
284
+ const parameters = fn.parameters.map((parameter, index) => {
285
+ const argument = root.arguments[index];
286
+ if (!parameter.type || !argument) {
287
+ this.context.fail(
288
+ root,
289
+ "Async argument count differs from its concrete signature.",
290
+ );
291
+ }
292
+ return {
293
+ name: `argument${index}`,
294
+ type: context.typeText(parameter.type, source),
295
+ expression: argument.getText(source),
296
+ };
297
+ });
298
+ return {
299
+ arguments: parameters,
300
+ invocation: `${root.expression.getText(source)}(${parameters.map((value) => value.name).join(",")})`,
301
+ type,
302
+ };
303
+ }
304
+ if (isSdk(context, root, "sleep")) {
305
+ const [duration, ...rest] = root.arguments;
306
+ if (!duration || rest.length) {
307
+ this.context.fail(root, "sleep requires one TIME argument.");
308
+ }
309
+ return {
310
+ arguments: [
311
+ {
312
+ name: "argument0",
313
+ type: "TIME",
314
+ expression: duration.getText(source),
315
+ },
316
+ ],
317
+ invocation: `${root.expression.getText(source)}(argument0)`,
318
+ type: "void",
319
+ };
320
+ }
321
+ return this.fetchCall(root);
322
+ }
323
+
324
+ /** A fetch keeps its options in the call; only its json body becomes a helper parameter. */
325
+ private fetchCall(root: ts.CallExpression) {
326
+ const { context, source } = this;
327
+ const typeArguments = root.typeArguments;
328
+ const response = typeArguments?.[0];
329
+ if (!typeArguments || !response) {
330
+ this.context.fail(root, "fetch requires a typed response.");
331
+ }
332
+ const type = context.typeText(response, source);
333
+ const [url, options] = root.arguments;
334
+ if (!url) {
335
+ this.context.fail(root, "fetch requires a URL.");
336
+ }
337
+ if (options && !ts.isObjectLiteralExpression(options)) {
338
+ this.context.fail(options, "fetch options must be an inline object.");
339
+ }
340
+ const parameters: HelperParameter[] = [];
341
+ const optionText = options
342
+ ? options.properties
343
+ .map((property) => {
344
+ if (!ts.isPropertyAssignment(property)) {
345
+ this.context.fail(property, "fetch requires named options.");
346
+ }
347
+ if (property.name.getText(source) !== "json") {
348
+ return property.getText(source);
349
+ }
350
+ parameters.push({
351
+ name: "argument0",
352
+ type: this.expressionType(property.initializer),
353
+ expression: property.initializer.getText(source),
354
+ });
355
+ return "json:argument0";
356
+ })
357
+ .join(",")
358
+ : "";
359
+ return {
360
+ arguments: parameters,
361
+ invocation: `${root.expression.getText(source)}<${typeArguments.map((type) => type.getText(source)).join(",")}>(${url.getText(source)}${options ? `,{${optionText}}` : ""})`,
362
+ type,
363
+ };
364
+ }
365
+
366
+ /** A value's PLC type: from an SDK type argument, its declaration, or the checker. */
367
+ private expressionType(node: ts.Expression): string {
368
+ const { context, source } = this;
369
+ const { checker } = context;
370
+ const typeArgument = ts.isCallExpression(node)
371
+ ? node.typeArguments?.[0]
372
+ : undefined;
373
+ if (
374
+ typeArgument &&
375
+ ts.isCallExpression(node) &&
376
+ [...typeArgumentIntrinsics].some((name) =>
377
+ context.namesSdk(node.expression, name),
378
+ )
379
+ ) {
380
+ return context.typeText(typeArgument, source);
381
+ }
382
+ const name = ts.isPropertyAccessExpression(node) ? node.name : node;
383
+ const declaration = context
384
+ .symbol(name)
385
+ ?.declarations?.find(isAnnotatedDeclaration);
386
+ if (declaration) {
387
+ return context.typeText(declaration.type, source);
388
+ }
389
+ const type = checker.getTypeAtLocation(node);
390
+ if (type.flags & ts.TypeFlags.BooleanLike) {
391
+ return "BOOL";
392
+ }
393
+ if (type.flags & ts.TypeFlags.Void) {
394
+ return "void";
395
+ }
396
+ return (
397
+ namedRecordText(checker, node) ??
398
+ this.context.fail(
399
+ node,
400
+ "Annotate this value with its concrete PLC type before using it in an async continuation.",
401
+ )
402
+ );
403
+ }
404
+
405
+ private isPromise(node: ts.Node): boolean {
406
+ const { checker } = this.context;
407
+ const type = checker.getTypeAtLocation(node);
408
+ return checker.getAwaitedType(type) !== type;
409
+ }
410
+
411
+ /** A generated helper coroutine, declared in the class or module that owns the chain. */
412
+ private declare(
413
+ name: string,
414
+ parameters: string,
415
+ type: string,
416
+ body: string,
417
+ ): string {
418
+ const { classOwner } = this;
419
+ return `${classOwner ? "private " : "export "}async ${classOwner ? "" : "function "}${name}(${parameters}):Promise<${type}>{${body}}`;
420
+ }
421
+
422
+ /**
423
+ * Declares a helper that takes the chain's parameters, and an input of type `input` unless it
424
+ * is null; returns the name it is called by.
425
+ */
426
+ private addHelper(
427
+ name: string,
428
+ body: string,
429
+ type: string,
430
+ input: string | null,
431
+ ): string {
432
+ const { classOwner } = this;
433
+ this.context.append(
434
+ classOwner ?? this.source,
435
+ this.expression,
436
+ this.declare(
437
+ name,
438
+ [this.signature, input === null ? "" : `promiseInput:${input}`]
439
+ .filter(Boolean)
440
+ .join(","),
441
+ type,
442
+ body,
443
+ ),
444
+ );
445
+ return `${classOwner ? "this." : ""}${name}`;
446
+ }
447
+
448
+ /** A call to a helper with the chain's parameters, then `input` when it takes one. */
449
+ private invoke(helper: string, input: string): string {
450
+ return `${helper}(${[this.args, input].filter(Boolean).join(",")})`;
451
+ }
452
+
453
+ lower({ detached }: { detached: boolean }): string {
454
+ const { context, classOwner, source } = this;
455
+ const links = this.chain.links;
456
+ const operation: Step = {
457
+ helper: this.addHelper(
458
+ context.names.name("tsplcPromiseOperation", this.chain.root),
459
+ helperFinish(this.rootInvocation, this.rootType, { discard: false }),
460
+ this.rootType,
461
+ null,
462
+ ),
463
+ type: this.rootType,
464
+ aggregate: isAggregate(
465
+ context.checker.getAwaitedType(
466
+ context.checker.getTypeAtLocation(this.chain.root),
467
+ ),
468
+ ),
469
+ };
470
+ const last = links.reduce(
471
+ (previous, link, index) =>
472
+ this.link(link, previous, {
473
+ terminal: detached && index === links.length - 1,
474
+ index,
475
+ }),
476
+ operation,
477
+ );
478
+ const values = this.params.map((value) => value.expression).join(",");
479
+ if (!detached) {
480
+ return `${last.helper}(${values})`;
481
+ }
482
+ const site = context.names.name("tsplcPromiseSite", this.chain.root);
483
+ const scope = classOwner ?? source;
484
+ context.append(
485
+ scope,
486
+ this.expression,
487
+ `${classOwner ? "private " : "const "}${site}=${cooperativeTasksAlias}.define(${last.helper});`,
488
+ );
489
+ const callee = calleeName(this.chain.root.expression);
490
+ context.sites.set(scope, [
491
+ ...(context.sites.get(scope) ?? []),
492
+ { name: site, root: callee && context.symbol(callee) },
493
+ ]);
494
+ return `${classOwner ? "this." : ""}${site}.start(${values});`;
495
+ }
496
+
497
+ /**
498
+ * The helper for one link: it awaits the previous step, then calls the fulfilled or
499
+ * rejected callback. A terminal link of a detached chain discards the result.
500
+ */
501
+ private link(
502
+ link: ChainLink,
503
+ previous: Step,
504
+ { terminal, index }: { terminal: boolean; index: number },
505
+ ): Step {
506
+ const fulfilled =
507
+ link.kind === "then"
508
+ ? this.callback(link.handlers[0], previous.type, `${index}Fulfilled`)
509
+ : undefined;
510
+ const rejected = this.callback(
511
+ link.handlers[link.kind === "catch" ? 0 : 1],
512
+ "UDINT",
513
+ `${index}Rejected`,
514
+ );
515
+ if (!fulfilled && !rejected) {
516
+ return previous;
517
+ }
518
+ const output = terminal ? "void" : (fulfilled?.type ?? previous.type);
519
+ if (rejected && !terminal && rejected.type !== output) {
520
+ this.context.fail(
521
+ this.expression,
522
+ "A recovery callback must return the same PLC type as the fulfilled branch.",
523
+ );
524
+ }
525
+ return {
526
+ helper: this.addHelper(
527
+ this.context.names.name(`tsplcPromiseChain${index}`, this.chain.root),
528
+ linkBody(
529
+ { ...previous, call: this.invoke(previous.helper, "") },
530
+ { fulfilled, rejected, terminal },
531
+ ),
532
+ output,
533
+ null,
534
+ ),
535
+ type: output,
536
+ aggregate: terminal
537
+ ? false
538
+ : (fulfilled?.aggregate ?? previous.aggregate),
539
+ };
540
+ }
541
+
542
+ /**
543
+ * How the chain calls a callback, declaring a helper for it when it needs one. `slot` tells the
544
+ * callbacks of one chain apart: its link and whether it fulfils or rejects.
545
+ */
546
+ private callback(
547
+ expression: ts.Expression | undefined,
548
+ inputType: string,
549
+ slot: string,
550
+ ): Callback | undefined {
551
+ if (
552
+ !expression ||
553
+ expression.kind === ts.SyntaxKind.NullKeyword ||
554
+ (ts.isIdentifier(expression) && expression.text === "undefined")
555
+ ) {
556
+ return;
557
+ }
558
+ const { context, source } = this;
559
+ const declaration = this.handlerDeclaration(expression);
560
+ const callbackSignature =
561
+ context.checker.getSignatureFromDeclaration(declaration);
562
+ const aggregate = isAggregate(
563
+ callbackSignature &&
564
+ context.checker.getAwaitedType(
565
+ context.checker.getReturnTypeOfSignature(callbackSignature),
566
+ ),
567
+ );
568
+ if (!declaration.body || declaration.parameters.length > 1) {
569
+ this.context.fail(
570
+ declaration,
571
+ "Promise callbacks take at most one value.",
572
+ );
573
+ }
574
+ if (declaration.getSourceFile() !== source) {
575
+ return this.namedCallback(expression, declaration, {
576
+ inputType,
577
+ aggregate,
578
+ slot,
579
+ });
580
+ }
581
+ const names = new Map(this.captureNames);
582
+ const parameter = declaration.parameters[0];
583
+ if (parameter) {
584
+ const symbol = ts.isIdentifier(parameter.name)
585
+ ? context.symbol(parameter.name)
586
+ : undefined;
587
+ if (!symbol) {
588
+ this.context.fail(parameter, "Promise callback parameters need names.");
589
+ }
590
+ names.set(symbol, "promiseValue");
591
+ }
592
+ const type = this.callbackType(declaration, declaration.body, {
593
+ parameter,
594
+ inputType,
595
+ });
596
+ const name = context.names.name(
597
+ `tsplcPromiseHandler${slot}`,
598
+ this.chain.root,
599
+ );
600
+ const body = this.replaceNames(declaration.body, names);
601
+ const takesInput = Boolean(parameter && inputType !== "void");
602
+ const handlerParams = [
603
+ ...(takesInput ? [`promiseValue:${inputType}`] : []),
604
+ ...this.params.map((value) => `${value.name}:${value.type}`),
605
+ ].join(",");
606
+ context.append(
607
+ this.classOwner ?? source,
608
+ declaration,
609
+ this.declare(
610
+ name,
611
+ handlerParams,
612
+ type,
613
+ this.callbackCode(declaration.body, body, type),
614
+ ),
615
+ );
616
+ return {
617
+ call: (input) =>
618
+ `${this.classOwner ? "this." : ""}${name}(${[...(takesInput ? [input] : []), ...this.params.map((value) => value.name)].join(",")})`,
619
+ type,
620
+ aggregate,
621
+ };
622
+ }
623
+
624
+ /** An inline callback, or the function declaration a named one refers to. */
625
+ private handlerDeclaration(expression: ts.Expression): Handler {
626
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression)) {
627
+ return expression;
628
+ }
629
+ const key = this.context.symbol(expression);
630
+ const named = key && this.context.routines.get(key);
631
+ if (!named || !ts.isFunctionDeclaration(named)) {
632
+ this.context.fail(
633
+ expression,
634
+ "Use a named function or inline arrow; bind instance methods with an arrow.",
635
+ );
636
+ }
637
+ return named;
638
+ }
639
+
640
+ /** Named callbacks retain their original module and access to its private state. */
641
+ private namedCallback(
642
+ expression: ts.Expression,
643
+ declaration: Handler,
644
+ {
645
+ inputType,
646
+ aggregate,
647
+ slot,
648
+ }: { inputType: string; aggregate: boolean; slot: string },
649
+ ): Callback {
650
+ const { context, source } = this;
651
+ const result = declaration.type;
652
+ if (!result) {
653
+ this.context.fail(
654
+ declaration,
655
+ "Annotate callback results with their concrete PLC type.",
656
+ );
657
+ }
658
+ const callbackType = context.typeText(
659
+ promisedType(result) ?? result,
660
+ source,
661
+ );
662
+ const name = expression.getText(source);
663
+ const takesInput = declaration.parameters.length > 0;
664
+ if (hasModifier(declaration, ts.SyntaxKind.AsyncKeyword)) {
665
+ return {
666
+ call: (input) => `${name}(${takesInput ? input : ""})`,
667
+ type: callbackType,
668
+ aggregate,
669
+ };
670
+ }
671
+ const helper = this.addHelper(
672
+ context.names.name(`tsplcPromiseNamed${slot}`, this.chain.root),
673
+ callbackType === "void"
674
+ ? `${name}(${takesInput ? "promiseInput" : ""});return;`
675
+ : `return ${name}(${takesInput ? "promiseInput" : ""});`,
676
+ callbackType,
677
+ takesInput ? inputType : null,
678
+ );
679
+ return {
680
+ call: (input) => this.invoke(helper, takesInput ? input : ""),
681
+ type: callbackType,
682
+ aggregate,
683
+ };
684
+ }
685
+
686
+ /** An inline callback's result type: its annotation, or what its body evidently returns. */
687
+ private callbackType(
688
+ declaration: Handler,
689
+ body: ts.ConciseBody,
690
+ {
691
+ parameter,
692
+ inputType,
693
+ }: {
694
+ parameter: ts.ParameterDeclaration | undefined;
695
+ inputType: string;
696
+ },
697
+ ): string {
698
+ const { context, source } = this;
699
+ const annotation = declaration.type;
700
+ if (annotation) {
701
+ return context.typeText(promisedType(annotation) ?? annotation, source);
702
+ }
703
+ const resolved = context.checker.getSignatureFromDeclaration(declaration);
704
+ const inferred =
705
+ resolved &&
706
+ context.checker.getAwaitedType(
707
+ context.checker.getReturnTypeOfSignature(resolved),
708
+ );
709
+ if (inferred && inferred.flags & ts.TypeFlags.Void) {
710
+ return "void";
711
+ }
712
+ if (ts.isBlock(body)) {
713
+ this.context.fail(
714
+ declaration,
715
+ "Annotate a callback that returns a value with its concrete PLC type.",
716
+ );
717
+ }
718
+ if (
719
+ ts.isIdentifier(body) &&
720
+ parameter &&
721
+ context.symbol(body) === context.symbol(parameter.name)
722
+ ) {
723
+ return inputType;
724
+ }
725
+ const returned = ts.isCallExpression(body)
726
+ ? operation(context, body)?.type
727
+ : undefined;
728
+ const promised = returned && promisedType(returned);
729
+ return promised
730
+ ? context.typeText(promised, source)
731
+ : this.expressionType(body);
732
+ }
733
+
734
+ /** A callback body as a helper body: a block's statements, or a returned expression. */
735
+ private callbackCode(body: ts.ConciseBody, printed: string, type: string) {
736
+ if (ts.isBlock(body)) {
737
+ return printed.slice(1, -1);
738
+ }
739
+ if (type === "void") {
740
+ return `${printed};return;`;
741
+ }
742
+ return `return ${this.isPromise(body) ? "await " : ""}${printed};`;
743
+ }
744
+
745
+ /** Prints a callback body with captures and its parameter renamed, awaiting returned promises. */
746
+ private replaceNames(
747
+ node: ts.Node,
748
+ names: ReadonlyMap<ts.Symbol, string>,
749
+ ): string {
750
+ const { context } = this;
751
+ const transformed = ts.transform(node, [
752
+ (transformation) => (root) => {
753
+ const visit = (value: ts.Node): ts.VisitResult<ts.Node> => {
754
+ if (
755
+ ts.isReturnStatement(value) &&
756
+ value.expression &&
757
+ !ts.isAwaitExpression(value.expression) &&
758
+ this.isPromise(value.expression)
759
+ ) {
760
+ return ts.factory.updateReturnStatement(
761
+ value,
762
+ ts.factory.createAwaitExpression(
763
+ ts.visitNode(value.expression, visit, ts.isExpression),
764
+ ),
765
+ );
766
+ }
767
+ if (ts.isShorthandPropertyAssignment(value)) {
768
+ const key =
769
+ context.checker.getShorthandAssignmentValueSymbol(value);
770
+ const name = key && names.get(key);
771
+ if (name) {
772
+ return ts.factory.createPropertyAssignment(
773
+ value.name,
774
+ ts.factory.createIdentifier(name),
775
+ );
776
+ }
777
+ }
778
+ if (ts.isIdentifier(value) && !isPropertyName(value)) {
779
+ const key = context.symbol(value);
780
+ const name = key && names.get(key);
781
+ if (name) {
782
+ return ts.factory.createIdentifier(name);
783
+ }
784
+ }
785
+ return ts.visitEachChild(value, visit, transformation);
786
+ };
787
+ const visited = ts.visitNode(root, visit);
788
+ if (!visited) {
789
+ throw new Error("A callback body lowered to nothing.");
790
+ }
791
+ return visited;
792
+ },
793
+ ]);
794
+ const printed = transformed.transformed
795
+ .map((root) =>
796
+ printer.printNode(ts.EmitHint.Unspecified, root, node.getSourceFile()),
797
+ )
798
+ .join("");
799
+ transformed.dispose();
800
+ return printed;
801
+ }
802
+ }
803
+
804
+ const printer = ts.createPrinter();
805
+
806
+ const isAnnotatedDeclaration = (
807
+ node: ts.Declaration,
808
+ ): node is (
809
+ | ts.VariableDeclaration
810
+ | ts.ParameterDeclaration
811
+ | ts.PropertyDeclaration
812
+ | ts.PropertySignature
813
+ ) & { type: ts.TypeNode } =>
814
+ (ts.isVariableDeclaration(node) ||
815
+ ts.isParameter(node) ||
816
+ ts.isPropertyDeclaration(node) ||
817
+ ts.isPropertySignature(node)) &&
818
+ node.type !== undefined;
819
+
820
+ /**
821
+ * A link helper's body. With both callbacks, the previous result is kept while a failure is
822
+ * caught, so the fulfilled callback runs outside the try and its own failure propagates.
823
+ */
824
+ function linkBody(
825
+ previous: Step & { call: string },
826
+ {
827
+ fulfilled,
828
+ rejected,
829
+ terminal,
830
+ }: {
831
+ fulfilled: Callback | undefined;
832
+ rejected: Callback | undefined;
833
+ terminal: boolean;
834
+ },
835
+ ): string {
836
+ const { call: prefix, type: resultType } = previous;
837
+ const success = successCode(fulfilled, resultType, terminal);
838
+ const load =
839
+ resultType === "void"
840
+ ? `await ${prefix};`
841
+ : `const promiseResult:${resultType}=await ${prefix};`;
842
+ if (rejected && fulfilled) {
843
+ const stored =
844
+ resultType === "void"
845
+ ? ""
846
+ : `let promiseResult:${resultType}=defaultValue<${resultType}>();`;
847
+ const attempt =
848
+ resultType === "void"
849
+ ? `await ${prefix};`
850
+ : `const loaded:${resultType}=await ${prefix};promiseResult=${copyValue("loaded", previous.aggregate)};`;
851
+ return `${stored}let succeeded:BOOL=false;let rejection:UDINT=0;try{${attempt}succeeded=true;}catch(promiseError){rejection=${errorCodeAlias}(promiseError);}if(!succeeded){${helperFinish(rejected.call("rejection"), rejected.type, { discard: terminal })}}${success}`;
852
+ }
853
+ if (rejected) {
854
+ return `try{${load}${success}}catch(promiseError){${helperFinish(rejected.call(`${errorCodeAlias}(promiseError)`), rejected.type, { discard: terminal })}}`;
855
+ }
856
+ return `${load}${success}`;
857
+ }
858
+
859
+ function successCode(
860
+ fulfilled: Callback | undefined,
861
+ resultType: string,
862
+ terminal: boolean,
863
+ ): string {
864
+ if (fulfilled) {
865
+ return helperFinish(fulfilled.call("promiseResult"), fulfilled.type, {
866
+ discard: terminal,
867
+ });
868
+ }
869
+ return resultType === "void" || terminal
870
+ ? "return;"
871
+ : "return promiseResult;";
872
+ }