@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,17 +1,16 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
- import { identityDigest, jobError, reservedErrors } from "@tsplc/compiler/ir";
1
+ import {
2
+ type HttpMethod,
3
+ httpMethods,
4
+ identityDigest,
5
+ jobError,
6
+ reservedErrors,
7
+ } from "@tsplc/compiler/ir";
8
+ import { jobStateFields } from "@tsplc/debug/manifest";
3
9
  import ts from "typescript";
4
- import type {
5
- AsyncContext,
6
- Job,
7
- MethodMembers,
8
- Routine,
9
- SourceRewrite,
10
- } from "./async";
11
- import { staticString } from "./configuration";
10
+ import type { AsyncContext, Job, MethodMembers, SourceRewrite } from "./async";
12
11
  import { copyValue } from "./cooperative";
13
- import type { GeneratedNames } from "./generated-names";
14
- import { importSpecifier } from "./module-graph";
12
+ import { loweringKey } from "./lowering-key";
13
+ import type { NamedRoutine } from "./module-graph";
15
14
  import {
16
15
  copied,
17
16
  type Edit,
@@ -22,12 +21,49 @@ import {
22
21
  mapped,
23
22
  type Part,
24
23
  } from "./positions";
25
- import { hasModifier } from "./types";
24
+ import { holdsBorrow, symbolAt } from "./sdk";
25
+ import { backgroundJob } from "./tasks";
26
+ import {
27
+ calleeName,
28
+ hasModifier,
29
+ isAggregateType,
30
+ isPropertyName,
31
+ namedRecordText,
32
+ promisedType,
33
+ } from "./types";
26
34
 
27
35
  type Step = Job["steps"][number];
28
36
  /** What a step does when the operation it waits on fails; `cancellable` failures may be a cancel. */
29
- type Reject = (error: Part, cancellable?: boolean) => Part;
30
- type FetchMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
37
+ type Reject = (error: Part, options: { cancellable: boolean }) => Part;
38
+
39
+ /**
40
+ * How the generated code names what it reads on its block: the members the coroutine adds, the
41
+ * methods that run it, and, in an async method, the members of the method's own class.
42
+ */
43
+ interface Naming {
44
+ member: (name: string) => string;
45
+ /** A method's declaration, with its modifier. */
46
+ entry: (name: keyof MethodMembers) => string;
47
+ /** `this.name` of a method's own class; undefined in a function, which has none. */
48
+ own: ((name: string) => string) | undefined;
49
+ }
50
+
51
+ const blockEntries: Record<keyof MethodMembers, string> = {
52
+ start: "start",
53
+ reset: "reset",
54
+ snapshot: "snapshot",
55
+ advance: "protected execute",
56
+ };
57
+
58
+ /** An async function's own block. */
59
+ const blockNaming: Naming = {
60
+ member: (name) => name,
61
+ entry: (name) => blockEntries[name],
62
+ own: undefined,
63
+ };
64
+
65
+ const isHttpMethod = (value: string | undefined): value is HttpMethod =>
66
+ httpMethods.some((method) => method === value);
31
67
 
32
68
  /** A parameter, local or caught error, which lives on the block across suspensions. */
33
69
  interface Field {
@@ -58,9 +94,14 @@ const containsAwait = (node: ts.Node, source: ts.SourceFile): boolean =>
58
94
  ts.isAwaitExpression(node) ||
59
95
  node.getChildren(source).some((child) => containsAwait(child, source));
60
96
 
61
- /** The prefix of the type aliases a routine's module exports for its result and arguments. */
62
- export const aliasPrefix = (names: GeneratedNames, fn: Routine) =>
63
- names.name(`TsplcAsync${fn.name.getText(fn.getSourceFile())}`, fn);
97
+ /** Whether the coroutine copies a statement into one step as written, rather than lowering it into steps. */
98
+ export const copiedWhole = (
99
+ statement: ts.Statement,
100
+ source: ts.SourceFile,
101
+ ): boolean =>
102
+ ts.isSwitchStatement(statement) ||
103
+ (ts.isIterationStatement(statement, false) &&
104
+ !containsAwait(statement, source));
64
105
 
65
106
  /**
66
107
  * A job's code identity: its steps, their targets and the state they keep. A job stores it when it
@@ -70,13 +111,160 @@ export const aliasPrefix = (names: GeneratedNames, fn: Routine) =>
70
111
  const codeDigest = (code: string): number =>
71
112
  Number.parseInt(identityDigest(code), 16) || 1;
72
113
 
73
- /** Replaces an async routine with a block that runs it as a resumable state machine. */
114
+ /** URL expressions are compile-time values, never reads from mutable PLC state. */
115
+ const staticString = (
116
+ checker: ts.TypeChecker,
117
+ root: ts.Expression,
118
+ ): string | undefined => {
119
+ const active = new Set<ts.Node>();
120
+ const valueNode = (node: ts.Node): ts.Node | undefined => {
121
+ if (ts.isParenthesizedExpression(node)) {
122
+ return node.expression;
123
+ }
124
+ if (ts.isIdentifier(node)) {
125
+ const declaration = symbolAt(checker, node)?.declarations?.find(
126
+ ts.isVariableDeclaration,
127
+ );
128
+ if (
129
+ declaration &&
130
+ ts.isVariableDeclarationList(declaration.parent) &&
131
+ declaration.parent.flags & ts.NodeFlags.Const
132
+ ) {
133
+ return declaration.initializer;
134
+ }
135
+ }
136
+ if (ts.isPropertyAccessExpression(node)) {
137
+ const field = symbolAt(checker, node.name);
138
+ if (
139
+ !field?.declarations?.some(
140
+ (declaration) =>
141
+ ts.canHaveModifiers(declaration) &&
142
+ hasModifier(declaration, ts.SyntaxKind.ReadonlyKeyword),
143
+ )
144
+ ) {
145
+ return;
146
+ }
147
+ const object = resolve(node.expression);
148
+ if (object && ts.isObjectLiteralExpression(object)) {
149
+ for (const property of object.properties) {
150
+ if (
151
+ ts.isPropertyAssignment(property) &&
152
+ (ts.isIdentifier(property.name) ||
153
+ ts.isStringLiteral(property.name)) &&
154
+ property.name.text === node.name.text
155
+ ) {
156
+ return property.initializer;
157
+ }
158
+ }
159
+ }
160
+ return;
161
+ }
162
+ return node;
163
+ };
164
+ const resolve = (node: ts.Node): ts.Node | undefined => {
165
+ if (active.has(node)) {
166
+ return;
167
+ }
168
+ active.add(node);
169
+ try {
170
+ const next = valueNode(node);
171
+ return next && next !== node ? resolve(next) : next;
172
+ } finally {
173
+ active.delete(node);
174
+ }
175
+ };
176
+ const read = (node: ts.Node): string | undefined => {
177
+ const resolved = resolve(node);
178
+ if (!resolved || active.has(resolved)) {
179
+ return;
180
+ }
181
+ active.add(resolved);
182
+ try {
183
+ if (
184
+ ts.isStringLiteral(resolved) ||
185
+ ts.isNoSubstitutionTemplateLiteral(resolved)
186
+ ) {
187
+ return resolved.text;
188
+ }
189
+ if (ts.isTemplateExpression(resolved)) {
190
+ let value = resolved.head.text;
191
+ for (const part of resolved.templateSpans) {
192
+ const item = read(part.expression);
193
+ if (item === undefined) {
194
+ return;
195
+ }
196
+ value += item + part.literal.text;
197
+ }
198
+ return value;
199
+ }
200
+ if (
201
+ ts.isBinaryExpression(resolved) &&
202
+ resolved.operatorToken.kind === ts.SyntaxKind.PlusToken
203
+ ) {
204
+ const left = read(resolved.left);
205
+ const right = read(resolved.right);
206
+ if (left !== undefined && right !== undefined) {
207
+ return left + right;
208
+ }
209
+ }
210
+ } finally {
211
+ active.delete(resolved);
212
+ }
213
+ };
214
+ return read(root);
215
+ };
216
+
217
+ /**
218
+ * Replaces an async routine with a block that runs it as a resumable state machine. An async
219
+ * method's block joins its own class as members, renamed apart from the class's own.
220
+ */
74
221
  export function lowerCoroutine(
75
222
  context: AsyncContext,
76
223
  file: SourceRewrite,
77
- fn: Routine,
224
+ fn: NamedRoutine,
78
225
  ): void {
79
- new Coroutine(context, file, fn).lower();
226
+ const symbol = context.symbol(fn.name);
227
+ const method = symbol && context.methods.get(symbol);
228
+ const replace = (text: Part) =>
229
+ file.replacements.push({
230
+ start: fn.getStart(file.source),
231
+ end: fn.end,
232
+ text,
233
+ });
234
+ if (!method) {
235
+ const coroutine = new Coroutine(context, file, fn, blockNaming);
236
+ replace(coroutine.blockClass(coroutine.digest()));
237
+ const name = fn.name.getText(file.source);
238
+ file.jobs.set(loweringKey(file.source.fileName, name), {
239
+ name,
240
+ span: context.positions.node(fn),
241
+ steps: coroutine.steps,
242
+ });
243
+ return;
244
+ }
245
+ // The digest is of the code as a block of its own would run it, with the class's members as
246
+ // `this["name"]`, which keeps the digests an online change compares from one build to the next.
247
+ const code = new Coroutine(
248
+ context,
249
+ {
250
+ source: file.source,
251
+ extra: [],
252
+ importedAliases: new Set(),
253
+ blocks: new Map(),
254
+ },
255
+ fn,
256
+ {
257
+ ...blockNaming,
258
+ own: (name) => `this[${JSON.stringify(name)}]`,
259
+ },
260
+ ).digest();
261
+ const prefix = context.names.name("tsplcAsync", fn);
262
+ const members = new Coroutine(context, file, fn, {
263
+ member: (name) => `${prefix}_${name}`,
264
+ entry: (name) => `public ${method[name]}`,
265
+ own: (name) => `this.${name}`,
266
+ }).members(code);
267
+ replace(joined(members, "\n"));
80
268
  }
81
269
 
82
270
  /**
@@ -84,93 +272,80 @@ export function lowerCoroutine(
84
272
  * machine; awaiting an operation adds a child block or borrow that the steps start and poll.
85
273
  */
86
274
  class Coroutine {
87
- private readonly method: MethodMembers | undefined;
88
275
  private readonly body: ts.Block;
89
276
  private readonly returnsVoid: boolean;
90
- // biome-ignore lint/correctness/noUnusedPrivateClassMembers: Read through destructuring in the return emitter.
91
277
  private readonly returnType: string;
92
278
  private readonly resultAggregate: boolean;
93
279
  private readonly fields = new Map<ts.Symbol, Field>();
94
- /** The index each for…of that suspends has reached in its array. */
95
- private readonly positionFields = new Map<ts.ForOfStatement, string>();
96
280
  private readonly parameters: (Field & { field: string })[];
97
281
  private readonly states = new Map<number, Mapped>();
98
282
  /** The loops that suspend, innermost last, with the steps their break and continue go to. */
99
283
  private readonly loops: { breakStep: number; continueStep: number }[] = [];
100
284
  private readonly yielding = new Set<number>();
101
- private readonly steps: Step[] = [];
285
+ readonly steps: Step[] = [];
102
286
  private readonly children: string[] = [];
103
287
  private readonly resets: string[] = [];
104
288
  private readonly cancels: string[] = [];
105
289
 
290
+ private readonly entry: number;
291
+
106
292
  constructor(
107
293
  private readonly context: AsyncContext,
108
- private readonly file: SourceRewrite,
109
- private readonly fn: Routine,
294
+ private readonly file: Pick<
295
+ SourceRewrite,
296
+ "source" | "extra" | "importedAliases" | "blocks"
297
+ >,
298
+ private readonly fn: NamedRoutine,
299
+ private readonly naming: Naming,
110
300
  ) {
111
- this.method = context.methods.get(context.symbol(fn.name)!);
112
- if (
113
- !fn.body ||
114
- fn.typeParameters?.length ||
115
- !fn.type ||
116
- !ts.isTypeReferenceNode(fn.type) ||
117
- fn.type.typeName.getText(file.source) !== "Promise" ||
118
- fn.type.typeArguments?.length !== 1
119
- ) {
301
+ const promised = fn.type && promisedType(fn.type);
302
+ if (!fn.body || fn.typeParameters?.length || !promised) {
120
303
  context.fail(
121
304
  fn,
122
305
  "Async functions require concrete parameters and an explicit Promise<T> result.",
123
306
  );
124
307
  }
125
- const promised = fn.type.typeArguments[0]!;
126
308
  this.body = fn.body;
127
309
  this.returnsVoid = promised.kind === ts.SyntaxKind.VoidKeyword;
128
310
  this.returnType = this.returnsVoid ? "BOOL" : this.text(promised);
129
- this.resultAggregate = Boolean(
130
- context.checker.getTypeFromTypeNode(promised).flags & ts.TypeFlags.Object,
311
+ this.resultAggregate = isAggregateType(
312
+ context.checker.getTypeFromTypeNode(promised),
131
313
  );
132
314
  this.parameters = fn.parameters.map((parameter, index) =>
133
315
  this.parameter(parameter, index),
134
316
  );
135
317
  this.collect(fn.body);
318
+ const end = this.body.getLastToken(file.source);
319
+ if (!end) {
320
+ throw new Error("A block body ends in a brace.");
321
+ }
322
+ this.entry = this.block(
323
+ this.body.statements,
324
+ this.returnsVoid
325
+ ? this.state(this.finish("true"), end, "return", { yields: false })
326
+ : this.state(this.failure(jobError.malformedResponse), end, "throw", {
327
+ yields: false,
328
+ }),
329
+ (error) => this.failure(error),
330
+ );
136
331
  }
137
332
 
138
333
  private text(node: ts.Node): string {
139
334
  return node.getText(this.file.source);
140
335
  }
141
336
 
142
- lower(): void {
143
- const { fn, file, method } = this;
144
- // Running off the end of the body: a void routine returns, any other fails.
145
- const end = this.body.getLastToken(file.source)!;
146
- const entry = this.block(
147
- this.body.statements,
148
- this.returnsVoid
149
- ? this.state(this.finish("true"), end, "return")
150
- : this.state(this.failure("4"), end, "throw"),
151
- );
152
- const generated = this.generate(entry);
153
- if (!method) {
154
- file.replacements.push({
155
- start: fn.getStart(file.source),
156
- end: fn.end,
157
- text: generated,
158
- });
159
- this.context.result.jobs.set(
160
- `${file.source.fileName}:${this.text(fn.name)}`,
161
- {
162
- name: this.text(fn.name),
163
- span: this.context.positions.node(fn),
164
- steps: this.steps,
165
- },
166
- );
167
- return;
337
+ /** `this.name` of a member the coroutine adds. */
338
+ private self(name: string): string {
339
+ return `this.${this.naming.member(name)}`;
340
+ }
341
+
342
+ /** A symbol the program declares, which every declaration the coroutine reads has. */
343
+ private declared(node: ts.Node): ts.Symbol {
344
+ const symbol = this.context.symbol(node);
345
+ if (!symbol) {
346
+ throw new Error(`${node.getText(this.file.source)} declares no symbol.`);
168
347
  }
169
- file.replacements.push({
170
- start: fn.getStart(file.source),
171
- end: fn.end,
172
- text: this.methodMembers(generated, method),
173
- });
348
+ return symbol;
174
349
  }
175
350
 
176
351
  private parameter(
@@ -189,28 +364,23 @@ class Coroutine {
189
364
  "Async parameters require explicit concrete value types.",
190
365
  );
191
366
  }
192
- if (/\bInOut\b/.test(this.text(parameter.type))) {
367
+ if (holdsBorrow(this.context, parameter.type)) {
193
368
  this.context.fail(
194
369
  parameter,
195
370
  "InOut cannot cross an async suspension; pass a value snapshot.",
196
371
  );
197
372
  }
198
373
  const type = this.text(parameter.type);
199
- const aggregate = Boolean(
200
- this.context.checker.getTypeFromTypeNode(parameter.type).flags &
201
- ts.TypeFlags.Object,
374
+ const aggregate = isAggregateType(
375
+ this.context.checker.getTypeFromTypeNode(parameter.type),
202
376
  );
203
- this.fields.set(this.context.symbol(parameter.name)!, {
204
- name: `argument${index}`,
377
+ const field = `argument${index}`;
378
+ this.fields.set(this.declared(parameter.name), {
379
+ name: field,
205
380
  type,
206
381
  aggregate,
207
382
  });
208
- return {
209
- name: parameter.name.text,
210
- type,
211
- aggregate,
212
- field: `argument${index}`,
213
- };
383
+ return { name: parameter.name.text, type, aggregate, field };
214
384
  }
215
385
 
216
386
  /** Moves the routine's locals and caught errors onto the block, and rejects what cannot suspend. */
@@ -218,12 +388,15 @@ class Coroutine {
218
388
  // A loop that doesn't suspend runs within one step, with its own locals.
219
389
  if (
220
390
  ts.isIterationStatement(node, false) &&
221
- !containsAwait(node, this.file.source)
391
+ copiedWhole(node, this.file.source)
222
392
  ) {
223
393
  return;
224
394
  }
225
395
  if (ts.isForOfStatement(node)) {
226
- this.collectForOf(node);
396
+ this.context.fail(
397
+ node,
398
+ "A for…of whose body awaits is not supported; count through the array's indexes with a for loop.",
399
+ );
227
400
  }
228
401
  if (ts.isFunctionLike(node) && node !== this.fn) {
229
402
  this.context.fail(
@@ -240,7 +413,7 @@ class Coroutine {
240
413
  "Catch requires a named error code or no binding.",
241
414
  );
242
415
  }
243
- this.fields.set(this.context.symbol(declaration.name)!, {
416
+ this.fields.set(this.declared(declaration.name), {
244
417
  name: `caught${this.fields.size}`,
245
418
  type: "UDINT",
246
419
  aggregate: false,
@@ -262,41 +435,17 @@ class Coroutine {
262
435
  "Annotate async locals with their concrete PLC type.",
263
436
  );
264
437
  }
265
- this.fields.set(this.context.symbol(node.name)!, {
438
+ this.fields.set(this.declared(node.name), {
266
439
  name: `local${this.fields.size}`,
267
440
  type,
268
- aggregate: Boolean(
269
- this.context.checker.getTypeAtLocation(node).flags &
270
- ts.TypeFlags.Object,
441
+ aggregate: isAggregateType(
442
+ this.context.checker.getTypeAtLocation(node),
271
443
  ),
272
444
  });
273
445
  }
274
446
  ts.forEachChild(node, (child) => this.collect(child));
275
447
  }
276
448
 
277
- /** A for…of that suspends keeps its position in the array, and its element, between steps. */
278
- private collectForOf(node: ts.ForOfStatement): void {
279
- const declaration = ts.isVariableDeclarationList(node.initializer)
280
- ? node.initializer.declarations[0]
281
- : undefined;
282
- if (!declaration || !ts.isIdentifier(declaration.name)) {
283
- this.context.fail(
284
- node.initializer,
285
- "A for…of that awaits declares one named element.",
286
- );
287
- }
288
- const { checker } = this.context;
289
- const element = checker.getTypeAtLocation(declaration.name);
290
- this.fields.set(this.context.symbol(declaration.name)!, {
291
- name: `local${this.fields.size}`,
292
- type: declaration.type
293
- ? this.text(declaration.type)
294
- : checker.typeToString(element),
295
- aggregate: Boolean(element.flags & ts.TypeFlags.Object),
296
- });
297
- this.positionFields.set(node, `position${this.positionFields.size}`);
298
- }
299
-
300
449
  /** An unannotated local's type: BOOL for a boolean literal, or the result of the routine it awaits. */
301
450
  private inferredType(
302
451
  node: ts.VariableDeclaration,
@@ -314,27 +463,19 @@ class Coroutine {
314
463
  ) {
315
464
  return undefined;
316
465
  }
317
- const call = initializer.expression;
318
- const target = ts.isPropertyAccessExpression(call.expression)
319
- ? call.expression.name
320
- : call.expression;
321
- const called = this.context.functions.get(this.context.symbol(target)!);
322
- if (!called?.type || !ts.isTypeReferenceNode(called.type)) {
466
+ const target = calleeName(initializer.expression.expression);
467
+ const symbol = target && this.context.symbol(target);
468
+ const called = symbol && this.context.functions.get(symbol);
469
+ const promised = called?.type && promisedType(called.type);
470
+ if (!called || !promised) {
323
471
  return undefined;
324
472
  }
325
- const { source, extra } = this.file;
326
- const annotated = called.type.typeArguments![0]!.getText(
327
- called.getSourceFile(),
328
- );
473
+ const { source } = this.file;
329
474
  if (called.getSourceFile() === source) {
330
- return annotated;
331
- }
332
- // Another module's result type is named through the alias its coroutine exports.
333
- const type = `${aliasPrefix(this.context.names, called)}Result`;
334
- const statement = `import type {${type}} from ${importSpecifier(source.fileName, called.getSourceFile().fileName)};`;
335
- if (!extra.some((item) => item.text === statement)) {
336
- extra.push(from(node, statement));
475
+ return promised.getText(source);
337
476
  }
477
+ const type = this.context.aliases(called).result;
478
+ this.context.importAliases(this.file, node, called, [type]);
338
479
  return type;
339
480
  }
340
481
 
@@ -343,6 +484,13 @@ class Coroutine {
343
484
  const { source } = this.file;
344
485
  const edits: Edit[] = [];
345
486
  const visit = (child: ts.Node): void => {
487
+ // A step runs within one scan; only the awaits the statement lowering suspends at can wait.
488
+ if (ts.isAwaitExpression(child)) {
489
+ this.context.fail(
490
+ child,
491
+ "This suspension position is not supported; await into a named local or return.",
492
+ );
493
+ }
346
494
  const replacement = this.replacement(child);
347
495
  if (replacement === undefined) {
348
496
  ts.forEachChild(child, visit);
@@ -370,25 +518,21 @@ class Coroutine {
370
518
  : rewritten;
371
519
  }
372
520
 
373
- /** What a node becomes on the block: a field read, or a method's own member by name. */
521
+ /** What a node becomes on the block: a field read, or a method's own member. */
374
522
  private replacement(node: ts.Node): string | undefined {
523
+ const { own } = this.naming;
375
524
  if (
376
- this.method &&
525
+ own &&
377
526
  ts.isPropertyAccessExpression(node) &&
378
527
  node.expression.kind === ts.SyntaxKind.ThisKeyword
379
528
  ) {
380
- return `this[${JSON.stringify(node.name.text)}]`;
529
+ return own(node.name.text);
381
530
  }
382
- if (
383
- ts.isIdentifier(node) &&
384
- !(
385
- ts.isPropertyAccessExpression(node.parent) && node.parent.name === node
386
- ) &&
387
- !(ts.isPropertyAssignment(node.parent) && node.parent.name === node)
388
- ) {
389
- const field = this.fields.get(this.context.symbol(node)!);
531
+ if (ts.isIdentifier(node) && !isPropertyName(node)) {
532
+ const symbol = this.context.symbol(node);
533
+ const field = symbol && this.fields.get(symbol);
390
534
  if (field) {
391
- return `this.${field.name}`;
535
+ return this.self(field.name);
392
536
  }
393
537
  }
394
538
  if (ts.isShorthandPropertyAssignment(node)) {
@@ -396,7 +540,7 @@ class Coroutine {
396
540
  this.context.checker.getShorthandAssignmentValueSymbol(node);
397
541
  const field = value && this.fields.get(value);
398
542
  if (field) {
399
- return `${node.name.text}: this.${field.name}`;
543
+ return `${node.name.text}: ${this.self(field.name)}`;
400
544
  }
401
545
  }
402
546
  return undefined;
@@ -407,7 +551,7 @@ class Coroutine {
407
551
  body: Part,
408
552
  origin: ts.Node,
409
553
  kind: Step["kind"],
410
- yields = false,
554
+ { yields }: { yields: boolean },
411
555
  ): number {
412
556
  const id = this.states.size + 1;
413
557
  this.states.set(id, from(origin, body));
@@ -426,23 +570,19 @@ class Coroutine {
426
570
  }
427
571
 
428
572
  private finish(value: Part): Mapped {
429
- return mapped`this.value = ${copyValue(value, this.resultAggregate)}; this.busy = false; this.done = true; this.step = 0;`;
573
+ return mapped`${this.self("value")} = ${copyValue(value, this.resultAggregate)}; ${this.self("busy")} = false; ${this.self("done")} = true; ${this.self("step")} = 0;`;
430
574
  }
431
575
 
432
576
  private failure(error: Part): Mapped {
433
- return mapped`this.error = ${error}; if(this.error === 0)this.error=${jobError.malformedResponse}; this.busy = false; this.done = true; this.step = 0;`;
577
+ const code = this.self("error");
578
+ return mapped`${code} = ${error}; if(${code} === 0)${code}=${jobError.malformedResponse}; ${this.self("busy")} = false; ${this.self("done")} = true; ${this.self("step")} = 0;`;
434
579
  }
435
580
 
436
581
  /** An awaited call's result as the target stores it: records and arrays are copied. */
437
582
  private awaitedValue(value: string, call: ts.CallExpression): Part {
438
583
  const { checker } = this.context;
439
- return copyValue(
440
- value,
441
- Boolean(
442
- checker.getAwaitedType(checker.getTypeAtLocation(call))!.flags &
443
- ts.TypeFlags.Object,
444
- ),
445
- );
584
+ const awaited = checker.getAwaitedType(checker.getTypeAtLocation(call));
585
+ return copyValue(value, awaited !== undefined && isAggregateType(awaited));
446
586
  }
447
587
 
448
588
  /** The steps that start and poll an awaited operation, then store its result in `target`. */
@@ -459,64 +599,38 @@ class Coroutine {
459
599
  "Await requires a tsPLC operation or a statically named async function.",
460
600
  );
461
601
  }
462
- const name = ts.isPropertyAccessExpression(call.expression)
463
- ? call.expression.name
464
- : call.expression;
602
+ const name = calleeName(call.expression);
603
+ if (!name) {
604
+ this.context.fail(
605
+ call,
606
+ "Await requires a known async helper or SDK operation.",
607
+ );
608
+ }
465
609
  const awaiting = { awaited, call, target, next, reject };
466
610
  if (this.context.namesSdk(name, "sleep")) {
467
611
  return this.sleepState(awaiting);
468
612
  }
469
- if (
470
- this.context.namesSdk(name, "fetch") ||
471
- this.context.namesSdk(name, "opcuaCall")
472
- ) {
473
- return this.requestState(awaiting, {
474
- rpc: Boolean(this.context.namesSdk(name, "opcuaCall")),
475
- });
613
+ const rpc = this.context.namesSdk(name, "opcuaCall");
614
+ if (rpc || this.context.namesSdk(name, "fetch")) {
615
+ return this.requestState(awaiting, { rpc });
476
616
  }
477
- if (this.backgroundJob(name)) {
617
+ const symbol = this.context.symbol(name);
618
+ if (backgroundJob(this.context, symbol)) {
478
619
  return this.jobState(awaiting);
479
620
  }
480
- const called = this.context.functions.get(this.context.symbol(name)!);
481
- if (!called) {
621
+ if (!symbol || !this.context.functions.has(symbol)) {
482
622
  this.context.fail(
483
623
  call,
484
624
  "Await requires a known async helper or SDK operation.",
485
625
  );
486
626
  }
487
- const method = this.context.methods.get(this.context.symbol(name)!);
627
+ const method = this.context.methods.get(symbol);
488
628
  if (method) {
489
629
  return this.methodState(awaiting, method);
490
630
  }
491
631
  return this.helperState(awaiting);
492
632
  }
493
633
 
494
- /** Whether an awaited name is a `backgroundTasks.define` job. */
495
- private backgroundJob(name: ts.Node): boolean {
496
- const declaration = this.context
497
- .symbol(name)
498
- ?.declarations?.find(
499
- (node) =>
500
- ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node),
501
- );
502
- const initializer =
503
- declaration &&
504
- (ts.isVariableDeclaration(declaration) ||
505
- ts.isPropertyDeclaration(declaration))
506
- ? declaration.initializer
507
- : undefined;
508
- return Boolean(
509
- initializer &&
510
- ts.isCallExpression(initializer) &&
511
- ts.isPropertyAccessExpression(initializer.expression) &&
512
- this.context.namesSdk(
513
- initializer.expression.expression,
514
- "backgroundTasks",
515
- ) &&
516
- initializer.expression.name.text === "define",
517
- );
518
- }
519
-
520
634
  /** `await sleep(duration)`: an on-delay timer child. */
521
635
  private sleepState({ awaited, call, target, next }: Awaiting): number {
522
636
  const child = `child${this.children.length}`;
@@ -524,18 +638,23 @@ class Coroutine {
524
638
  if (!duration || rest.length || call.typeArguments?.length || target) {
525
639
  this.context.fail(call, "sleep takes one TIME and returns void.");
526
640
  }
527
- this.children.push(`private ${child} = new OnDelayTimer();`);
528
- this.resets.push(`this.${child}.update({enabled:false,duration:ms(0)});`);
641
+ this.children.push(
642
+ `private ${this.naming.member(child)} = new OnDelayTimer();`,
643
+ );
644
+ this.resets.push(
645
+ `${this.self(child)}.update({enabled:false,duration:ms(0)});`,
646
+ );
529
647
  const poll = this.state(
530
- mapped`this.${child}.update({enabled:true,duration:${this.rewrite(duration)}}); if(this.${child}.out.done) { this.step = ${next}; }`,
648
+ mapped`${this.self(child)}.update({enabled:true,duration:${this.rewrite(duration)}}); if(${this.self(child)}.out.done) { ${this.self("step")} = ${next}; }`,
531
649
  awaited,
532
650
  "await",
651
+ { yields: false },
533
652
  );
534
653
  return this.state(
535
- mapped`this.${child}.update({enabled:true,duration:${this.rewrite(duration)}});this.step=${poll};`,
654
+ mapped`${this.self(child)}.update({enabled:true,duration:${this.rewrite(duration)}});${this.self("step")}=${poll};`,
536
655
  awaited,
537
656
  "await",
538
- true,
657
+ { yields: true },
539
658
  );
540
659
  }
541
660
 
@@ -544,8 +663,8 @@ class Coroutine {
544
663
  { awaited, call, target, next, reject }: Awaiting,
545
664
  { rpc }: { rpc: boolean },
546
665
  ): number {
547
- const { checker, result } = this.context;
548
- const { source, extra } = this.file;
666
+ const { checker } = this.context;
667
+ const { source, extra, blocks } = this.file;
549
668
  const child = `child${this.children.length}`;
550
669
  const [address, second, ...rest] = call.arguments;
551
670
  const [response, request, ...more] = call.typeArguments ?? [];
@@ -587,8 +706,8 @@ interface ${httpName}Output {busy:BOOL;done:BOOL;error:UDINT;result:${responseTy
587
706
  class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { protected execute(input:${httpName}Input):${httpName}Output {return {busy:false,done:false,error:0,result:defaultValue<${responseType}>()};} }`,
588
707
  ),
589
708
  );
590
- result.blocks.set(
591
- `${source.fileName}:${httpName}`,
709
+ blocks.set(
710
+ loweringKey(source.fileName, httpName),
592
711
  rpc
593
712
  ? { kind: "rpc", path: url }
594
713
  : {
@@ -598,23 +717,26 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
598
717
  json: Boolean(json),
599
718
  },
600
719
  );
601
- this.children.push(`private ${child} = new ${httpName}();`);
720
+ this.children.push(
721
+ `private ${this.naming.member(child)} = new ${httpName}();`,
722
+ );
602
723
  this.resets.push(
603
- `this.${child}.update({start:false,cancel:false,request:defaultValue<${requestType}>()});`,
724
+ `${this.self(child)}.update({start:false,cancel:false,request:defaultValue<${requestType}>()});`,
604
725
  );
605
726
  this.cancels.push(
606
- `this.${child}.update({start:false,cancel:true,request:defaultValue<${requestType}>()});`,
727
+ `${this.self(child)}.update({start:false,cancel:true,request:defaultValue<${requestType}>()});`,
607
728
  );
608
729
  return this.state(
609
- mapped`this.${child}.update({start:true,cancel:false,request:${json ? this.rewrite(json) : `defaultValue<${requestType}>()`}}); if(this.${child}.out.done) { if(this.${child}.out.error !== 0) {${reject(`this.${child}.out.error`, true)}} else {${target ? mapped`${target} = ${this.awaitedValue(`this.${child}.out.result`, call)};` : ""}this.step = ${next};} }`,
730
+ mapped`${this.self(child)}.update({start:true,cancel:false,request:${json ? this.rewrite(json) : `defaultValue<${requestType}>()`}}); if(${this.self(child)}.out.done) { if(${this.self(child)}.out.error !== 0) {${reject(`${this.self(child)}.out.error`, { cancellable: true })}} else {${target ? mapped`${target} = ${this.awaitedValue(`${this.self(child)}.out.result`, call)};` : ""}${this.self("step")} = ${next};} }`,
610
731
  awaited,
611
732
  "await",
733
+ { yields: false },
612
734
  );
613
735
  }
614
736
 
615
737
  /** A fetch's inline `{ method, json }` options. */
616
738
  private fetchOptions(options: ts.Expression | undefined): {
617
- method: FetchMethod;
739
+ method: HttpMethod;
618
740
  json: ts.Expression | undefined;
619
741
  } {
620
742
  if (!options) {
@@ -626,7 +748,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
626
748
  "fetch options must be an inline { method, json } object.",
627
749
  );
628
750
  }
629
- const chosen: { method: FetchMethod; json: ts.Expression | undefined } = {
751
+ const chosen: { method: HttpMethod; json: ts.Expression | undefined } = {
630
752
  method: "GET",
631
753
  json: undefined,
632
754
  };
@@ -639,13 +761,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
639
761
  }
640
762
  if (property.name.text === "method") {
641
763
  const value = staticString(this.context.checker, property.initializer);
642
- if (
643
- value !== "GET" &&
644
- value !== "POST" &&
645
- value !== "PUT" &&
646
- value !== "PATCH" &&
647
- value !== "DELETE"
648
- ) {
764
+ if (!isHttpMethod(value)) {
649
765
  this.context.fail(property, "Unsupported fetch method.");
650
766
  }
651
767
  chosen.method = value;
@@ -666,22 +782,12 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
666
782
  if (request) {
667
783
  return this.text(request);
668
784
  }
669
- const { checker } = this.context;
670
- const layout = checker.getTypeAtLocation(json);
671
- if (
672
- !layout.aliasSymbol &&
673
- (!layout.symbol || layout.symbol.name === "__type")
674
- ) {
785
+ return (
786
+ namedRecordText(this.context.checker, json) ??
675
787
  this.context.fail(
676
788
  json,
677
789
  "Annotate json with a named PLC record or supply the Request type argument.",
678
- );
679
- }
680
- return checker.typeToString(
681
- layout,
682
- json,
683
- ts.TypeFormatFlags.NoTruncation |
684
- ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
790
+ )
685
791
  );
686
792
  }
687
793
 
@@ -689,24 +795,25 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
689
795
  private jobState({ awaited, call, target, next, reject }: Awaiting): number {
690
796
  const receiver = this.rewrite(call.expression);
691
797
  const borrow = `borrow${this.children.length}`;
692
- this.children.push(`private ${borrow}:BOOL=false;`);
693
- this.resets.push(`this.${borrow}=false;`);
798
+ this.children.push(`private ${this.naming.member(borrow)}:BOOL=false;`);
799
+ this.resets.push(`${this.self(borrow)}=false;`);
694
800
  this.cancels.push(
695
- `if(this.${borrow}){${receiver}.cancel();const borrowed=${receiver}.snapshot();if(!borrowed.valid||borrowed.busy)return;if(!${receiver}.reset())return;this.${borrow}=false;}`,
801
+ `if(${this.self(borrow)}){${receiver}.cancel();const borrowed=${receiver}.snapshot();if(!borrowed.valid||borrowed.busy)return;if(!${receiver}.reset())return;${this.self(borrow)}=false;}`,
696
802
  );
697
803
  const poll = this.state(
698
- mapped`const borrowed=${receiver}.snapshot();if(borrowed.valid&&borrowed.done){if(${receiver}.reset()){this.${borrow}=false;if(borrowed.error!==0){${reject("borrowed.error", true)}}else{${target ? mapped`${target}=${this.awaitedValue("borrowed.result", call)};` : ""}this.step=${next};}}}`,
804
+ mapped`const borrowed=${receiver}.snapshot();if(borrowed.valid&&borrowed.done){if(${receiver}.reset()){${this.self(borrow)}=false;if(borrowed.error!==0){${reject("borrowed.error", { cancellable: true })}}else{${target ? mapped`${target}=${this.awaitedValue("borrowed.result", call)};` : ""}${this.self("step")}=${next};}}}`,
699
805
  awaited,
700
806
  "await",
807
+ { yields: false },
701
808
  );
702
809
  return this.state(
703
- mapped`const available=${receiver}.snapshot();if(!available.valid)return;if(available.busy||available.done){${reject("7")}}else{const accepted:BOOL=${receiver}.start(${joined(
810
+ mapped`const available=${receiver}.snapshot();if(!available.valid)return;if(available.busy||available.done){${reject(jobError.noRequestSlot, { cancellable: false })}}else{const accepted:BOOL=${receiver}.start(${joined(
704
811
  call.arguments.map((argument) => this.rewrite(argument)),
705
812
  ",",
706
- )});if(accepted){this.${borrow}=true;this.step=${poll};}}`,
813
+ )});if(accepted){${this.self(borrow)}=true;${this.self("step")}=${poll};}}`,
707
814
  awaited,
708
815
  "await",
709
- true,
816
+ { yields: true },
710
817
  );
711
818
  }
712
819
 
@@ -720,26 +827,27 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
720
827
  }
721
828
  const receiver = this.rewrite(call.expression.expression);
722
829
  const borrow = `methodBorrow${this.children.length}`;
723
- this.children.push(`private ${borrow}:BOOL=false;`);
830
+ this.children.push(`private ${this.naming.member(borrow)}:BOOL=false;`);
724
831
  this.resets.push(
725
- `if(this.${borrow}){${receiver}.${method.reset}();this.${borrow}=false;}`,
832
+ `if(${this.self(borrow)}){${receiver}.${method.reset}();${this.self(borrow)}=false;}`,
726
833
  );
727
834
  this.cancels.push(
728
- `if(this.${borrow}){${receiver}.${method.advance}({cancel:true});const cancellingChild=${receiver}.${method.snapshot}();if(cancellingChild.busy)return;${receiver}.${method.reset}();this.${borrow}=false;}`,
835
+ `if(${this.self(borrow)}){${receiver}.${method.advance}({cancel:true});const cancellingChild=${receiver}.${method.snapshot}();if(cancellingChild.busy)return;${receiver}.${method.reset}();${this.self(borrow)}=false;}`,
729
836
  );
730
837
  const poll = this.state(
731
- mapped`${receiver}.${method.advance}({cancel:false});const childState=${receiver}.${method.snapshot}();if(childState.done){${receiver}.${method.reset}();this.${borrow}=false;if(childState.error!==0){${reject("childState.error", true)}}else{${target ? mapped`${target}=${this.awaitedValue("childState.result", call)};` : ""}this.step=${next};}}`,
838
+ mapped`${receiver}.${method.advance}({cancel:false});const childState=${receiver}.${method.snapshot}();if(childState.done){${receiver}.${method.reset}();${this.self(borrow)}=false;if(childState.error!==0){${reject("childState.error", { cancellable: true })}}else{${target ? mapped`${target}=${this.awaitedValue("childState.result", call)};` : ""}${this.self("step")}=${next};}}`,
732
839
  awaited,
733
840
  "await",
841
+ { yields: false },
734
842
  );
735
843
  return this.state(
736
844
  mapped`const accepted:BOOL=${receiver}.${method.start}(${joined(
737
845
  call.arguments.map((argument) => this.rewrite(argument)),
738
846
  ",",
739
- )});if(!accepted){${reject("7")}}else{this.${borrow}=true;${receiver}.${method.advance}({cancel:false});this.step=${poll};}`,
847
+ )});if(!accepted){${reject(jobError.noRequestSlot, { cancellable: false })}}else{${this.self(borrow)}=true;${receiver}.${method.advance}({cancel:false});${this.self("step")}=${poll};}`,
740
848
  awaited,
741
849
  "await",
742
- true,
850
+ { yields: true },
743
851
  );
744
852
  }
745
853
 
@@ -756,25 +864,26 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
756
864
  this.context.fail(call, "Async helpers require a static function.");
757
865
  }
758
866
  this.children.push(
759
- `private ${child} = new ${this.text(call.expression)}();`,
867
+ `private ${this.naming.member(child)} = new ${this.text(call.expression)}();`,
760
868
  );
761
- this.resets.push(`this.${child}.reset();`);
869
+ this.resets.push(`${this.self(child)}.reset();`);
762
870
  this.cancels.push(
763
- `this.${child}.update({cancel:true});const cancellingChild=this.${child}.snapshot();if(cancellingChild.busy)return;`,
871
+ `${this.self(child)}.update({cancel:true});const cancellingChild=${this.self(child)}.snapshot();if(cancellingChild.busy)return;`,
764
872
  );
765
873
  const poll = this.state(
766
- mapped`this.${child}.update({cancel:false}); const childState = this.${child}.snapshot(); if(childState.done) {if(childState.error !== 0) {${reject("childState.error", true)}} else {${target ? mapped`${target} = ${this.awaitedValue("childState.result", call)};` : ""}this.step = ${next};} }`,
874
+ mapped`${this.self(child)}.update({cancel:false}); const childState = ${this.self(child)}.snapshot(); if(childState.done) {if(childState.error !== 0) {${reject("childState.error", { cancellable: true })}} else {${target ? mapped`${target} = ${this.awaitedValue("childState.result", call)};` : ""}${this.self("step")} = ${next};} }`,
767
875
  awaited,
768
876
  "await",
877
+ { yields: false },
769
878
  );
770
879
  return this.state(
771
- mapped`const accepted:BOOL = this.${child}.start(${joined(
880
+ mapped`const accepted:BOOL = ${this.self(child)}.start(${joined(
772
881
  call.arguments.map((argument) => this.rewrite(argument)),
773
882
  ",",
774
- )}); if(accepted){this.${child}.update({cancel:false});this.step = ${poll};}`,
883
+ )}); if(accepted){${this.self(child)}.update({cancel:false});${this.self("step")} = ${poll};}`,
775
884
  awaited,
776
885
  "await",
777
- true,
886
+ { yields: true },
778
887
  );
779
888
  }
780
889
 
@@ -782,7 +891,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
782
891
  private block(
783
892
  statements: readonly ts.Statement[],
784
893
  next: number,
785
- reject: Reject = (error) => this.failure(error),
894
+ reject: Reject,
786
895
  ): number {
787
896
  return statements.reduceRight(
788
897
  (following, statement) => this.statement(statement, following, reject),
@@ -805,9 +914,10 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
805
914
  ? this.block([statement.elseStatement], next, reject)
806
915
  : next;
807
916
  return this.state(
808
- mapped`if(${this.rewrite(statement.expression)}) this.step = ${yes}; else this.step = ${no};`,
917
+ mapped`if(${this.rewrite(statement.expression)}) ${this.self("step")} = ${yes}; else ${this.self("step")} = ${no};`,
809
918
  statement.expression,
810
919
  "statement",
920
+ { yields: false },
811
921
  );
812
922
  }
813
923
  if (ts.isTryStatement(statement)) {
@@ -815,16 +925,17 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
815
925
  }
816
926
  if (
817
927
  ts.isIterationStatement(statement, false) &&
818
- containsAwait(statement, this.file.source)
928
+ !copiedWhole(statement, this.file.source)
819
929
  ) {
820
930
  return this.loop(statement, next, reject);
821
931
  }
822
932
  const loop = this.loops.at(-1);
823
933
  if (loop && ts.isBreakOrContinueStatement(statement) && !statement.label) {
824
934
  return this.state(
825
- `this.step = ${ts.isBreakStatement(statement) ? loop.breakStep : loop.continueStep};`,
935
+ `${this.self("step")} = ${ts.isBreakStatement(statement) ? loop.breakStep : loop.continueStep};`,
826
936
  statement,
827
937
  "statement",
938
+ { yields: false },
828
939
  );
829
940
  }
830
941
  if (ts.isThrowStatement(statement)) {
@@ -839,6 +950,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
839
950
  "Async throw requires a numeric error code.",
840
951
  );
841
952
  }
953
+ // Only a literal code is checked; a computed one is the program's to keep out of the range.
842
954
  if (
843
955
  ts.isNumericLiteral(statement.expression) &&
844
956
  Number(statement.expression.text) >= reservedErrors.first &&
@@ -850,9 +962,10 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
850
962
  );
851
963
  }
852
964
  return this.state(
853
- reject(this.rewrite(statement.expression)),
965
+ reject(this.rewrite(statement.expression), { cancellable: false }),
854
966
  statement,
855
967
  "throw",
968
+ { yields: false },
856
969
  );
857
970
  }
858
971
  if (ts.isReturnStatement(statement)) {
@@ -871,22 +984,21 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
871
984
  ) {
872
985
  return this.awaitState(statement.expression, undefined, next, reject);
873
986
  }
874
- if (containsAwait(statement, this.file.source)) {
875
- this.context.fail(
876
- statement,
877
- "This suspension position is not supported; await into a named local or return.",
878
- );
879
- }
880
987
  if (ts.isWhileStatement(statement) || ts.isDoStatement(statement)) {
881
988
  this.context.fail(
882
989
  statement,
883
990
  "Unbounded loops are not supported in async routines.",
884
991
  );
885
992
  }
993
+ // `count++;` and `total += n;` are assignments, the one form a step's statement takes.
994
+ const text = ts.isExpressionStatement(statement)
995
+ ? mapped`${this.updateText(statement.expression)};`
996
+ : this.rewrite(statement);
886
997
  return this.state(
887
- mapped`${this.rewrite(statement)} this.step = ${next};`,
998
+ mapped`${text} ${this.self("step")} = ${next};`,
888
999
  statement,
889
1000
  "statement",
1001
+ { yields: false },
890
1002
  );
891
1003
  }
892
1004
 
@@ -900,20 +1012,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
900
1012
  reject: Reject,
901
1013
  ): number {
902
1014
  const test = this.reserve(statement, "statement");
903
- const update =
904
- ts.isForStatement(statement) && statement.incrementor
905
- ? this.state(
906
- mapped`${this.updateText(statement.incrementor)}; this.step = ${test};`,
907
- statement.incrementor,
908
- "statement",
909
- )
910
- : ts.isForOfStatement(statement)
911
- ? this.state(
912
- `this.${this.positionFields.get(statement)} = this.${this.positionFields.get(statement)} + 1; this.step = ${test};`,
913
- statement,
914
- "statement",
915
- )
916
- : test;
1015
+ const update = this.loopUpdate(statement, test);
917
1016
  this.loops.push({ breakStep: next, continueStep: update });
918
1017
  const body = this.block([statement.statement], update, reject);
919
1018
  this.loops.pop();
@@ -929,23 +1028,30 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
929
1028
  test,
930
1029
  )
931
1030
  : this.state(
932
- mapped`${this.rewrite(statement.initializer)}; this.step = ${test};`,
1031
+ mapped`${this.rewrite(statement.initializer)}; ${this.self("step")} = ${test};`,
933
1032
  statement.initializer,
934
1033
  "statement",
1034
+ { yields: false },
935
1035
  );
936
1036
  return start;
937
1037
  }
938
- if (ts.isForOfStatement(statement)) {
1038
+ return test;
1039
+ }
1040
+
1041
+ /** The step that moves a loop on to its next iteration, then back to its test. */
1042
+ private loopUpdate(statement: ts.IterationStatement, test: number): number {
1043
+ if (ts.isForStatement(statement) && statement.incrementor) {
939
1044
  return this.state(
940
- `this.${this.positionFields.get(statement)} = 0; this.step = ${test};`,
941
- statement,
1045
+ mapped`${this.updateText(statement.incrementor)}; ${this.self("step")} = ${test};`,
1046
+ statement.incrementor,
942
1047
  "statement",
1048
+ { yields: false },
943
1049
  );
944
1050
  }
945
1051
  return test;
946
1052
  }
947
1053
 
948
- /** A loop's update as an assignment, the one form a step's statement takes: `i++` is `i = i + 1`. */
1054
+ /** An update as an assignment, the one form a step's statement takes: `i++` is `i = i + 1`. */
949
1055
  private updateText(incrementor: ts.Expression): Mapped {
950
1056
  if (
951
1057
  (ts.isPrefixUnaryExpression(incrementor) ||
@@ -972,64 +1078,49 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
972
1078
  body: number,
973
1079
  next: number,
974
1080
  ): Mapped {
975
- if (ts.isForOfStatement(statement)) {
976
- const position = `this.${this.positionFields.get(statement)}`;
977
- const array = this.rewrite(statement.expression);
978
- const declaration = ts.isVariableDeclarationList(statement.initializer)
979
- ? statement.initializer.declarations[0]
980
- : undefined;
981
- const field =
982
- declaration && this.fields.get(this.context.symbol(declaration.name)!);
983
- return mapped`if (${position} < ${array}.length) { this.${field?.name ?? ""} = ${copyValue(mapped`${array}[${position}]`, field?.aggregate ?? false)}; this.step = ${body}; } else { this.step = ${next}; }`;
984
- }
985
- const condition = ts.isForStatement(statement)
986
- ? statement.condition
987
- : ts.isWhileStatement(statement) || ts.isDoStatement(statement)
988
- ? statement.expression
989
- : undefined;
1081
+ const condition = loopCondition(statement);
990
1082
  if (!condition) {
991
- return mapped`this.step = ${body};`;
1083
+ return mapped`${this.self("step")} = ${body};`;
992
1084
  }
993
- return mapped`if (${this.rewrite(condition)}) this.step = ${body}; else this.step = ${next};`;
1085
+ return mapped`if (${this.rewrite(condition)}) ${this.self("step")} = ${body}; else ${this.self("step")} = ${next};`;
994
1086
  }
995
1087
 
996
1088
  /** A step whose body is written once what follows it is known, as a loop's test is. */
997
1089
  private reserve(origin: ts.Node, kind: Step["kind"]): number {
998
- return this.state("", origin, kind);
1090
+ return this.state("", origin, kind, { yields: false });
999
1091
  }
1000
1092
 
1001
1093
  private fill(step: number, origin: ts.Node, body: Part): void {
1002
- if (!this.states.has(step)) {
1003
- throw new Error(`Unknown step ${step}.`);
1004
- }
1005
1094
  this.states.set(step, from(origin, body));
1006
1095
  }
1007
1096
 
1097
+ /** The field `collect` gave a local or caught error. */
1098
+ private local(declaration: ts.VariableDeclaration): Field {
1099
+ const field = this.fields.get(this.declared(declaration.name));
1100
+ if (!field) {
1101
+ throw new Error("Every async local is collected onto the block.");
1102
+ }
1103
+ return field;
1104
+ }
1105
+
1008
1106
  /** A failure inside `try` moves to the catch steps with the error code; a cancel still fails. */
1009
1107
  private tryStatement(
1010
1108
  statement: ts.TryStatement,
1011
1109
  next: number,
1012
1110
  reject: Reject,
1013
1111
  ): number {
1014
- if (!statement.catchClause || statement.finallyBlock) {
1015
- this.context.fail(
1016
- statement,
1017
- "Async try requires catch; finally is not supported yet.",
1018
- );
1112
+ const clause = statement.catchClause;
1113
+ if (!clause) {
1114
+ throw new Error("Control-flow lowering gives every async try a catch.");
1019
1115
  }
1020
- const caught = this.block(
1021
- statement.catchClause.block.statements,
1022
- next,
1023
- reject,
1024
- );
1025
- const declaration = statement.catchClause.variableDeclaration;
1026
- const field =
1027
- declaration && this.fields.get(this.context.symbol(declaration.name)!);
1116
+ const caught = this.block(clause.block.statements, next, reject);
1117
+ const declaration = clause.variableDeclaration;
1118
+ const field = declaration && this.local(declaration);
1028
1119
  return this.block(
1029
1120
  statement.tryBlock.statements,
1030
1121
  next,
1031
- (error, cancellable) => {
1032
- const recover = mapped`${field ? mapped`this.${field.name} = ${error};` : ""}this.step = ${caught};`;
1122
+ (error, { cancellable }) => {
1123
+ const recover = mapped`${field ? mapped`${this.self(field.name)} = ${error};` : ""}${this.self("step")} = ${caught};`;
1033
1124
  return cancellable
1034
1125
  ? mapped`if(${error} === ${jobError.cancelled} || ${error} === ${jobError.codeChanged}) {${this.failure(error)}} else {${recover}}`
1035
1126
  : recover;
@@ -1046,7 +1137,9 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
1046
1137
  if (!this.returnsVoid) {
1047
1138
  this.context.fail(statement, "Async routines must return a value.");
1048
1139
  }
1049
- return this.state(this.finish("true"), statement, "return");
1140
+ return this.state(this.finish("true"), statement, "return", {
1141
+ yields: false,
1142
+ });
1050
1143
  }
1051
1144
  // Returning another routine's promise waits for it, as an await would.
1052
1145
  const adopted =
@@ -1064,15 +1157,17 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
1064
1157
  this.finish(this.rewrite(statement.expression)),
1065
1158
  statement,
1066
1159
  "return",
1160
+ { yields: false },
1067
1161
  );
1068
1162
  }
1069
1163
  return this.awaitState(
1070
1164
  suspension,
1071
- this.returnsVoid ? undefined : "this.value",
1165
+ this.returnsVoid ? undefined : this.self("value"),
1072
1166
  this.state(
1073
- this.finish(this.returnsVoid ? "true" : "this.value"),
1167
+ this.finish(this.returnsVoid ? "true" : this.self("value")),
1074
1168
  statement,
1075
1169
  "return",
1170
+ { yields: false },
1076
1171
  ),
1077
1172
  reject,
1078
1173
  );
@@ -1083,151 +1178,154 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
1083
1178
  next: number,
1084
1179
  reject: Reject,
1085
1180
  ): number {
1086
- const field = this.fields.get(this.context.symbol(declaration.name)!);
1087
- if (!field || !declaration.initializer) {
1088
- this.context.fail(declaration, "Invalid async local.");
1181
+ const field = this.local(declaration);
1182
+ const { initializer } = declaration;
1183
+ if (!initializer) {
1184
+ throw new Error("Every async local has an initializer.");
1089
1185
  }
1090
- const target = `this.${field.name}`;
1091
- return ts.isAwaitExpression(declaration.initializer)
1092
- ? this.awaitState(declaration.initializer, target, next, reject)
1186
+ const target = this.self(field.name);
1187
+ return ts.isAwaitExpression(initializer)
1188
+ ? this.awaitState(initializer, target, next, reject)
1093
1189
  : this.state(
1094
- mapped`${target} = ${copyValue(this.rewrite(declaration.initializer), field.aggregate)}; this.step = ${next};`,
1190
+ mapped`${target} = ${copyValue(this.rewrite(initializer), field.aggregate)}; ${this.self("step")} = ${next};`,
1095
1191
  declaration,
1096
1192
  "statement",
1193
+ { yields: false },
1097
1194
  );
1098
1195
  }
1099
1196
 
1100
- /** The block class: start, reset and snapshot members, and an execute that runs steps until one yields. */
1101
- private generate(entry: number): Mapped {
1102
- const { fn, returnType, parameters } = this;
1103
- const exported = hasModifier(fn, ts.SyntaxKind.ExportKeyword)
1104
- ? "export "
1105
- : "";
1106
- const prefix = aliasPrefix(this.context.names, fn);
1107
- const aliases = `export type ${prefix}Result = ${returnType};\n${parameters.map((p, i) => `export type ${prefix}Argument${i} = ${p.type};`).join("\n")}`;
1108
- const fields = `private step:UINT=0; private cancelling:BOOL=false; private busy:BOOL=false; private done:BOOL=false; private error:UDINT=0; private value:${returnType}=defaultValue<${returnType}>();
1109
- ${[...this.fields.values()].map((f) => `private ${f.name}:${f.type}=defaultValue<${f.type}>();`).join("\n")}
1110
- ${[...this.positionFields.values()].map((name) => `private ${name}:DINT=0;`).join("\n")}
1111
- ${this.children.join("\n")}`;
1112
- const table = joined(
1113
- [...this.states].map(
1114
- ([id, body]) => mapped`case ${id}: {${body}} break;`,
1115
- ),
1116
- "\n",
1117
- );
1118
- const code = codeDigest(
1197
+ /** The code digest: the block's fields, its parameters, its steps and how it resets and cancels. */
1198
+ digest(): number {
1199
+ return codeDigest(
1119
1200
  [
1120
- fields,
1121
- parameters.map((p) => `${p.field}:${p.type}`).join(","),
1122
- entry,
1123
- table.text,
1201
+ this.fieldText(),
1202
+ this.parameters.map((p) => `${p.field}:${p.type}`).join(","),
1203
+ this.entry,
1204
+ this.table().text,
1124
1205
  this.resets.join(" "),
1125
1206
  this.cancels.join(" "),
1126
1207
  [...this.yielding].join(","),
1127
1208
  ].join("\n"),
1128
1209
  );
1129
- const { codeChanged } = jobError;
1130
- return mapped`${aliases}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
1131
- ${fields}
1132
- private tsplcCode:UDINT=0; private tsplcPending:UDINT=0;
1133
- start(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.busy || this.done)return false; ${parameters.map((p) => `this.${p.field} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${this.resets.join(" ")} this.value = defaultValue<${returnType}>(); this.error=0;this.cancelling=false;this.tsplcPending=0;this.tsplcCode=${code};this.busy=true;this.done=false;this.step=${entry};return true;}
1134
- reset():void {${this.resets.join(" ")} this.busy=false;this.cancelling=false;this.tsplcPending=0;this.done=false;this.error=0;this.step=0;}
1135
- snapshot():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {if(this.done&&this.tsplcCode!==${code}){return {busy:false,done:true,error:${codeChanged},result:defaultValue<${returnType}>()};}return {busy:this.busy,done:this.done,error:this.error,result:${copyValue("this.value", this.resultAggregate)}};}
1136
- protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(this.tsplcCode!==${code}&&!this.cancelling){this.tsplcPending=${codeChanged};this.cancelling=true;}if(input.cancel)this.cancelling=true;if(this.cancelling){${this.cancels.map((cancel) => `{${cancel}}`).join(" ")}if(this.tsplcPending===0)this.tsplcPending=${jobError.cancelled};${this.failure("this.tsplcPending")}return;}for(let transition:DINT=0;transition<${this.states.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${table}
1137
- default: {this.tsplcPending=${codeChanged};this.cancelling=true;return;} }if(!this.busy||this.step===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}
1210
+ }
1211
+
1212
+ /** An async function's block: its exported type aliases, then a class of its members. */
1213
+ blockClass(code: number): Mapped {
1214
+ const { fn, parameters } = this;
1215
+ const returnType = this.returnType;
1216
+ const exported = hasModifier(fn, ts.SyntaxKind.ExportKeyword)
1217
+ ? "export "
1218
+ : "";
1219
+ const aliases = this.context.aliases(fn);
1220
+ const [start, reset, snapshot, execute] = this.methods(code);
1221
+ return mapped`export type ${aliases.result} = ${returnType};\n${parameters.map((p, i) => `export type ${aliases.argument(i)} = ${p.type};`).join("\n")}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
1222
+ ${this.fieldText()}
1223
+ ${this.codeFields().join(" ")}
1224
+ ${start}
1225
+ ${reset}
1226
+ ${snapshot}
1227
+ ${execute}
1138
1228
 
1139
1229
  }`;
1140
1230
  }
1141
1231
 
1142
- /** An async method's block members join its own class, renamed apart from the class's members. */
1143
- private methodMembers(generated: Mapped, method: MethodMembers): Mapped {
1144
- const { source } = this.file;
1145
- const parsed = ts.createSourceFile(
1146
- source.fileName,
1147
- generated.text,
1148
- ts.ScriptTarget.Latest,
1149
- true,
1150
- );
1151
- const worker = parsed.statements.find(ts.isClassDeclaration)!;
1152
- const names = new Map(
1153
- worker.members.map((member) => [
1154
- member.name!.getText(parsed),
1155
- `${this.context.names.name("tsplcAsync", this.fn)}_${member.name!.getText(parsed)}`,
1156
- ]),
1157
- );
1158
- names.set("start", method.start);
1159
- names.set("reset", method.reset);
1160
- names.set("snapshot", method.snapshot);
1161
- names.set("execute", method.advance);
1162
- // Only the members remain, one per line.
1163
- const members = worker.members;
1164
- const edits: Edit[] = [
1165
- ...members.map((member, index) => ({
1166
- start: index ? members[index - 1]!.end : 0,
1167
- end: member.getStart(parsed),
1168
- text: index ? "\n" : "",
1169
- })),
1170
- {
1171
- start: members.at(-1)!.end,
1172
- end: generated.text.length,
1173
- text: "",
1174
- },
1232
+ /** An async method's members, one per line, for its own class. */
1233
+ members(code: number): Part[] {
1234
+ return [
1235
+ ...Object.values(this.fieldGroups()).flat(),
1236
+ ...this.codeFields(),
1237
+ ...this.methods(code),
1175
1238
  ];
1176
- const visit = (node: ts.Node): void => {
1177
- if (
1178
- ts.isElementAccessExpression(node) &&
1179
- node.expression.kind === ts.SyntaxKind.ThisKeyword &&
1180
- ts.isStringLiteral(node.argumentExpression)
1181
- ) {
1182
- edits.push({
1183
- start: node.getStart(parsed),
1184
- end: node.end,
1185
- text: `this.${node.argumentExpression.text}`,
1186
- });
1187
- return;
1188
- }
1189
- const renamed =
1190
- (ts.isPropertyAccessExpression(node) &&
1191
- node.expression.kind === ts.SyntaxKind.ThisKeyword) ||
1192
- ts.isPropertyDeclaration(node) ||
1193
- ts.isMethodDeclaration(node)
1194
- ? node.name
1195
- : undefined;
1196
- const name =
1197
- renamed && ts.isIdentifier(renamed)
1198
- ? names.get(renamed.text)
1199
- : undefined;
1200
- if (renamed && name !== undefined) {
1201
- // Generated methods are called from the owner's other members.
1202
- const modifiers = ts.isMethodDeclaration(node)
1203
- ? node.modifiers
1204
- : undefined;
1205
- if (modifiers?.length) {
1206
- edits.push({
1207
- start: modifiers[0]!.getStart(parsed),
1208
- end: modifiers.at(-1)!.end,
1209
- text: "public",
1210
- });
1211
- }
1212
- edits.push({
1213
- start: renamed.getStart(parsed),
1214
- end: renamed.end,
1215
- text:
1216
- ts.isMethodDeclaration(node) && !modifiers?.length
1217
- ? `public ${name}`
1218
- : name,
1219
- });
1220
- if (ts.isPropertyAccessExpression(node)) {
1221
- return;
1222
- }
1223
- }
1224
- ts.forEachChild(node, visit);
1239
+ }
1240
+
1241
+ /** The state the steps keep, the routine's locals and its children. */
1242
+ private fieldGroups(): {
1243
+ state: string[];
1244
+ locals: string[];
1245
+ children: string[];
1246
+ } {
1247
+ const returnType = this.returnType;
1248
+ const field = (name: string, rest: string) =>
1249
+ `private ${this.naming.member(name)}${rest}`;
1250
+ return {
1251
+ state: [
1252
+ ...Object.entries(jobStateFields).map(([name, type]) =>
1253
+ field(name, `:${type}=${type === "BOOL" ? "false" : "0"};`),
1254
+ ),
1255
+ field("value", `:${returnType}=defaultValue<${returnType}>();`),
1256
+ ],
1257
+ locals: [...this.fields.values()].map((local) =>
1258
+ field(local.name, `:${local.type}=defaultValue<${local.type}>();`),
1259
+ ),
1260
+ children: this.children,
1225
1261
  };
1226
- visit(worker);
1227
- return edited(generated, edits);
1262
+ }
1263
+
1264
+ /**
1265
+ * The fields as a function's block declares them: the state on one line, then one per line.
1266
+ * The empty line before the children is where loops once kept their positions; it stays, as
1267
+ * the code digest is taken over this text.
1268
+ */
1269
+ private fieldText(): string {
1270
+ const { state, locals, children } = this.fieldGroups();
1271
+ return `${state.join(" ")}\n${locals.join("\n")}\n\n${children.join("\n")}`;
1272
+ }
1273
+
1274
+ /** The digest of the code a job started with, and the error a job stops with. */
1275
+ private codeFields(): string[] {
1276
+ return [
1277
+ `private ${this.naming.member("tsplcCode")}:UDINT=0;`,
1278
+ `private ${this.naming.member("tsplcPending")}:UDINT=0;`,
1279
+ ];
1280
+ }
1281
+
1282
+ /** Start, reset and snapshot, and the method that runs steps until one yields. */
1283
+ private methods(code: number): [string, string, string, Mapped] {
1284
+ const { parameters, naming } = this;
1285
+ const returnType = this.returnType;
1286
+ const busy = this.self("busy");
1287
+ const done = this.self("done");
1288
+ const error = this.self("error");
1289
+ const step = this.self("step");
1290
+ const cancelling = this.self("cancelling");
1291
+ const pending = this.self("tsplcPending");
1292
+ const started = this.self("tsplcCode");
1293
+ const resets = this.resets.join(" ");
1294
+ const { cancelled, codeChanged } = jobError;
1295
+ const table = this.table();
1296
+ return [
1297
+ `${naming.entry("start")}(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(${busy} || ${done})return false; ${parameters.map((p) => `${this.self(p.field)} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${resets} ${this.self("value")} = defaultValue<${returnType}>(); ${error}=0;${cancelling}=false;${pending}=0;${started}=${code};${busy}=true;${done}=false;${step}=${this.entry};return true;}`,
1298
+ `${naming.entry("reset")}():void {${resets} ${busy}=false;${cancelling}=false;${pending}=0;${done}=false;${error}=0;${step}=0;}`,
1299
+ `${naming.entry("snapshot")}():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {if(${done}&&${started}!==${code}){return {busy:false,done:true,error:${codeChanged},result:defaultValue<${returnType}>()};}return {busy:${busy},done:${done},error:${error},result:${copyValue(this.self("value"), this.resultAggregate)}};}`,
1300
+ mapped`${naming.entry("advance")}(input:{cancel:BOOL}):void {if(!${busy})return;if(${started}!==${code}&&!${cancelling}){${pending}=${codeChanged};${cancelling}=true;}if(input.cancel)${cancelling}=true;if(${cancelling}){${this.cancels.map((cancel) => `{${cancel}}`).join(" ")}if(${pending}===0)${pending}=${cancelled};${this.failure(pending)}return;}for(let transition:DINT=0;transition<${this.states.size + 1};transition++){const previous:UINT=${step};switch(${step}){${table}
1301
+ default: {${pending}=${codeChanged};${cancelling}=true;return;} }if(!${busy}||${step}===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}`,
1302
+ ];
1303
+ }
1304
+
1305
+ /** The steps, each a case of the block's state machine. */
1306
+ private table(): Mapped {
1307
+ return joined(
1308
+ [...this.states].map(
1309
+ ([id, body]) => mapped`case ${id}: {${body}} break;`,
1310
+ ),
1311
+ "\n",
1312
+ );
1228
1313
  }
1229
1314
  }
1230
1315
 
1316
+ /** The condition a loop tests before each iteration; undefined when it has none. */
1317
+ const loopCondition = (
1318
+ statement: ts.IterationStatement,
1319
+ ): ts.Expression | undefined => {
1320
+ if (ts.isForStatement(statement)) {
1321
+ return statement.condition;
1322
+ }
1323
+ if (ts.isWhileStatement(statement) || ts.isDoStatement(statement)) {
1324
+ return statement.expression;
1325
+ }
1326
+ return undefined;
1327
+ };
1328
+
1231
1329
  /** An awaited call and where its result goes. */
1232
1330
  interface Awaiting {
1233
1331
  awaited: ts.AwaitExpression | ts.CallExpression;