@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -1,14 +1,29 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import ts from "typescript";
3
- import type { PromiseContext, Routine } from "./promises";
4
- import { hasModifier } from "./types";
5
-
6
- type Handler = ts.ArrowFunction | ts.FunctionExpression | Routine;
7
- type Owner = ts.FunctionDeclaration | ts.MethodDeclaration;
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;
8
23
 
9
24
  /** A `.then(fulfilled, rejected)` or `.catch(rejected)` link of a chain. */
10
25
  interface ChainLink {
11
- kind: "then" | "catch";
26
+ kind: (typeof linkKinds)[number];
12
27
  handlers: readonly ts.Expression[];
13
28
  }
14
29
 
@@ -25,60 +40,62 @@ interface HelperParameter {
25
40
  expression: string;
26
41
  }
27
42
 
28
- /** A callback as the chain calls it, with the type it resolves to. */
43
+ /** A callback as the chain calls it on an input, with the type it resolves to. */
29
44
  interface Callback {
30
- call: string;
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;
31
53
  type: string;
32
54
  aggregate: boolean;
33
55
  }
34
56
 
35
57
  const asyncRoutine = (context: PromiseContext, node: ts.Node) => {
36
- const fn = context.routines.get(context.symbol(node)!);
58
+ const symbol = context.symbol(node);
59
+ const fn = symbol && context.routines.get(symbol);
37
60
  return fn && hasModifier(fn, ts.SyntaxKind.AsyncKeyword) ? fn : undefined;
38
61
  };
39
62
 
40
63
  /** The async routine a `backgroundTasks.define` job runs. */
41
64
  const job = (context: PromiseContext, node: ts.Node) => {
42
- const declaration = context
43
- .symbol(node)
44
- ?.declarations?.find(
45
- (value) =>
46
- ts.isVariableDeclaration(value) || ts.isPropertyDeclaration(value),
47
- );
48
- if (
49
- !declaration ||
50
- (!ts.isVariableDeclaration(declaration) &&
51
- !ts.isPropertyDeclaration(declaration))
52
- ) {
53
- return;
54
- }
55
- const init = declaration.initializer;
56
- if (
57
- !init ||
58
- !ts.isCallExpression(init) ||
59
- !ts.isPropertyAccessExpression(init.expression) ||
60
- !context.namesSdk(init.expression.expression, "backgroundTasks") ||
61
- init.expression.name.text !== "define"
62
- ) {
63
- return;
64
- }
65
- return asyncRoutine(context, init.arguments[0]!);
65
+ const [work] = backgroundJob(context, context.symbol(node))?.arguments ?? [];
66
+ return work && asyncRoutine(context, work);
66
67
  };
67
68
 
68
- const callee = (call: ts.CallExpression) =>
69
- ts.isPropertyAccessExpression(call.expression)
70
- ? call.expression.name
71
- : call.expression;
72
-
73
69
  /** The async routine a call runs, directly or as a background job. */
74
- const operation = (context: PromiseContext, call: ts.CallExpression) =>
75
- asyncRoutine(context, callee(call)) ?? job(context, callee(call));
70
+ const operation = (context: PromiseContext, call: ts.CallExpression) => {
71
+ const callee = calleeName(call.expression);
72
+ return callee && (asyncRoutine(context, callee) ?? job(context, callee));
73
+ };
76
74
 
77
75
  const isSdk = (
78
76
  context: PromiseContext,
79
77
  call: ts.CallExpression,
80
78
  name: string,
81
- ) => context.namesSdk(callee(call), name);
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;
82
99
 
83
100
  /** The chain an expression is: an async call or SDK sleep or fetch, with its links. */
