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