@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,4 +1,3 @@
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 { resolve } from "node:path";
3
2
  import {
4
3
  type Diagnostic,
@@ -9,7 +8,13 @@ import {
9
8
  import ts from "typescript";
10
9
  import { lowerCoroutine } from "./coroutines";
11
10
  import { GeneratedNames } from "./generated-names";
12
- import { runtimeSources } from "./module-graph";
11
+ import {
12
+ blockArrayElement,
13
+ importSpecifier,
14
+ type NamedRoutine,
15
+ namedRoutines,
16
+ plcSources,
17
+ } from "./module-graph";
13
18
  import {
14
19
  type Edit,
15
20
  edited,
@@ -25,20 +30,19 @@ import { lowerTaskDefinitions } from "./tasks";
25
30
  import { hasModifier, SemanticError } from "./types";
26
31
 
27
32
  export type Job = NonNullable<FunctionBlock["job"]>;
28
- /** A named async function or method. */
29
- export type Routine = (ts.FunctionDeclaration | ts.MethodDeclaration) & {
30
- readonly name: ts.PropertyName;
31
- };
33
+ type Runtime = NonNullable<FunctionBlock["runtime"]>;
34
+ type Schedule = NonNullable<PlcProgram["background"]>;
35
+ type Continuation = NonNullable<PlcProgram["continuation"]>;
32
36
 
33
37
  export interface AsyncLowering {
34
38
  sources: Map<string, Mapped>;
35
- blocks: Map<string, NonNullable<FunctionBlock["runtime"]>>;
36
- /** The async function each generated block runs, by `<file>:<block>`. */
39
+ blocks: Map<string, Runtime>;
40
+ /** The async function each generated block runs, by lowering key. */
37
41
  jobs: Map<string, Job>;
38
42
  programs: Record<string, { module: string; export: string }>;
39
- schedules: Map<string, NonNullable<PlcProgram["background"]>>;
43
+ schedules: Map<string, Schedule>;
40
44
  diagnostics: Diagnostic[];
41
- continuations: Map<string, NonNullable<PlcProgram["continuation"]>>;
45
+ continuations: Map<string, Continuation>;
42
46
  }
43
47
 
44
48
  /** The names of the members an async method's coroutine adds to its block. */
@@ -49,41 +53,59 @@ export interface MethodMembers {
49
53
  advance: string;
50
54
  }
51
55
 
56
+ /** The type aliases a routine's module exports for its result and arguments, so other modules can name them. */
57
+ interface RoutineAliases {
58
+ result: string;
59
+ argument: (index: number) => string;
60
+ }
61
+
52
62
  /** What every part of async lowering shares while it rewrites the program. */
53
63
  export interface AsyncContext {
54
64
  checker: ts.TypeChecker;
65
+ sdk: string;
55
66
  positions: Positions;
56
- result: AsyncLowering;
57
67
  /** Async routines by symbol. */
58
- functions: ReadonlyMap<ts.Symbol, Routine>;
68
+ functions: ReadonlyMap<ts.Symbol, NamedRoutine>;
59
69
  /** Async methods by symbol, with the members their coroutine adds. */
60
70
  methods: ReadonlyMap<ts.Symbol, MethodMembers>;
61
- /** Polls and background jobs that block instances run, by block symbol. */
62
- ownedContinuations: Map<ts.Symbol, string[]>;
63
- ownedJobs: Map<
64
- ts.Symbol,
65
- { method: string; schedule: NonNullable<PlcProgram["background"]> }[]
66
- >;
67
71
  symbol: (node: ts.Node) => ts.Symbol | undefined;
68
72
  /** Whether a node names the SDK declaration `name`. */
69
73
  namesSdk: (node: ts.Node, name: string) => boolean;
70
74
  fail: (node: ts.Node, message: string) => never;
71
75
  /** Names for generated declarations, from the source node each stands for. */
72
76
  names: GeneratedNames;
77
+ aliases: (fn: NamedRoutine) => RoutineAliases;
78
+ importAliases: typeof importAliases;
79
+ /** Whether code anywhere in the program reads the binding `declaration` declares. */
80
+ referenced: (declaration: ts.VariableDeclaration) => boolean;
81
+ }
82
+
83
+ /** A background job a block's instances serve: the block method that serves it, and its schedule. */
84
+ interface OwnedJob {
85
+ method: string;
86
+ schedule: Schedule;
73
87
  }
74
88
 
75
- /** One source file being rewritten: edits to its text and declarations added around it. */
89
+ /**
90
+ * One source file being rewritten: edits to its text, declarations added around it, and the
91
+ * records of what it generates, which count only once the whole source has been rewritten.
92
+ */
76
93
  export interface SourceRewrite {
77
94
  source: ts.SourceFile;
78
95
  replacements: Edit[];
79
96
  extra: Mapped[];
97
+ /** The routine aliases its imports name. */
98
+ importedAliases: Set<string>;
99
+ blocks: Map<string, Runtime>;
100
+ jobs: Map<string, Job>;
101
+ programs: AsyncLowering["programs"];
102
+ schedules: Map<string, Schedule>;
103
+ continuations: Map<string, Continuation>;
104
+ /** The polls and background jobs of the blocks it declares, which their instances run, by block symbol. */
105
+ ownedPolls: Map<ts.Symbol, string[]>;
106
+ ownedJobs: Map<ts.Symbol, OwnedJob[]>;
80
107
  }
81
108
 
82
- const isAsyncRoutine = (node: ts.Node): node is Routine =>
83
- (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) &&
84
- node.name !== undefined &&
85
- hasModifier(node, ts.SyntaxKind.AsyncKeyword);
86
-
87
109
  const asyncDiagnostic = (
88
110
  positions: Positions,
89
111
  node: ts.Node,
@@ -112,113 +134,252 @@ export const lowerAsync = (
112
134
  throw new SemanticError(asyncDiagnostic(positions, node, message));
113
135
  };
114
136
  const names = new GeneratedNames(root);
115
- const { functions, methods } = asyncRoutines(program, symbol, names);
137
+ const sources = plcSources(program);
138
+ const { functions, methods } = asyncRoutines(sources, checker, names);
116
139
  if (!functions.size) {
117
140
  return result;
118
141
  }
142
+ const recursion = recursiveRoutine(functions, symbol);
143
+ if (recursion) {
144
+ result.diagnostics.push(
145
+ asyncDiagnostic(
146
+ positions,
147
+ recursion.name,
148
+ `${recursion.name.getText()} calls itself, and a PLC routine can't: each call's state is allocated when the program compiles. Write the repetition as a loop.`,
149
+ ),
150
+ );
151
+ return result;
152
+ }
119
153
  const context: AsyncContext = {
120
154
  checker,
155
+ sdk,
121
156
  positions,
122
- result,
123
157
  functions,
124
158
  methods,
125
- ownedContinuations: new Map(),
126
- ownedJobs: new Map(),
127
159
  symbol,
128
160
  namesSdk: (node, name) => namesSdk(checker, sdk, node, name),
129
161
  fail,
130
162
  names,
163
+ aliases: (fn) => {
164
+ const prefix = names.name(
165
+ `TsplcAsync${fn.name.getText(fn.getSourceFile())}`,
166
+ fn,
167
+ );
168
+ return {
169
+ result: `${prefix}Result`,
170
+ argument: (index) => `${prefix}Argument${index}`,
171
+ };
172
+ },
173
+ importAliases,
174
+ referenced: (declaration) => {
175
+ const target = symbol(declaration.name);
176
+ const reads = (node: ts.Node): boolean =>
177
+ (ts.isIdentifier(node) &&
178
+ node !== declaration.name &&
179
+ target !== undefined &&
180
+ symbol(node) === target) ||
181
+ ts.forEachChild(node, reads) === true;
182
+ return sources.some(reads);
183
+ },
131
184
  };
132
- const sources = runtimeSources(program).filter(
133
- (source) => !source.isDeclarationFile,
134
- );
185
+ const ownedPolls = new Map<ts.Symbol, string[]>();
186
+ const ownedJobs = new Map<ts.Symbol, OwnedJob[]>();
135
187
  for (const source of sources) {
136
- rewriteSource(context, source);
188
+ const rewrite = rewriteSource(context, source);
189
+ if (rewrite instanceof SemanticError) {
190
+ result.diagnostics.push(rewrite.diagnostic);
191
+ continue;
192
+ }
193
+ if (!rewrite) {
194
+ continue;
195
+ }
196
+ result.sources.set(source.fileName, rewrittenText(rewrite));
197
+ for (const [key, value] of rewrite.blocks) {
198
+ result.blocks.set(key, value);
199
+ }
200
+ for (const [key, value] of rewrite.jobs) {
201
+ result.jobs.set(key, value);
202
+ }
203
+ Object.assign(result.programs, rewrite.programs);
204
+ for (const [key, value] of rewrite.schedules) {
205
+ result.schedules.set(key, value);
206
+ }
207
+ for (const [key, value] of rewrite.continuations) {
208
+ result.continuations.set(key, value);
209
+ }
210
+ for (const [block, polls] of rewrite.ownedPolls) {
211
+ ownedPolls.set(block, polls);
212
+ }
213
+ for (const [block, jobs] of rewrite.ownedJobs) {
214
+ ownedJobs.set(block, jobs);
215
+ }
137
216
  }
138
217
  for (const source of sources) {
139
- addInstanceEntries(context, source);
218
+ addInstanceEntries(context, { ownedPolls, ownedJobs }, source, result);
140
219
  }
141
220
  return result;
142
221
  };
143
222
 
223
+ /** Imports those of `names`, aliases `fn`'s module exports, that the source does not import yet. */
224
+ function importAliases(
225
+ file: Pick<SourceRewrite, "source" | "extra" | "importedAliases">,
226
+ node: ts.Node,
227
+ fn: NamedRoutine,
228
+ names: readonly string[],
229
+ ): void {
230
+ const missing = names.filter((name) => !file.importedAliases.has(name));
231
+ if (!missing.length) {
232
+ return;
233
+ }
234
+ for (const name of missing) {
235
+ file.importedAliases.add(name);
236
+ }
237
+ file.extra.push(
238
+ from(
239
+ node,
240
+ `import type {${missing.join(",")}} from ${importSpecifier(file.source.fileName, fn.getSourceFile().fileName)};`,
241
+ ),
242
+ );
243
+ }
244
+
245
+ /**
246
+ * An async function that calls itself, directly or through other async functions. Each becomes a
247
+ * block holding an instance of every function it calls, so a cycle would be a block inside itself.
248
+ * An async method keeps its state in its own instance, so its calls allocate nothing.
249
+ */
250
+ function recursiveRoutine(
251
+ functions: ReadonlyMap<ts.Symbol, NamedRoutine>,
252
+ symbol: (node: ts.Node) => ts.Symbol | undefined,
253
+ ): NamedRoutine | undefined {
254
+ const callees = (fn: NamedRoutine): ts.Symbol[] => {
255
+ const found: ts.Symbol[] = [];
256
+ const visit = (node: ts.Node): void => {
257
+ if (ts.isCallExpression(node)) {
258
+ const callee = ts.isPropertyAccessExpression(node.expression)
259
+ ? node.expression.name
260
+ : node.expression;
261
+ const target = symbol(callee);
262
+ const routine = target && functions.get(target);
263
+ if (target && routine && ts.isFunctionDeclaration(routine)) {
264
+ found.push(target);
265
+ }
266
+ }
267
+ ts.forEachChild(node, visit);
268
+ };
269
+ if (fn.body) {
270
+ visit(fn.body);
271
+ }
272
+ return found;
273
+ };
274
+ const finished = new Set<ts.Symbol>();
275
+ const active = new Set<ts.Symbol>();
276
+ const cycle = (key: ts.Symbol): NamedRoutine | undefined => {
277
+ const fn = functions.get(key);
278
+ if (active.has(key)) {
279
+ return fn;
280
+ }
281
+ if (finished.has(key) || !fn) {
282
+ return undefined;
283
+ }
284
+ active.add(key);
285
+ for (const callee of callees(fn)) {
286
+ const found = cycle(callee);
287
+ if (found) {
288
+ return found;
289
+ }
290
+ }
291
+ active.delete(key);
292
+ finished.add(key);
293
+ return undefined;
294
+ };
295
+ for (const key of functions.keys()) {
296
+ const found = cycle(key);
297
+ if (found) {
298
+ return found;
299
+ }
300
+ }
301
+ return undefined;
302
+ }
303
+
144
304
  /** Async functions and methods by symbol; methods also get the names of their coroutine members. */
145
305
  function asyncRoutines(
146
- program: ts.Program,
147
- symbol: (node: ts.Node) => ts.Symbol | undefined,
306
+ sources: readonly ts.SourceFile[],
307
+ checker: ts.TypeChecker,
148
308
  names: GeneratedNames,
149
309
  ) {
150
- const functions = new Map<ts.Symbol, Routine>();
310
+ const functions = new Map<ts.Symbol, NamedRoutine>();
151
311
  const methods = new Map<ts.Symbol, MethodMembers>();
152
- for (const source of runtimeSources(program)) {
153
- if (source.isDeclarationFile) {
312
+ for (const [key, fn] of namedRoutines(sources, checker)) {
313
+ if (!hasModifier(fn, ts.SyntaxKind.AsyncKeyword)) {
154
314
  continue;
155
315
  }
156
- for (const statement of source.statements) {
157
- const routines = ts.isClassDeclaration(statement)
158
- ? statement.members.filter(ts.isMethodDeclaration)
159
- : [statement];
160
- for (const fn of routines) {
161
- if (!isAsyncRoutine(fn)) {
162
- continue;
163
- }
164
- functions.set(symbol(fn.name)!, fn);
165
- if (ts.isMethodDeclaration(fn)) {
166
- const prefix = names.name(`tsplcAsync${fn.name.getText(source)}`, fn);
167
- methods.set(symbol(fn.name)!, {
168
- start: `${prefix}Start`,
169
- reset: `${prefix}Reset`,
170
- snapshot: `${prefix}Snapshot`,
171
- advance: `${prefix}Advance`,
172
- });
173
- }
174
- }
316
+ functions.set(key, fn);
317
+ if (ts.isMethodDeclaration(fn)) {
318
+ const prefix = names.name(`tsplcAsync${fn.name.getText()}`, fn);
319
+ methods.set(key, {
320
+ start: `${prefix}Start`,
321
+ reset: `${prefix}Reset`,
322
+ snapshot: `${prefix}Snapshot`,
323
+ advance: `${prefix}Advance`,
324
+ });
175
325
  }
176
326
  }
177
327
  return { functions, methods };
178
328
  }
179
329
 
180
330
  /**
181
- * Replaces a source's async routines and task definitions with generated blocks. A source
182
- * that fails is left as written and reports why.
331
+ * Replaces a source's async routines and task definitions with generated blocks: undefined when
332
+ * it has none, and the reason when it fails, in which case it is left as written.
183
333
  */
184
- function rewriteSource(context: AsyncContext, source: ts.SourceFile): void {
334
+ function rewriteSource(
335
+ context: AsyncContext,
336
+ source: ts.SourceFile,
337
+ ): SourceRewrite | SemanticError | undefined {
338
+ const rewrite: SourceRewrite = {
339
+ source,
340
+ replacements: [],
341
+ extra: [],
342
+ importedAliases: new Set(),
343
+ blocks: new Map(),
344
+ jobs: new Map(),
345
+ programs: {},
346
+ schedules: new Map(),
347
+ continuations: new Map(),
348
+ ownedPolls: new Map(),
349
+ ownedJobs: new Map(),
350
+ };
185
351
  try {
186
- const replacements: Edit[] = [];
187
- const extra: Mapped[] = [];
188
- const file = { source, replacements, extra };
189
352
  for (const fn of context.functions.values()) {
190
353
  if (fn.getSourceFile() === source) {
191
- lowerCoroutine(context, file, fn);
354
+ lowerCoroutine(context, rewrite, fn);
192
355
  }
193
356
  }
194
- lowerTaskDefinitions(context, file);
195
- if (!replacements.length) {
196
- return;
197
- }
198
- // Generated classes go first, other declarations last.
199
- const added = joined(extra, "\n");
200
- const generated = ts.createSourceFile(
201
- source.fileName,
202
- added.text,
203
- ts.ScriptTarget.Latest,
204
- true,
205
- );
206
- const part = (node: ts.Node) =>
207
- slice(added, node.getStart(generated), node.end);
208
- const before = generated.statements.filter(ts.isClassDeclaration).map(part);
209
- const after = generated.statements
210
- .filter((statement) => !ts.isClassDeclaration(statement))
211
- .map(part);
212
- context.result.sources.set(
213
- source.fileName,
214
- mapped`${joined(before, "\n")}\n${edited(source, replacements)}\n${joined(after, "\n")}`,
215
- );
357
+ lowerTaskDefinitions(context, rewrite);
216
358
  } catch (cause) {
217
359
  if (!(cause instanceof SemanticError)) {
218
360
  throw cause;
219
361
  }
220
- context.result.diagnostics.push(cause.diagnostic);
362
+ return cause;
221
363
  }
364
+ return rewrite.replacements.length ? rewrite : undefined;
365
+ }
366
+
367
+ /** A rewritten source's text: generated classes first, the source with its edits, then the other declarations. */
368
+ function rewrittenText({ source, replacements, extra }: SourceRewrite): Mapped {
369
+ const added = joined(extra, "\n");
370
+ const generated = ts.createSourceFile(
371
+ source.fileName,
372
+ added.text,
373
+ ts.ScriptTarget.Latest,
374
+ true,
375
+ );
376
+ const part = (node: ts.Node) =>
377
+ slice(added, node.getStart(generated), node.end);
378
+ const before = generated.statements.filter(ts.isClassDeclaration).map(part);
379
+ const after = generated.statements
380
+ .filter((statement) => !ts.isClassDeclaration(statement))
381
+ .map(part);
382
+ return mapped`${joined(before, "\n")}\n${edited(source, replacements)}\n${joined(after, "\n")}`;
222
383
  }
223
384
 
224
385
  /**
@@ -227,17 +388,23 @@ function rewriteSource(context: AsyncContext, source: ts.SourceFile): void {
227
388
  */
228
389
  function addInstanceEntries(
229
390
  context: AsyncContext,
391
+ owned: Pick<SourceRewrite, "ownedPolls" | "ownedJobs">,
230
392
  source: ts.SourceFile,
393
+ result: AsyncLowering,
231
394
  ): void {
232
- const { positions, result } = context;
395
+ const { positions } = context;
233
396
  const entries: Mapped[] = [];
397
+ const program = (entry: string) => {
398
+ result.programs[entry] = {
399
+ module: resolve(source.fileName),
400
+ export: entry,
401
+ };
402
+ };
234
403
  const visit = (node: ts.Node): void => {
235
- const instance = allocatedInstances(context.checker, source, node);
236
- const jobs =
237
- instance && context.ownedJobs.get(context.symbol(instance.block)!);
238
- const polls =
239
- instance &&
240
- context.ownedContinuations.get(context.symbol(instance.block)!);
404
+ const instance = allocatedInstance(context, node);
405
+ const block = instance && context.symbol(instance.block);
406
+ const jobs = block && owned.ownedJobs.get(block);
407
+ const polls = block && owned.ownedPolls.get(block);
241
408
  if (!instance || (!jobs && !polls)) {
242
409
  ts.forEachChild(node, visit);
243
410
  return;
@@ -249,13 +416,15 @@ function addInstanceEntries(
249
416
  !ts.isVariableDeclarationList(declaration.parent) ||
250
417
  !ts.isVariableStatement(declaration.parent.parent) ||
251
418
  !ts.isSourceFile(declaration.parent.parent.parent) ||
252
- (jobs && instance.first !== undefined)
419
+ (jobs && instance.elements)
253
420
  ) {
254
421
  result.diagnostics.push(
255
422
  asyncDiagnostic(
256
423
  positions,
257
424
  node,
258
- "Function blocks with background jobs require module-level named instances.",
425
+ jobs
426
+ ? "Function blocks with background jobs require module-level named instances."
427
+ : "Function blocks with continuations require module-level named instances.",
259
428
  ),
260
429
  );
261
430
  return;
@@ -263,19 +432,28 @@ function addInstanceEntries(
263
432
  const name = declaration.name.text;
264
433
  // One entry polls all of an instance's sites, in their order: they share its task.
265
434
  if (polls?.length) {
435
+ const range =
436
+ instance.elements && elementRange(context, instance.elements);
437
+ if (range === null) {
438
+ result.diagnostics.push(
439
+ asyncDiagnostic(
440
+ positions,
441
+ node,
442
+ "A block array whose blocks have continuations needs a literal length and lower bound.",
443
+ ),
444
+ );
445
+ return;
446
+ }
266
447
  const entry = context.names.name("tsplcContinuation", declaration);
267
448
  const calls = polls.map((poll) =>
268
- instance.first === undefined
449
+ range === undefined
269
450
  ? `${name}.${poll}();`
270
- : `for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}`,
451
+ : `for(let element:DINT=${range.first};element<=${range.last};element++){${name}[element].${poll}();}`,
271
452
  );
272
453
  entries.push(
273
454
  from(node, `export function ${entry}():void{${calls.join("")}}`),
274
455
  );
275
- result.programs[entry] = {
276
- module: resolve(source.fileName),
277
- export: entry,
278
- };
456
+ program(entry);
279
457
  result.continuations.set(entry, {
280
458
  instance: name,
281
459
  file: positions.node(declaration).file,
@@ -289,10 +467,7 @@ function addInstanceEntries(
289
467
  entries.push(
290
468
  from(node, `export function ${entry}():void{${name}.${job.method}();}`),
291
469
  );
292
- result.programs[entry] = {
293
- module: resolve(source.fileName),
294
- export: entry,
295
- };
470
+ program(entry);
296
471
  result.schedules.set(entry, { ...job.schedule, worker: name });
297
472
  }
298
473
  ts.forEachChild(node, visit);
@@ -308,35 +483,48 @@ function addInstanceEntries(
308
483
 
309
484
  /**
310
485
  * The block instances an expression allocates: `new Block()` one instance, and
311
- * `defaultValue<FixedArray<Block, N, Lower>>()` one per element.
486
+ * `defaultValue<FixedArray<Block, N, Lower>>()` one per element, whose length and lower bound
487
+ * are type arguments.
312
488
  */
313
- function allocatedInstances(
314
- checker: ts.TypeChecker,
315
- source: ts.SourceFile,
489
+ function allocatedInstance(
490
+ context: AsyncContext,
316
491
  node: ts.Node,
317
- ): { block: ts.Node; first?: number; last?: number } | undefined {
492
+ ):
493
+ | { block: ts.Node; elements?: { length: ts.TypeNode; lower?: ts.TypeNode } }
494
+ | undefined {
318
495
  if (ts.isNewExpression(node)) {
319
496
  return { block: node.expression };
320
497
  }
321
- const type = ts.isCallExpression(node) ? node.typeArguments?.[0] : undefined;
322
- const [element, length, lower] =
323
- type &&
324
- ts.isTypeReferenceNode(type) &&
325
- type.typeName.getText(source) === "FixedArray"
326
- ? (type.typeArguments ?? [])
327
- : [];
328
- if (!element || !ts.isTypeReferenceNode(element) || !length) {
498
+ if (
499
+ !ts.isCallExpression(node) ||
500
+ !context.namesSdk(node.expression, "defaultValue")
501
+ ) {
329
502
  return undefined;
330
503
  }
504
+ const [type] = node.typeArguments ?? [];
505
+ const element = type && blockArrayElement(type, context.checker, context.sdk);
506
+ const [, length, lower] =
507
+ type && ts.isTypeReferenceNode(type) ? (type.typeArguments ?? []) : [];
508
+ if (!element || !length) {
509
+ return undefined;
510
+ }
511
+ return { block: element.typeName, elements: { length, lower } };
512
+ }
513
+
514
+ /** A block array's first and last index; null when its length or lower bound is not a literal. */
515
+ function elementRange(
516
+ { checker }: AsyncContext,
517
+ { length, lower }: { length: ts.TypeNode; lower?: ts.TypeNode },
518
+ ): { first: number; last: number } | null {
331
519
  // A literal, or a table's `(typeof table)["length"]`.
332
- const integer = (node: ts.TypeNode) => {
333
- const literal = checker.getTypeFromTypeNode(node);
334
- return literal.isNumberLiteral() ? literal.value : NaN;
335
- };
336
- const first = lower ? integer(lower) : 0;
337
- return {
338
- block: element.typeName,
339
- first,
340
- last: first + integer(length) - 1,
520
+ const literal = (node: ts.TypeNode) => {
521
+ const type = checker.getTypeFromTypeNode(node);
522
+ return type.isNumberLiteral() ? type.value : undefined;
341
523
  };
524
+ const first = lower ? literal(lower) : 0;
525
+ const count = literal(length);
526
+ if (first === undefined || count === undefined) {
527
+ return null;
528
+ }
529
+ return { first, last: first + count - 1 };
342
530
  }