84
101
  export const chainOf = (
@@ -88,11 +105,9 @@ export const chainOf = (
88
105
  if (!ts.isCallExpression(expression)) {
89
106
  return;
90
107
  }
91
- if (
92
- ts.isPropertyAccessExpression(expression.expression) &&
93
- ["then", "catch"].includes(expression.expression.name.text)
94
- ) {
95
- const prefix = chainOf(context, expression.expression.expression);
108
+ const link = linkOf(expression);
109
+ if (link) {
110
+ const prefix = chainOf(context, link.target);
96
111
  if (!prefix) {
97
112
  return;
98
113
  }
@@ -100,10 +115,7 @@ export const chainOf = (
100
115
  root: prefix.root,
101
116
  links: [
102
117
  ...prefix.links,
103
- {
104
- kind: expression.expression.name.text === "then" ? "then" : "catch",
105
- handlers: expression.arguments,
106
- },
118
+ { kind: link.kind, handlers: expression.arguments },
107
119
  ],
108
120
  };
109
121
  }
@@ -124,21 +136,26 @@ export const chainOf = (
124
136
  export const lowerChain = (
125
137
  context: PromiseContext,
126
138
  expression: ts.Expression,
127
- owner: Owner,
128
- detached: boolean,
129
- ): string => new PromiseChain(context, expression, owner).lower(detached);
139
+ chain: Chain,
140
+ owner: Callable,
141
+ { detached }: { detached: boolean },
142
+ ): string =>
143
+ new PromiseChain(context, expression, chain, owner).lower({ detached });
130
144
 
131
145
  const isAggregate = (type: ts.Type | undefined) =>
132
- Boolean(type && type.flags & ts.TypeFlags.Object);
146
+ type !== undefined && isAggregateType(type);
133
147
 
134
- const helperFinish = (call: string, type: string, discard = false) =>
148
+ const helperFinish = (
149
+ call: string,
150
+ type: string,
151
+ { discard }: { discard: boolean },
152
+ ) =>
135
153
  type === "void" || discard
136
154
  ? `await ${call};return;`
137
155
  : `return await ${call};`;
138
156
 
139
157
  /** One chain being lowered: its captures, root operation and helpers. */
140
158
  class PromiseChain {
141
- private readonly chain: Chain;
142
159
  private readonly source: ts.SourceFile;
143
160
  /** The class that owns the helpers when the chain is in a method; otherwise the module does. */
144
161
  private readonly classOwner: ts.ClassDeclaration | undefined;
@@ -156,16 +173,9 @@ class PromiseChain {
156
173
  constructor(
157
174
  private readonly context: PromiseContext,
158
175
  private readonly expression: ts.Expression,
159
- private readonly owner: Owner,
176
+ private readonly chain: Chain,
177
+ private readonly owner: Callable,
160
178
  ) {
161
- const chain = chainOf(context, expression);
162
- if (!chain) {
163
- this.context.fail(
164
- expression,
165
- "Expected a statically resolved async call.",
166
- );
167
- }
168
- this.chain = chain;
169
179
  this.source = expression.getSourceFile();
170
180
  this.classOwner =
171
181
  ts.isMethodDeclaration(owner) && ts.isClassDeclaration(owner.parent)
@@ -175,12 +185,6 @@ class PromiseChain {
175
185
  context.useDiagnostics(expression);
176
186
  for (const link of chain.links) {
177
187
  for (const value of link.handlers) {
178
- if (
179
- value.kind === ts.SyntaxKind.UndefinedKeyword ||
180
- value.kind === ts.SyntaxKind.NullKeyword
181
- ) {
182
- continue;
183
- }
184
188
  if (ts.isArrowFunction(value) || ts.isFunctionExpression(value)) {
185
189
  this.collectCaptures(value);
186
190
  }
@@ -209,14 +213,7 @@ class PromiseChain {
209
213
  /** The routine's const locals and parameters a callback reads become helper parameters. */
210
214
  private collectCaptures(handler: ts.ArrowFunction | ts.FunctionExpression) {
211
215
  const visit = (node: ts.Node): void => {
212
- if (
213
- ts.isIdentifier(node) &&
214
- !(
215
- ts.isPropertyAccessExpression(node.parent) &&
216
- node.parent.name === node
217
- ) &&
218
- !(ts.isPropertyAssignment(node.parent) && node.parent.name === node)
219
- ) {
216
+ if (ts.isIdentifier(node) && !isPropertyName(node)) {
220
217
  this.capture(node);
221
218
  }
222
219
  ts.forEachChild(node, visit);
@@ -226,9 +223,7 @@ class PromiseChain {
226
223
 
227
224
  private capture(node: ts.Identifier): void {
228
225
  const { context } = this;
229
- const key = ts.isShorthandPropertyAssignment(node.parent)
230
- ? context.checker.getShorthandAssignmentValueSymbol(node.parent)
231
- : context.symbol(node);
226
+ const key = valueSymbol(context.checker, node);
232
227
  const declaration = key?.valueDeclaration;
233
228
  if (
234
229
  !key ||
@@ -255,7 +250,7 @@ class PromiseChain {
255
250
  "Annotate a captured value with its concrete PLC type.",
256
251
  );
257
252
  }
258
- if (this.hasBorrow(declaration.type)) {
253
+ if (holdsBorrow(context, declaration.type)) {
259
254
  this.context.fail(
260
255
  node,
261
256
  "A continuation cannot capture borrowed InOut storage; capture values or use controller state.",
@@ -268,42 +263,6 @@ class PromiseChain {
268
263
  });
269
264
  }
270
265
 
271
- /** Whether a type holds an InOut borrow, directly or through the layouts it names. */
272
- private hasBorrow(node: ts.TypeNode, seen = new Set<ts.Symbol>()): boolean {
273
- const { context } = this;
274
- if (ts.isTypeReferenceNode(node)) {
275
- if (context.namesSdk(node.typeName, "InOut")) {
276
- return true;
277
- }
278
- const key = context.symbol(node.typeName);
279
- if (key && !seen.has(key)) {
280
- seen.add(key);
281
- for (const declaration of key.declarations ?? []) {
282
- if (
283
- ts.isInterfaceDeclaration(declaration) &&
284
- declaration.members.some(
285
- (member) =>
286
- ts.isPropertySignature(member) &&
287
- member.type &&
288
- this.hasBorrow(member.type, seen),
289
- )
290
- ) {
291
- return true;
292
- }
293
- if (
294
- ts.isTypeAliasDeclaration(declaration) &&
295
- this.hasBorrow(declaration.type, seen)
296
- ) {
297
- return true;
298
- }
299
- }
300
- }
301
- }
302
- return node
303
- .getChildren()
304
- .some((child) => ts.isTypeNode(child) && this.hasBorrow(child, seen));
305
- }
306
-
307
266
  /** The root operation's arguments, the call that runs it, and the type it resolves to. */
308
267
  private rootCall(): {
309
268
  arguments: HelperParameter[];
@@ -314,14 +273,14 @@ class PromiseChain {
314
273
  const { root } = this.chain;
315
274
  const fn = operation(context, root);
316
275
  if (fn) {
317
- const node = fn.type;
318
- if (!node || !ts.isTypeReferenceNode(node) || !node.typeArguments?.[0]) {
276
+ const promised = fn.type && promisedType(fn.type);
277
+ if (!promised) {
319
278
  this.context.fail(
320
279
  fn,
321
280
  "Async calls need an explicit Promise<T> result.",
322
281
  );
323
282
  }
324
- const type = context.typeText(node.typeArguments[0], source);
283
+ const type = context.typeText(promised, source);
325
284
  const parameters = fn.parameters.map((parameter, index) => {
326
285
  const argument = root.arguments[index];
327
286
  if (!parameter.type || !argument) {
@@ -371,33 +330,35 @@ class PromiseChain {
371
330
  this.context.fail(root, "fetch requires a typed response.");
372
331
  }
373
332
  const type = context.typeText(response, source);
374
- const options = root.arguments[1];
333
+ const [url, options] = root.arguments;
334
+ if (!url) {
335
+ this.context.fail(root, "fetch requires a URL.");
336
+ }
375
337
  if (options && !ts.isObjectLiteralExpression(options)) {
376
338
  this.context.fail(options, "fetch options must be an inline object.");
377
339
  }
378
340
  const parameters: HelperParameter[] = [];
379
- const optionText =
380
- options && ts.isObjectLiteralExpression(options)
381
- ? options.properties
382
- .map((property) => {
383
- if (!ts.isPropertyAssignment(property)) {
384
- this.context.fail(property, "fetch requires named options.");
385
- }
386
- if (property.name.getText(source) !== "json") {
387
- return property.getText(source);
388
- }
389
- parameters.push({
390
- name: "argument0",
391
- type: this.expressionType(property.initializer),
392
- expression: property.initializer.getText(source),
393
- });
394
- return "json:argument0";
395
- })
396
- .join(",")
397
- : "";
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
+ : "";
398
359
  return {
399
360
  arguments: parameters,
400
- invocation: `${root.expression.getText(source)}<${typeArguments.map((type) => type.getText(source)).join(",")}>(${root.arguments[0]!.getText(source)}${options ? `,{${optionText}}` : ""})`,
361
+ invocation: `${root.expression.getText(source)}<${typeArguments.map((type) => type.getText(source)).join(",")}>(${url.getText(source)}${options ? `,{${optionText}}` : ""})`,
401
362
  type,
402
363
  };
403
364
  }
@@ -406,36 +367,23 @@ class PromiseChain {
406
367
  private expressionType(node: ts.Expression): string {
407
368
  const { context, source } = this;
408
369
  const { checker } = context;
370
+ const typeArgument = ts.isCallExpression(node)
371
+ ? node.typeArguments?.[0]
372
+ : undefined;
409
373
  if (
374
+ typeArgument &&
410
375
  ts.isCallExpression(node) &&
411
- node.typeArguments?.[0] &&
412
- (context.namesSdk(node.expression, "defaultValue") ||
413
- context.namesSdk(node.expression, "copy") ||
414
- ["exact", "wrap", "wrapAdd", "wrapMultiply", "saturate"].some((name) =>
415
- context.namesSdk(node.expression, name),
416
- ))
376
+ [...typeArgumentIntrinsics].some((name) =>
377
+ context.namesSdk(node.expression, name),
378
+ )
417
379
  ) {
418
- return context.typeText(node.typeArguments[0], source);
380
+ return context.typeText(typeArgument, source);
419
381
  }
420
382
  const name = ts.isPropertyAccessExpression(node) ? node.name : node;
421
383
  const declaration = context
422
384
  .symbol(name)
423
- ?.declarations?.find(
424
- (value) =>
425
- (ts.isVariableDeclaration(value) ||
426
- ts.isParameter(value) ||
427
- ts.isPropertyDeclaration(value) ||
428
- ts.isPropertySignature(value)) &&
429
- value.type,
430
- );
431
- if (
432
- declaration &&
433
- (ts.isVariableDeclaration(declaration) ||
434
- ts.isParameter(declaration) ||
435
- ts.isPropertyDeclaration(declaration) ||
436
- ts.isPropertySignature(declaration)) &&
437
- declaration.type
438
- ) {
385
+ ?.declarations?.find(isAnnotatedDeclaration);
386
+ if (declaration) {
439
387
  return context.typeText(declaration.type, source);
440
388
  }
441
389
  const type = checker.getTypeAtLocation(node);
@@ -445,21 +393,12 @@ class PromiseChain {
445
393
  if (type.flags & ts.TypeFlags.Void) {
446
394
  return "void";
447
395
  }
448
- if (
449
- type.symbol &&
450
- type.symbol.name !== "__type" &&
451
- type.flags & ts.TypeFlags.Object
452
- ) {
453
- return checker.typeToString(
454
- type,
396
+ return (
397
+ namedRecordText(checker, node) ??
398
+ this.context.fail(
455
399
  node,
456
- ts.TypeFormatFlags.NoTruncation |
457
- ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
458
- );
459
- }
460
- this.context.fail(
461
- node,
462
- "Annotate this value with its concrete PLC type before using it in an async continuation.",
400
+ "Annotate this value with its concrete PLC type before using it in an async continuation.",
401
+ )
463
402
  );
464
403
  }
465
404
 
@@ -480,12 +419,15 @@ class PromiseChain {
480
419
  return `${classOwner ? "private " : "export "}async ${classOwner ? "" : "function "}${name}(${parameters}):Promise<${type}>{${body}}`;
481
420
  }
482
421
 
483
- /** Declares a helper that takes the chain's parameters, and returns the call to it. */
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
+ */
484
426
  private addHelper(
485
427
  name: string,
486
428
  body: string,
487
429
  type: string,
488
- extra?: { type: string; argument: string },
430
+ input: string | null,
489
431
  ): string {
490
432
  const { classOwner } = this;
491
433
  this.context.append(
@@ -493,24 +435,30 @@ class PromiseChain {
493
435
  this.expression,
494
436
  this.declare(
495
437
  name,
496
- [this.signature, extra ? `promiseInput:${extra.type}` : ""]
438
+ [this.signature, input === null ? "" : `promiseInput:${input}`]
497
439
  .filter(Boolean)
498
440
  .join(","),
499
441
  type,
500
442
  body,
501
443
  ),
502
444
  );
503
- return `${classOwner ? "this." : ""}${name}(${[this.args, extra?.argument ?? ""].filter(Boolean).join(",")})`;
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(",")})`;
504
451
  }
505
452
 
506
- lower(detached: boolean): string {
453
+ lower({ detached }: { detached: boolean }): string {
507
454
  const { context, classOwner, source } = this;
508
455
  const links = this.chain.links;
509
- let lowered = {
510
- call: this.addHelper(
456
+ const operation: Step = {
457
+ helper: this.addHelper(
511
458
  context.names.name("tsplcPromiseOperation", this.chain.root),
512
- helperFinish(this.rootInvocation, this.rootType),
459
+ helperFinish(this.rootInvocation, this.rootType, { discard: false }),
513
460
  this.rootType,
461
+ null,
514
462
  ),
515
463
  type: this.rootType,
516
464
  aggregate: isAggregate(
@@ -519,25 +467,30 @@ class PromiseChain {
519
467
  ),
520
468
  ),
521
469
  };
522
- for (const [index, link] of links.entries()) {
523
- lowered = this.link(link, lowered, {
524
- terminal: detached && index === links.length - 1,
525
- index,
526
- });
527
- }
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
+ );
528
478
  const values = this.params.map((value) => value.expression).join(",");
529
479
  if (!detached) {
530
- return lowered.call.replace(`(${this.args})`, `(${values})`);
480
+ return `${last.helper}(${values})`;
531
481
  }
532
482
  const site = context.names.name("tsplcPromiseSite", this.chain.root);
533
- const callable = lowered.call.slice(0, lowered.call.indexOf("("));
534
483
  const scope = classOwner ?? source;
535
484
  context.append(
536
485
  scope,
537
486
  this.expression,
538
- `${classOwner ? "private " : "const "}${site}=tsplcCooperative.define(${callable});`,
487
+ `${classOwner ? "private " : "const "}${site}=${cooperativeTasksAlias}.define(${last.helper});`,
539
488
  );
540
- context.sites.set(scope, [...(context.sites.get(scope) ?? []), site]);
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
+ ]);
541
494
  return `${classOwner ? "this." : ""}${site}.start(${values});`;
542
495
  }
543
496
 
@@ -547,22 +500,16 @@ class PromiseChain {
547
500
  */
548
501
  private link(
549
502
  link: ChainLink,
550
- previous: Callback,
503
+ previous: Step,
551
504
  { terminal, index }: { terminal: boolean; index: number },
552
- ): Callback {
505
+ ): Step {
553
506
  const fulfilled =
554
507
  link.kind === "then"
555
- ? this.callback(
556
- link.handlers[0],
557
- previous.type,
558
- "promiseResult",
559
- `${index}Fulfilled`,
560
- )
508
+ ? this.callback(link.handlers[0], previous.type, `${index}Fulfilled`)
561
509
  : undefined;
562
510
  const rejected = this.callback(
563
511
  link.handlers[link.kind === "catch" ? 0 : 1],
564
512
  "UDINT",
565
- "tsplcErrorCode(promiseError)",
566
513
  `${index}Rejected`,
567
514
  );
568
515
  if (!fulfilled && !rejected) {
@@ -576,10 +523,14 @@ class PromiseChain {
576
523
  );
577
524
  }
578
525
  return {
579
- call: this.addHelper(
526
+ helper: this.addHelper(
580
527
  this.context.names.name(`tsplcPromiseChain${index}`, this.chain.root),
581
- linkBody(previous, { fulfilled, rejected, terminal }),
528
+ linkBody(
529
+ { ...previous, call: this.invoke(previous.helper, "") },
530
+ { fulfilled, rejected, terminal },
531
+ ),
582
532
  output,
533
+ null,
583
534
  ),
584
535
  type: output,
585
536
  aggregate: terminal
@@ -588,12 +539,13 @@ class PromiseChain {
588
539
  };
589
540
  }
590
541
 
591
- /** How the chain calls a callback, declaring a helper for it when it needs one. */
592
- /** `slot` tells the callbacks of one chain apart: its link and whether it fulfils or rejects. */
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
+ */
593
546
  private callback(
594
547
  expression: ts.Expression | undefined,
595
548
  inputType: string,
596
- input: string,
597
549
  slot: string,
598
550
  ): Callback | undefined {
599
551
  if (
@@ -622,7 +574,6 @@ class PromiseChain {
622
574
  if (declaration.getSourceFile() !== source) {
623
575
  return this.namedCallback(expression, declaration, {
624
576
  inputType,
625
- input,
626
577
  aggregate,
627
578
  slot,
628
579
  });
@@ -630,10 +581,13 @@ class PromiseChain {
630
581
  const names = new Map(this.captureNames);
631
582
  const parameter = declaration.parameters[0];
632
583
  if (parameter) {
633
- if (!ts.isIdentifier(parameter.name)) {
584
+ const symbol = ts.isIdentifier(parameter.name)
585
+ ? context.symbol(parameter.name)
586
+ : undefined;
587
+ if (!symbol) {
634
588
  this.context.fail(parameter, "Promise callback parameters need names.");
635
589
  }
636
- names.set(context.symbol(parameter.name)!, "promiseValue");
590
+ names.set(symbol, "promiseValue");
637
591
  }
638
592
  const type = this.callbackType(declaration, declaration.body, {
639
593
  parameter,
@@ -660,7 +614,8 @@ class PromiseChain {
660
614
  ),
661
615
  );
662
616
  return {
663
- call: `${this.classOwner ? "this." : ""}${name}(${[...(takesInput ? [input] : []), ...this.params.map((value) => value.name)].join(",")})`,
617
+ call: (input) =>
618
+ `${this.classOwner ? "this." : ""}${name}(${[...(takesInput ? [input] : []), ...this.params.map((value) => value.name)].join(",")})`,
664
619
  type,
665
620
  aggregate,
666
621
  };
@@ -688,10 +643,9 @@ class PromiseChain {
688
643
  declaration: Handler,
689
644
  {
690
645
  inputType,
691
- input,
692
646
  aggregate,
693
647
  slot,
694
- }: { inputType: string; input: string; aggregate: boolean; slot: string },
648
+ }: { inputType: string; aggregate: boolean; slot: string },
695
649
  ): Callback {
696
650
  const { context, source } = this;
697
651
  const result = declaration.type;
@@ -701,30 +655,29 @@ class PromiseChain {
701
655
  "Annotate callback results with their concrete PLC type.",
702
656
  );
703
657
  }
704
- const output =
705
- ts.isTypeReferenceNode(result) &&
706
- result.typeName.getText(declaration.getSourceFile()) === "Promise"
707
- ? result.typeArguments![0]!
708
- : result;
709
- const callbackType = context.typeText(output, source);
658
+ const callbackType = context.typeText(
659
+ promisedType(result) ?? result,
660
+ source,
661
+ );
710
662
  const name = expression.getText(source);
711
663
  const takesInput = declaration.parameters.length > 0;
712
664
  if (hasModifier(declaration, ts.SyntaxKind.AsyncKeyword)) {
713
665
  return {
714
- call: `${name}(${takesInput ? input : ""})`,
666
+ call: (input) => `${name}(${takesInput ? input : ""})`,
715
667
  type: callbackType,
716
668
  aggregate,
717
669
  };
718
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
+ );
719
679
  return {
720
- call: this.addHelper(
721
- context.names.name(`tsplcPromiseNamed${slot}`, this.chain.root),
722
- callbackType === "void"
723
- ? `${name}(${takesInput ? "promiseInput" : ""});return;`
724
- : `return ${name}(${takesInput ? "promiseInput" : ""});`,
725
- callbackType,
726
- takesInput ? { type: inputType, argument: input } : undefined,
727
- ),
680
+ call: (input) => this.invoke(helper, takesInput ? input : ""),
728
681
  type: callbackType,
729
682
  aggregate,
730
683
  };
@@ -745,10 +698,7 @@ class PromiseChain {
745
698
  const { context, source } = this;
746
699
  const annotation = declaration.type;
747
700
  if (annotation) {
748
- return ts.isTypeReferenceNode(annotation) &&
749
- annotation.typeName.getText(source) === "Promise"
750
- ? context.typeText(annotation.typeArguments![0]!, source)
751
- : context.typeText(annotation, source);
701
+ return context.typeText(promisedType(annotation) ?? annotation, source);
752
702
  }
753
703
  const resolved = context.checker.getSignatureFromDeclaration(declaration);
754
704
  const inferred =
@@ -756,7 +706,7 @@ class PromiseChain {
756
706
  context.checker.getAwaitedType(
757
707
  context.checker.getReturnTypeOfSignature(resolved),
758
708
  );
759
- if (inferred?.flags && inferred.flags & ts.TypeFlags.Void) {
709
+ if (inferred && inferred.flags & ts.TypeFlags.Void) {
760
710
  return "void";
761
711
  }
762
712
  if (ts.isBlock(body)) {
@@ -765,7 +715,6 @@ class PromiseChain {
765
715
  "Annotate a callback that returns a value with its concrete PLC type.",
766
716
  );
767
717
  }
768
- // `value => value` passes the input through.
769
718
  if (
770
719
  ts.isIdentifier(body) &&
771
720
  parameter &&
@@ -774,10 +723,11 @@ class PromiseChain {
774
723
  return inputType;
775
724
  }
776
725
  const returned = ts.isCallExpression(body)
777
- ? operation(context, body)
726
+ ? operation(context, body)?.type
778
727
  : undefined;
779
- return returned?.type && ts.isTypeReferenceNode(returned.type)
780
- ? context.typeText(returned.type.typeArguments![0]!, source)
728
+ const promised = returned && promisedType(returned);
729
+ return promised
730
+ ? context.typeText(promised, source)
781
731
  : this.expressionType(body);
782
732
  }
783
733
 
@@ -810,7 +760,7 @@ class PromiseChain {
810
760
  return ts.factory.updateReturnStatement(
811
761
  value,
812
762
  ts.factory.createAwaitExpression(
813
- ts.visitNode(value.expression, visit) as ts.Expression,
763
+ ts.visitNode(value.expression, visit, ts.isExpression),
814
764
  ),
815
765
  );
816
766
  }
@@ -825,17 +775,7 @@ class PromiseChain {
825
775
  );
826
776
  }
827
777
  }
828
- if (
829
- ts.isIdentifier(value) &&
830
- !(
831
- ts.isPropertyAccessExpression(value.parent) &&
832
- value.parent.name === value
833
- ) &&
834
- !(
835
- ts.isPropertyAssignment(value.parent) &&
836
- value.parent.name === value
837
- )
838
- ) {
778
+ if (ts.isIdentifier(value) && !isPropertyName(value)) {
839
779
  const key = context.symbol(value);
840
780
  const name = key && names.get(key);
841
781
  if (name) {
@@ -844,14 +784,18 @@ class PromiseChain {
844
784
  }
845
785
  return ts.visitEachChild(value, visit, transformation);
846
786
  };
847
- return ts.visitNode(root, visit) as typeof root;
787
+ const visited = ts.visitNode(root, visit);
788
+ if (!visited) {
789
+ throw new Error("A callback body lowered to nothing.");
790
+ }
791
+ return visited;
848
792
  },
849
793
  ]);
850
- const printed = printer.printNode(
851
- ts.EmitHint.Unspecified,
852
- transformed.transformed[0]!,
853
- node.getSourceFile(),
854
- );
794
+ const printed = transformed.transformed
795
+ .map((root) =>
796
+ printer.printNode(ts.EmitHint.Unspecified, root, node.getSourceFile()),
797
+ )
798
+ .join("");
855
799
  transformed.dispose();
856
800
  return printed;
857
801
  }
@@ -859,12 +803,26 @@ class PromiseChain {
859
803
 
860
804
  const printer = ts.createPrinter();
861
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
+
862
820
  /**
863
821
  * A link helper's body. With both callbacks, the previous result is kept while a failure is
864
822
  * caught, so the fulfilled callback runs outside the try and its own failure propagates.
865
823
  */
866
824
  function linkBody(
867
- previous: Callback,
825
+ previous: Step & { call: string },
868
826
  {
869
827
  fulfilled,
870
828
  rejected,
@@ -889,11 +847,11 @@ function linkBody(
889
847
  const attempt =
890
848
  resultType === "void"
891
849
  ? `await ${prefix};`
892
- : `const loaded:${resultType}=await ${prefix};promiseResult=${previous.aggregate ? "copy(loaded)" : "loaded"};`;
893
- 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}`;
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}`;
894
852
  }
895
853
  if (rejected) {
896
- return `try{${load}${success}}catch(promiseError){${helperFinish(rejected.call, rejected.type, terminal)}}`;
854
+ return `try{${load}${success}}catch(promiseError){${helperFinish(rejected.call(`${errorCodeAlias}(promiseError)`), rejected.type, { discard: terminal })}}`;
897
855
  }
898
856
  return `${load}${success}`;
899
857
  }
@@ -904,7 +862,9 @@ function successCode(
904
862
  terminal: boolean,
905
863
  ): string {
906
864
  if (fulfilled) {
907
- return helperFinish(fulfilled.call, fulfilled.type, terminal);
865
+ return helperFinish(fulfilled.call("promiseResult"), fulfilled.type, {
866
+ discard: terminal,
867
+ });
908
868
  }
909
869
  return resultType === "void" || terminal
910
870
  ? "return;"