@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,8 +1,14 @@
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 { type Diagnostic, error } from "@tsplc/compiler/ir";
3
2
  import ts from "typescript";
3
+ import {
4
+ asyncWrapAdd,
5
+ cooperativeTasksAlias,
6
+ diagnosticsInstance,
7
+ errorCodeAlias,
8
+ } from "./cooperative";
4
9
  import { GeneratedNames } from "./generated-names";
5
- import { importSpecifier, runtimeSources } from "./module-graph";
10
+ import { loweringKey } from "./lowering-key";
11
+ import { importSpecifier, namedRoutines, plcSources } from "./module-graph";
6
12
  import {
7
13
  type Edit,
8
14
  edited,
@@ -12,11 +18,12 @@ import {
12
18
  mapped,
13
19
  type Positions,
14
20
  } from "./positions";
15
- import { chainOf, lowerChain } from "./promise-chains";
16
- import { namesSdk, symbolAt } from "./sdk";
21
+ import { type Chain, chainOf, lowerChain } from "./promise-chains";
22
+ import { namesSdk, sdkModules, symbolAt } from "./sdk";
17
23
  import { hasModifier, SemanticError } from "./types";
18
24
 
19
- export type Routine = ts.FunctionDeclaration | ts.MethodDeclaration;
25
+ /** A function or method a chain can call or be written in. */
26
+ export type Callable = ts.FunctionDeclaration | ts.MethodDeclaration;
20
27
 
21
28
  interface PromiseLowering {
22
29
  sources: Map<string, Mapped>;
@@ -24,13 +31,22 @@ interface PromiseLowering {
24
31
  runtimeBlocks: Map<string, { kind: "mailbox" }>;
25
32
  }
26
33
 
34
+ /** A detached chain's site, and the routine its chain starts with. */
35
+ export interface ChainSite {
36
+ name: string;
37
+ root: ts.Symbol | undefined;
38
+ }
39
+
27
40
  /** What lowering one chain needs from the rewrite of the whole program. */
28
41
  export interface PromiseContext {
29
42
  readonly checker: ts.TypeChecker;
30
43
  /** Every function and method by symbol; named callbacks and operations resolve here. */
31
- readonly routines: ReadonlyMap<ts.Symbol, Routine>;
32
- /** The sites of detached chains, by the module or class whose cancelAsync cancels them. */
33
- readonly sites: Map<ts.SourceFile | ts.ClassDeclaration, string[]>;
44
+ readonly routines: ReadonlyMap<ts.Symbol, Callable>;
45
+ /**
46
+ * The sites of detached chains, by the module or class whose cancelAsync cancels them, each with
47
+ * the routine its chain starts with.
48
+ */
49
+ readonly sites: Map<ts.SourceFile | ts.ClassDeclaration, ChainSite[]>;
34
50
  symbol(node: ts.Node): ts.Symbol | undefined;
35
51
  /** Whether a node names the SDK declaration `name`. */
36
52
  namesSdk(node: ts.Node, name: string): boolean;
@@ -51,9 +67,6 @@ export interface PromiseContext {
51
67
  useDiagnostics(node: ts.Node): void;
52
68
  }
53
69
 
54
- /** The name of the shared diagnostics instance that detached chains report failures to. */
55
- const diagnosticsInstance = "tsplcPromiseDiagnostics";
56
-
57
70
  /** Normalize promise syntax into named coroutines; scheduling stays in async lowering. */
58
71
  export const lowerPromises = (
59
72
  program: ts.Program,
@@ -61,9 +74,7 @@ export const lowerPromises = (
61
74
  positions: Positions,
62
75
  root: string,
63
76
  ): PromiseLowering => {
64
- const files = runtimeSources(program).filter(
65
- (source) => !source.isDeclarationFile,
66
- );
77
+ const files = plcSources(program);
67
78
  const rewrite = new PromiseRewrite(
68
79
  program.getTypeChecker(),
69
80
  sdk,
@@ -88,10 +99,10 @@ export const lowerPromises = (
88
99
  rewrite.append(
89
100
  source,
90
101
  owner,
91
- `export class TsplcPromiseDiagnostics extends FunctionBlock<{}>{private count:UDINT=0;private lastError:UDINT=0;public report(code:UDINT,count:UDINT):BOOL{this.count=tsplcAsyncWrapAdd<UDINT>(this.count,count);this.lastError=code;return true;}public snapshot():{valid:BOOL;count:UDINT;lastError:UDINT}{return {valid:true,count:this.count,lastError:this.lastError};}protected execute(input:{}):void{}}
102
+ `export class TsplcPromiseDiagnostics extends FunctionBlock<{}>{private count:UDINT=0;private lastError:UDINT=0;public report(code:UDINT,count:UDINT):BOOL{this.count=${asyncWrapAdd}<UDINT>(this.count,count);this.lastError=code;return true;}public snapshot():{valid:BOOL;count:UDINT;lastError:UDINT}{return {valid:true,count:this.count,lastError:this.lastError};}protected execute(input:{}):void{}}
92
103
  export const ${diagnosticsInstance}=new TsplcPromiseDiagnostics();`,
93
104
  );
94
- runtimeBlocks.set(`${source.fileName}:TsplcPromiseDiagnostics`, {
105
+ runtimeBlocks.set(loweringKey(source.fileName, "TsplcPromiseDiagnostics"), {
95
106
  kind: "mailbox",
96
107
  });
97
108
  for (const file of new Set([
@@ -124,15 +135,19 @@ function rewriteChains(
124
135
  diagnostics: Diagnostic[],
125
136
  ) {
126
137
  const diagnosticsCalls: ts.CallExpression[] = [];
127
- const cancelCalls: { node: ts.CallExpression; owner: Routine }[] = [];
138
+ const cancelCalls: { node: ts.CallExpression; owner: Callable }[] = [];
128
139
  const lower = (
129
140
  node: ts.Node,
130
141
  expression: ts.Expression,
131
- owner: Routine,
142
+ chain: Chain,
143
+ owner: Callable,
132
144
  { detached }: { detached: boolean },
133
145
  ) => {
134
146
  try {
135
- rewrite.edit(node, lowerChain(rewrite, expression, owner, detached));
147
+ rewrite.edit(
148
+ node,
149
+ lowerChain(rewrite, expression, chain, owner, { detached }),
150
+ );
136
151
  } catch (cause) {
137
152
  if (!(cause instanceof SemanticError)) {
138
153
  throw cause;
@@ -141,7 +156,7 @@ function rewriteChains(
141
156
  }
142
157
  };
143
158
  for (const source of files) {
144
- const visit = (node: ts.Node, owner?: Routine): void => {
159
+ const visit = (node: ts.Node, owner?: Callable): void => {
145
160
  if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
146
161
  if (node.body) {
147
162
  ts.forEachChild(node.body, (child) => visit(child, node));
@@ -171,7 +186,8 @@ function rewriteChains(
171
186
  const expression = ts.isVoidExpression(node.expression)
172
187
  ? node.expression.expression
173
188
  : node.expression;
174
- if (chainOf(rewrite, expression)) {
189
+ const chain = chainOf(rewrite, expression);
190
+ if (chain) {
175
191
  if (hasModifier(owner, ts.SyntaxKind.AsyncKeyword)) {
176
192
  diagnostics.push(
177
193
  rewrite.diagnostic(
@@ -181,13 +197,16 @@ function rewriteChains(
181
197
  );
182
198
  return;
183
199
  }
184
- lower(node, expression, owner, { detached: true });
200
+ lower(node, expression, chain, owner, { detached: true });
185
201
  return;
186
202
  }
187
203
  }
188
- if (ts.isCallExpression(node) && chainOf(rewrite, node)?.links.length) {
189
- lower(node, node, owner, { detached: false });
190
- return;
204
+ if (ts.isCallExpression(node)) {
205
+ const chain = chainOf(rewrite, node);
206
+ if (chain?.links.length) {
207
+ lower(node, node, chain, owner, { detached: false });
208
+ return;
209
+ }
191
210
  }
192
211
  ts.forEachChild(node, (child) => visit(child, owner));
193
212
  };
@@ -196,21 +215,36 @@ function rewriteChains(
196
215
  return { diagnosticsCalls, cancelCalls };
197
216
  }
198
217
 
199
- /** `cancelAsync()` cancels every detached chain of the module, or `cancelAsync(this)` of the block. */
218
+ /**
219
+ * `cancelAsync()` cancels every detached chain of the module, `cancelAsync(this)` of the block, and
220
+ * `cancelAsync(run, ...)` in a module each of the module's chains that starts with one of those
221
+ * routines, which is how a plain program cancels one object's calls.
222
+ */
200
223
  function cancelScope(
201
224
  rewrite: PromiseRewrite,
202
225
  node: ts.CallExpression,
203
- owner: Routine,
226
+ owner: Callable,
204
227
  diagnostics: Diagnostic[],
205
228
  ): void {
206
229
  const scope =
207
230
  ts.isMethodDeclaration(owner) && ts.isClassDeclaration(owner.parent)
208
231
  ? owner.parent
209
232
  : owner.getSourceFile();
233
+ const member = ts.isClassDeclaration(scope);
234
+ const [argument, ...rest] = node.arguments;
235
+ const roots = member
236
+ ? undefined
237
+ : node.arguments.map((routine) =>
238
+ ts.isIdentifier(routine) ? rewrite.symbol(routine) : undefined,
239
+ );
240
+ const byRoutine =
241
+ roots !== undefined &&
242
+ roots.length > 0 &&
243
+ roots.every((root) => root !== undefined && rewrite.routines.has(root));
210
244
  if (
211
- node.arguments.length &&
212
- (node.arguments.length !== 1 ||
213
- node.arguments[0]!.kind !== ts.SyntaxKind.ThisKeyword)
245
+ argument &&
246
+ !byRoutine &&
247
+ (rest.length || argument.kind !== ts.SyntaxKind.ThisKeyword)
214
248
  ) {
215
249
  diagnostics.push(
216
250
  rewrite.diagnostic(
@@ -220,9 +254,12 @@ function cancelScope(
220
254
  );
221
255
  }
222
256
  const name = rewrite.names.name("tsplcCancelScope", node);
223
- const member = ts.isClassDeclaration(scope);
224
257
  const body = (rewrite.sites.get(scope) ?? [])
225
- .map((site) => `${member ? "this." : ""}${site}.cancel();`)
258
+ .filter(
259
+ (site) =>
260
+ !byRoutine || (site.root !== undefined && roots.includes(site.root)),
261
+ )
262
+ .map((site) => `${member ? "this." : ""}${site.name}.cancel();`)
226
263
  .join("");
227
264
  rewrite.append(
228
265
  scope,
@@ -236,13 +273,16 @@ function cancelScope(
236
273
 
237
274
  /** The edits and generated code promise lowering makes across the program. */
238
275
  class PromiseRewrite implements PromiseContext {
239
- readonly routines = new Map<ts.Symbol, Routine>();
240
- readonly sites = new Map<ts.SourceFile | ts.ClassDeclaration, string[]>();
276
+ readonly routines: ReadonlyMap<ts.Symbol, Callable>;
277
+ readonly sites = new Map<ts.SourceFile | ts.ClassDeclaration, ChainSite[]>();
241
278
  /** The first node that needs the shared diagnostics block, which its module declares. */
242
279
  diagnosticsOwner: ts.Node | undefined;
243
- private readonly additions = new Map<ts.SourceFile, Mapped[]>();
280
+ /** Generated code by the module it ends or the class it joins. */
281
+ private readonly additions = new Map<
282
+ ts.SourceFile | ts.ClassDeclaration,
283
+ Mapped[]
284
+ >();
244
285
  private readonly edits = new Map<ts.SourceFile, Edit[]>();
245
- private readonly members = new Map<ts.ClassDeclaration, Mapped[]>();
246
286
  private readonly aliases = new Map<ts.Node, string>();
247
287
  private readonly typeImports = new Map<ts.SourceFile, Set<string>>();
248
288
  private readonly imported = new Set<ts.SourceFile>();
@@ -253,22 +293,7 @@ class PromiseRewrite implements PromiseContext {
253
293
  files: readonly ts.SourceFile[],
254
294
  readonly names: GeneratedNames,
255
295
  ) {
256
- for (const source of files) {
257
- for (const statement of source.statements) {
258
- const candidates = ts.isClassDeclaration(statement)
259
- ? statement.members.filter(ts.isMethodDeclaration)
260
- : [statement];
261
- for (const candidate of candidates) {
262
- if (
263
- (ts.isFunctionDeclaration(candidate) ||
264
- ts.isMethodDeclaration(candidate)) &&
265
- candidate.name
266
- ) {
267
- this.routines.set(this.symbol(candidate.name)!, candidate);
268
- }
269
- }
270
- }
271
- }
296
+ this.routines = namedRoutines(files, checker);
272
297
  }
273
298
 
274
299
  symbol(node: ts.Node): ts.Symbol | undefined {
@@ -292,17 +317,10 @@ class PromiseRewrite implements PromiseContext {
292
317
  origin: ts.Node,
293
318
  text: string,
294
319
  ): void {
295
- if (ts.isClassDeclaration(scope)) {
296
- this.members.set(scope, [
297
- ...(this.members.get(scope) ?? []),
298
- from(origin, text),
299
- ]);
300
- } else {
301
- this.additions.set(scope, [
302
- ...(this.additions.get(scope) ?? []),
303
- from(origin, text),
304
- ]);
305
- }
320
+ this.additions.set(scope, [
321
+ ...(this.additions.get(scope) ?? []),
322
+ from(origin, text),
323
+ ]);
306
324
  }
307
325
 
308
326
  edit(node: ts.Node, text: string): void {
@@ -314,8 +332,8 @@ class PromiseRewrite implements PromiseContext {
314
332
  }
315
333
 
316
334
  /** The modules generated code has been added to so far. */
317
- extendedFiles(): Iterable<ts.SourceFile> {
318
- return this.additions.keys();
335
+ extendedFiles(): ts.SourceFile[] {
336
+ return [...this.additions.keys()].filter(ts.isSourceFile);
319
337
  }
320
338
 
321
339
  typeText(node: ts.TypeNode, source: ts.SourceFile): string {
@@ -360,7 +378,7 @@ class PromiseRewrite implements PromiseContext {
360
378
  this.append(
361
379
  source,
362
380
  origin,
363
- `import {cooperativeTasks as tsplcCooperative,errorCode as tsplcErrorCode} from "@tsplc/compiler/async";import {wrapAdd as tsplcAsyncWrapAdd} from "@tsplc/compiler/types";`,
381
+ `import {cooperativeTasks as ${cooperativeTasksAlias},errorCode as ${errorCodeAlias}} from "${sdkModules.async}";import {wrapAdd as ${asyncWrapAdd}} from "${sdkModules.types}";`,
364
382
  );
365
383
  }
366
384
 
@@ -370,7 +388,10 @@ class PromiseRewrite implements PromiseContext {
370
388
 
371
389
  /** Each changed module's text: its edits, class members appended in place, then its additions. */
372
390
  sources(files: readonly ts.SourceFile[]): Map<string, Mapped> {
373
- for (const [owner, texts] of this.members) {
391
+ for (const [owner, texts] of this.additions) {
392
+ if (!ts.isClassDeclaration(owner)) {
393
+ continue;
394
+ }
374
395
  const source = owner.getSourceFile();
375
396
  this.edits.set(source, [
376
397
  ...(this.edits.get(source) ?? []),
@@ -1,9 +1,4 @@
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 {
3
- aggregate,
4
- type MethodOwner,
5
- type PlcFunction,
6
- } from "@tsplc/compiler/ir";
1
+ import type { MethodOwner, PlcFunction, Variable } from "@tsplc/compiler/ir";
7
2
  import ts from "typescript";
8
3
  import type { Positions } from "./positions";
9
4
  import {
@@ -16,21 +11,37 @@ import {
16
11
  /** A routine whose signature is admitted and whose body is still to be lowered. */
17
12
  interface PendingRoutine {
18
13
  node: ts.FunctionDeclaration | ts.MethodDeclaration;
14
+ body: ts.Block;
19
15
  fn: PlcFunction;
16
+ /** Each parameter's symbol and the variable it binds. */
17
+ parameters: readonly (readonly [ts.Symbol, Variable])[];
20
18
  environment: TypeEnvironment;
21
19
  }
22
20
 
21
+ /** Concrete helpers that generic calls may specialize, which bounds recursive specialization. */
22
+ const maxSpecializations = 256;
23
+
23
24
  /**
24
25
  * The routines a module contains: helpers and block methods by symbol, every
25
26
  * instance by id, and the worklist of bodies still to lower. Lowering a body can
26
27
  * instantiate more generic helpers, which join the worklist.
27
28
  */
28
29
  export class RoutineTable {
29
- readonly functions = new Map<ts.Symbol, PlcFunction>();
30
- readonly methods = new Map<ts.Symbol, PlcFunction>();
31
- readonly functionDeclarations = new Map<ts.Symbol, ts.FunctionDeclaration>();
32
- readonly instances = new Map<string, PlcFunction>();
33
- readonly pending: PendingRoutine[] = [];
30
+ private readonly functionsBySymbol = new Map<ts.Symbol, PlcFunction>();
31
+ readonly functions: ReadonlyMap<ts.Symbol, PlcFunction> =
32
+ this.functionsBySymbol;
33
+ private readonly methodsBySymbol = new Map<ts.Symbol, PlcFunction>();
34
+ readonly methods: ReadonlyMap<ts.Symbol, PlcFunction> = this.methodsBySymbol;
35
+ private readonly declarations = new Map<ts.Symbol, ts.FunctionDeclaration>();
36
+ readonly functionDeclarations: ReadonlyMap<
37
+ ts.Symbol,
38
+ ts.FunctionDeclaration
39
+ > = this.declarations;
40
+ private readonly instancesById = new Map<string, PlcFunction>();
41
+ readonly instances: ReadonlyMap<string, PlcFunction> = this.instancesById;
42
+ private readonly worklist: PendingRoutine[] = [];
43
+ readonly pending: readonly PendingRoutine[] = this.worklist;
44
+ private specializations = 0;
34
45
 
35
46
  constructor(
36
47
  private readonly checker: ts.TypeChecker,
@@ -39,46 +50,84 @@ export class RoutineTable {
39
50
  private readonly fail: Fail,
40
51
  ) {}
41
52
 
53
+ /** Admits a helper declaration; one without type parameters has its single instance now. */
54
+ declareFunction(symbol: ts.Symbol, node: ts.FunctionDeclaration): void {
55
+ this.declarations.set(symbol, node);
56
+ if (!node.typeParameters?.length) {
57
+ this.functionsBySymbol.set(
58
+ symbol,
59
+ this.instantiate(node, [], node, new Map()),
60
+ );
61
+ }
62
+ }
63
+
64
+ /** Admits a block method, which `owner` calls on its instances. */
65
+ declareMethod(
66
+ symbol: ts.Symbol,
67
+ node: ts.MethodDeclaration,
68
+ owner: MethodOwner,
69
+ ): void {
70
+ this.methodsBySymbol.set(
71
+ symbol,
72
+ this.instance(node, [], node, new Map(), owner),
73
+ );
74
+ }
75
+
76
+ /** Replaces a pending routine's instance with `fn`, its lowered body. */
77
+ complete(routine: PendingRoutine, fn: PlcFunction): void {
78
+ this.instancesById.set(fn.id, fn);
79
+ const { node } = routine;
80
+ if (
81
+ ts.isFunctionDeclaration(node) &&
82
+ node.name &&
83
+ !node.typeParameters?.length
84
+ ) {
85
+ this.functionsBySymbol.set(this.resolver.symbol(node.name), fn);
86
+ }
87
+ }
88
+
42
89
  instantiate(
43
90
  node: ts.FunctionDeclaration | ts.MethodDeclaration,
44
91
  arguments_: readonly ts.TypeNode[],
45
92
  call: ts.Node,
46
93
  outer: TypeEnvironment,
94
+ ): PlcFunction {
95
+ return this.instance(node, arguments_, call, outer, null);
96
+ }
97
+
98
+ private instance(
99
+ node: ts.FunctionDeclaration | ts.MethodDeclaration,
100
+ arguments_: readonly ts.TypeNode[],
101
+ call: ts.Node,
102
+ outer: TypeEnvironment,
103
+ owner: MethodOwner | null,
47
104
  ): PlcFunction {
48
105
  if (!node.name || !ts.isIdentifier(node.name)) {
49
106
  this.fail(node, "PLC1001", "PLC routines need identifier names.");
50
107
  }
51
108
  const routineName = node.name.text;
52
- const environment = this.resolver.bindings(
109
+ const { environment, suffix } = this.resolver.bindings(
53
110
  node.typeParameters,
54
111
  arguments_,
55
112
  outer,
56
113
  call,
57
114
  );
58
- const suffix = (node.typeParameters ?? [])
59
- .map((parameter) =>
60
- this.resolver.key(
61
- environment.get(this.resolver.symbol(parameter.name))!,
62
- ),
63
- )
64
- .join(",");
65
115
  const id = `${this.resolver.id(node, routineName)}${suffix ? `<${suffix}>` : ""}`;
66
- const existing = this.instances.get(id);
116
+ const existing = this.instancesById.get(id);
67
117
  if (existing) {
68
118
  return existing;
69
119
  }
70
- // Bounds generic expansion; plain helpers each instantiate once.
71
- if (
72
- suffix &&
73
- [...this.instances.keys()].filter((key) => key.endsWith(">")).length >=
74
- 256
75
- ) {
120
+ if (suffix && this.specializations >= maxSpecializations) {
76
121
  this.fail(
77
122
  call,
78
123
  "PLC2001",
79
- "Generic specialization exceeds 256 concrete helpers; recursive specialization is unsupported.",
124
+ `Generic specialization exceeds ${maxSpecializations} concrete helpers; recursive specialization is unsupported.`,
80
125
  );
81
126
  }
127
+ const body = node.body;
128
+ if (!body) {
129
+ throw new Error(`Routine ${id} has no implementation to lower.`);
130
+ }
82
131
  const parameters = node.parameters.map((parameter) => {
83
132
  if (
84
133
  !ts.isIdentifier(parameter.name) ||
@@ -109,38 +158,44 @@ export class RoutineTable {
109
158
  "Parameters cannot use logical I/O wrappers.",
110
159
  );
111
160
  }
112
- // Records, arrays and blocks pass by reference, as objects do in TypeScript.
113
- const mode =
114
- type.mode ??
115
- (block || aggregate(this.resolver.types.get(type.type))
116
- ? "inOut"
117
- : undefined);
118
- return {
161
+ const mode = this.resolver.parameterMode(type);
162
+ const variable: Variable = {
119
163
  id: `${this.resolver.id(parameter, parameter.name.text)}@${id}`,
120
164
  name: parameter.name.text,
121
165
  type: type.type,
122
- storage: "parameter" as const,
166
+ storage: "parameter",
123
167
  mutable: mode === "inOut",
124
168
  ...(mode && { mode }),
125
- retain: false,
169
+ retention: "none",
126
170
  span: this.positions.node(parameter),
127
171
  };
172
+ return [this.resolver.symbol(parameter.name), variable] as const;
128
173
  });
129
- let result: string | undefined;
130
- if (node.type && node.type.kind !== ts.SyntaxKind.VoidKeyword) {
131
- const type = this.resolver.resolve(node.type, environment);
132
- if (!this.resolver.isValue(type)) {
133
- this.fail(node.type, "PLC2001", "Helper results require value types.");
134
- }
135
- if (type.io) {
136
- this.fail(
137
- node.type,
138
- "PLC4002",
139
- "Helper results cannot use I/O wrappers.",
140
- );
141
- }
142
- result = type.type;
143
- } else if (!node.type) {
174
+ const result = this.result(node, environment);
175
+ const fn: PlcFunction = {
176
+ id,
177
+ name: `${routineName}${suffix ? `_${suffix}` : ""}`,
178
+ parameters: parameters.map(([, variable]) => variable),
179
+ locals: [],
180
+ body: [],
181
+ span: this.positions.node(node),
182
+ ...(result && { result }),
183
+ ...(owner && { owner }),
184
+ };
185
+ this.instancesById.set(id, fn);
186
+ if (suffix) {
187
+ this.specializations++;
188
+ }
189
+ this.worklist.push({ node, body, fn, parameters, environment });
190
+ return fn;
191
+ }
192
+
193
+ /** The type a routine returns; undefined when it returns nothing. */
194
+ private result(
195
+ node: ts.FunctionDeclaration | ts.MethodDeclaration,
196
+ environment: TypeEnvironment,
197
+ ): string | undefined {
198
+ if (!node.type) {
144
199
  const signature = this.checker.getSignatureFromDeclaration(node);
145
200
  if (
146
201
  !signature ||
@@ -151,21 +206,23 @@ export class RoutineTable {
151
206
  ) {
152
207
  this.fail(node, "PLC2001", "Annotate helper results explicitly.");
153
208
  }
209
+ return undefined;
154
210
  }
155
- const bounds = this.resolver.mathHelper(node, routineName);
156
- const fn: PlcFunction = {
157
- id,
158
- name: `${routineName}${suffix ? `_${suffix}` : ""}`,
159
- parameters,
160
- locals: [],
161
- body: [],
162
- span: this.positions.node(node),
163
- ...(result && { result }),
164
- ...(bounds && { bounds }),
165
- };
166
- this.instances.set(id, fn);
167
- this.pending.push({ node, fn, environment });
168
- return fn;
211
+ if (node.type.kind === ts.SyntaxKind.VoidKeyword) {
212
+ return undefined;
213
+ }
214
+ const type = this.resolver.resolve(node.type, environment);
215
+ if (!this.resolver.isValue(type)) {
216
+ this.fail(node.type, "PLC2001", "Helper results require value types.");
217
+ }
218
+ if (type.io) {
219
+ this.fail(
220
+ node.type,
221
+ "PLC4002",
222
+ "Helper results cannot use I/O wrappers.",
223
+ );
224
+ }
225
+ return type.type;
169
226
  }
170
227
  }
171
228