@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,20 +1,45 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
- import { basename, dirname } from "node:path";
3
+ import { basename, dirname, join } from "node:path";
4
4
  import ts from "typescript";
5
5
 
6
+ /** The specifiers a program imports the SDK's modules by. */
7
+ export const sdkModules = {
8
+ async: "@tsplc/compiler/async",
9
+ clock: "@tsplc/compiler/clock",
10
+ config: "@tsplc/compiler/config",
11
+ globals: "@tsplc/compiler/globals",
12
+ retain: "@tsplc/compiler/retain",
13
+ telemetry: "@tsplc/compiler/telemetry",
14
+ types: "@tsplc/compiler/types",
15
+ } as const;
16
+
17
+ /** The methods of `@tsplc/compiler/telemetry`'s `telemetry`. */
18
+ export const telemetryMethods = [
19
+ "capture",
20
+ "info",
21
+ "warn",
22
+ "error",
23
+ "captureException",
24
+ "text",
25
+ ] as const;
26
+
6
27
  /** The `@tsplc/compiler/globals` declaration file a project compiles against. */
7
28
  export const sdkFor = (
8
29
  project: string,
9
30
  options: ts.CompilerOptions,
10
31
  ): string => {
11
- const name = "@tsplc/compiler/globals";
12
32
  const resolveSdk = (from: string) =>
13
- createRequire(from).resolve(name).replaceAll("\\", "/");
33
+ createRequire(from).resolve(sdkModules.globals).replaceAll("\\", "/");
14
34
  try {
15
35
  const installed = resolveSdk(project);
36
+ // Bun answers a project without node_modules from its global cache, which holds whatever
37
+ // version it last fetched: that is no install of the project's.
38
+ if (!installed.includes("/node_modules/")) {
39
+ return resolveSdk(import.meta.url);
40
+ }
16
41
  const resolved = ts.resolveModuleName(
17
- name,
42
+ sdkModules.globals,
18
43
  project,
19
44
  options,
20
45
  ts.sys,
@@ -36,10 +61,16 @@ export const sdkFor = (
36
61
  ) {
37
62
  throw cause;
38
63
  }
64
+ // A project that does not install @tsplc/compiler, as the compiler's own test projects
65
+ // do not, compiles against this compiler's SDK.
39
66
  return resolveSdk(import.meta.url);
40
67
  }
41
68
  };
42
69
 
70
+ /** The dialect's globals beside `sdk`, which only the compiler's own generated code may use. */
71
+ export const dialectFor = (sdk: string): string =>
72
+ join(dirname(sdk), "dialect.d.ts").replaceAll("\\", "/");
73
+
43
74
  /** Whether `fileName` is one of the SDK declaration files, which sit beside `sdk`. */
44
75
  export const inSdk = (sdk: string, fileName: string): boolean =>
45
76
  fileName.startsWith(`${dirname(sdk)}/`);
@@ -50,6 +81,22 @@ export const sdkModule = (fileName: string): string => {
50
81
  return `@tsplc/compiler/${name === "index" ? "types" : name}`;
51
82
  };
52
83
 
84
+ /** Whether `declaration` is in the SDK module a program imports by `module`. */
85
+ export const declaredInSdkModule = (
86
+ sdk: string,
87
+ module: (typeof sdkModules)[keyof typeof sdkModules],
88
+ declaration: ts.Declaration,
89
+ ): boolean => {
90
+ const file = declaration.getSourceFile().fileName;
91
+ return inSdk(sdk, file) && sdkModule(file) === module;
92
+ };
93
+
94
+ /** Whether `declaration` is in the SDK's `@tsplc/compiler/telemetry`. */
95
+ export const isTelemetryDeclaration = (
96
+ sdk: string,
97
+ declaration: ts.Declaration,
98
+ ): boolean => declaredInSdkModule(sdk, sdkModules.telemetry, declaration);
99
+
53
100
  /** A symbol followed through import and export aliases to what it names. */
54
101
  export const unaliased = (
55
102
  checker: ts.TypeChecker,
@@ -68,6 +115,15 @@ export const symbolAt = (
68
115
  return symbol && unaliased(checker, symbol);
69
116
  };
70
117
 
118
+ /** The symbol `node` reads; a shorthand property's own name reads the variable it is named for, not the property it declares. */
119
+ export const valueSymbol = (
120
+ checker: ts.TypeChecker,
121
+ node: ts.Node,
122
+ ): ts.Symbol | undefined =>
123
+ ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node
124
+ ? checker.getShorthandAssignmentValueSymbol(node.parent)
125
+ : checker.getSymbolAtLocation(node);
126
+
71
127
  /** Whether the SDK declares `symbol`. */
72
128
  export const declaredBySdk = (sdk: string, symbol: ts.Symbol): boolean =>
73
129
  Boolean(
@@ -76,7 +132,7 @@ export const declaredBySdk = (sdk: string, symbol: ts.Symbol): boolean =>
76
132
  ),
77
133
  );
78
134
 
79
- /** Whether `node` names the SDK's `name`, such as `sleep`, `expose` or `env`. */
135
+ /** Whether `node` names the SDK's `name`, such as `sleep` or `env`. */
80
136
  export const namesSdk = (
81
137
  checker: ts.TypeChecker,
82
138
  sdk: string,
@@ -86,3 +142,46 @@ export const namesSdk = (
86
142
  const symbol = symbolAt(checker, node);
87
143
  return symbol?.name === name && declaredBySdk(sdk, symbol);
88
144
  };
145
+
146
+ /** Whether a type holds an InOut borrow, directly or through the layouts it names. */
147
+ export const holdsBorrow = (
148
+ context: {
149
+ namesSdk: (node: ts.Node, name: string) => boolean;
150
+ symbol: (node: ts.Node) => ts.Symbol | undefined;
151
+ },
152
+ type: ts.Node,
153
+ ): boolean => {
154
+ const seen = new Set<ts.Symbol>();
155
+ const visit = (node: ts.Node): boolean => {
156
+ if (ts.isTypeReferenceNode(node)) {
157
+ if (context.namesSdk(node.typeName, "InOut")) {
158
+ return true;
159
+ }
160
+ const symbol = context.symbol(node.typeName);
161
+ if (symbol && !seen.has(symbol)) {
162
+ seen.add(symbol);
163
+ for (const declaration of symbol.declarations ?? []) {
164
+ if (
165
+ ts.isInterfaceDeclaration(declaration) &&
166
+ declaration.members.some(
167
+ (member) =>
168
+ ts.isPropertySignature(member) &&
169
+ member.type &&
170
+ visit(member.type),
171
+ )
172
+ ) {
173
+ return true;
174
+ }
175
+ if (
176
+ ts.isTypeAliasDeclaration(declaration) &&
177
+ visit(declaration.type)
178
+ ) {
179
+ return true;
180
+ }
181
+ }
182
+ }
183
+ }
184
+ return ts.forEachChild(node, (child) => visit(child) || undefined) ?? false;
185
+ };
186
+ return visit(type);
187
+ };
@@ -1,18 +1,19 @@
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 { dirname, join, relative } from "node:path";
1
+ import { dirname, join } from "node:path";
3
2
  import { type Diagnostic, error } from "@tsplc/compiler/ir";
3
+ import type { ServerConfig } from "@tsplc/config";
4
4
  import {
5
5
  isIntegerType,
6
+ plcProcedureKind,
6
7
  type ServiceContract,
7
8
  serviceContract,
8
- servicePath,
9
9
  type WireField,
10
10
  type WireScalar,
11
11
  wireLayout,
12
12
  wireRecord,
13
- } from "@tsplc/server";
13
+ } from "@tsplc/server/contract";
14
+ import { servicePath } from "@tsplc/server/wire";
14
15
  import ts from "typescript";
15
- import { runtimeSources } from "./module-graph";
16
+ import { importSpecifier, plcSources, runtimeImport } from "./module-graph";
16
17
  import {
17
18
  type Edit,
18
19
  edited,
@@ -21,13 +22,38 @@ import {
21
22
  mapped,
22
23
  type Positions,
23
24
  } from "./positions";
24
- import { namesSdk, symbolAt } from "./sdk";
25
+ import { namesSdk, sdkModules, symbolAt } from "./sdk";
26
+ import type { ServiceRecord } from "./types";
25
27
 
26
28
  /** The server section's transport; each client's type argument names its router. */
27
- export interface ServiceOptions {
28
- transport: "http" | "opcua";
29
- baseUrlEnv?: string;
30
- }
29
+ export type ServiceOptions = Pick<ServerConfig, "transport" | "baseUrlEnv">;
30
+
31
+ /** Why a procedure's input or output cannot cross the wire to the PLC; the message names the field. */
32
+ class WireLayoutError extends Error {}
33
+
34
+ /** A server contract check, whose every Error describes a schema the PLC cannot exchange. */
35
+ const contractCheck = <T>(check: () => T): T => {
36
+ try {
37
+ return check();
38
+ } catch (cause) {
39
+ throw cause instanceof Error ? new WireLayoutError(cause.message) : cause;
40
+ }
41
+ };
42
+
43
+ /** What `read` returns, or the WireLayoutError it rejected the schema with. */
44
+ const wireLayoutOf = <T>(read: () => T): T | WireLayoutError => {
45
+ try {
46
+ return read();
47
+ } catch (cause) {
48
+ if (cause instanceof WireLayoutError) {
49
+ return cause;
50
+ }
51
+ throw cause;
52
+ }
53
+ };
54
+
55
+ /** The longest server base URL the PLC holds. */
56
+ const baseUrlCapacity = 512;
31
57
 
32
58
  /** A procedure record read from its type, with the PLC enum each enum field names. */
33
59
  interface RecordLayout {
@@ -54,7 +80,7 @@ const layoutNumber = (
54
80
  return undefined;
55
81
  }
56
82
  if (!value.isNumberLiteral()) {
57
- throw new Error(`${label}: ${name} must be a literal number.`);
83
+ throw new WireLayoutError(`${label}: ${name} must be a literal number.`);
58
84
  }
59
85
  return value.value;
60
86
  };
@@ -80,7 +106,9 @@ const scalarLayout = (
80
106
  for (const item of member.parent.members) {
81
107
  const value = checker.getConstantValue(item);
82
108
  if (typeof value !== "number") {
83
- throw new Error(`${label}: PLC enums require numeric members.`);
109
+ throw new WireLayoutError(
110
+ `${label}: PLC enums require numeric members.`,
111
+ );
84
112
  }
85
113
  members[item.name.getText()] = value;
86
114
  }
@@ -100,7 +128,7 @@ const scalarLayout = (
100
128
  return { field: { kind: "integer", iec: iec.value, minimum, maximum } };
101
129
  }
102
130
  }
103
- throw new Error(
131
+ throw new WireLayoutError(
104
132
  `${label}: use z.boolean(), z.enum() of a numeric enum, iec.STRING(), or an integer such as iec.INT().`,
105
133
  );
106
134
  };
@@ -121,14 +149,16 @@ const recordLayout = (
121
149
  type.getNumberIndexType() ||
122
150
  type.getCallSignatures().length
123
151
  ) {
124
- throw new Error(
152
+ throw new WireLayoutError(
125
153
  `${label}: PLC procedures exchange one closed z.strictObject() record.`,
126
154
  );
127
155
  }
128
156
  for (const field of type.getProperties()) {
129
157
  const key = `${label}.${field.name}`;
130
158
  if (field.flags & ts.SymbolFlags.Optional) {
131
- throw new Error(`${key}: optional wire fields are unsupported.`);
159
+ throw new WireLayoutError(
160
+ `${key}: optional wire fields are unsupported.`,
161
+ );
132
162
  }
133
163
  const value = checker.getTypeOfSymbol(field);
134
164
  const length = layoutNumber(checker, value, "length", key);
@@ -144,7 +174,10 @@ const recordLayout = (
144
174
  }
145
175
  }
146
176
  }
147
- return { fields: wireRecord(fields, label, output).fields, enums };
177
+ return {
178
+ fields: contractCheck(() => wireRecord(fields, label, output)).fields,
179
+ enums,
180
+ };
148
181
  };
149
182
 
150
183
  /** Identifies a record by layout, so every name for it lowers to one PLC struct. */
@@ -165,11 +198,10 @@ const procedureAt = (
165
198
  router: ts.Type,
166
199
  path: readonly string[],
167
200
  ) => {
168
- let type = property(checker, router, "_def");
169
- type = type && property(checker, type, "record");
170
- for (const part of path) {
171
- type = type && property(checker, type, part);
172
- }
201
+ const type = ["_def", "record", ...path].reduce<ts.Type | undefined>(
202
+ (parent, name) => parent && property(checker, parent, name),
203
+ router,
204
+ );
173
205
  const definition = type && property(checker, type, "_def");
174
206
  if (!definition || !property(checker, definition, "procedure")) {
175
207
  return undefined;
@@ -191,6 +223,52 @@ const pascalServicePath = (path: string) =>
191
223
  .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
192
224
  .join("");
193
225
 
226
+ /** The export of the generated service module that calls the procedure at `path`. */
227
+ const serviceExportName = (path: string) =>
228
+ `tsplcService_${path.replaceAll(".", "_")}`;
229
+
230
+ interface ServiceCall {
231
+ contract: ServiceContract;
232
+ input: string;
233
+ output: string;
234
+ }
235
+
236
+ /** A called procedure's contract with the record names it exchanges, or why the PLC cannot call it. */
237
+ const serviceCall = (
238
+ checker: ts.TypeChecker,
239
+ path: string,
240
+ procedure: NonNullable<ReturnType<typeof procedureAt>>,
241
+ record: (layout: RecordLayout, name: string) => string,
242
+ ): ServiceCall | WireLayoutError =>
243
+ wireLayoutOf(() => {
244
+ const kind = contractCheck(() => plcProcedureKind(path, procedure.kind));
245
+ const input = recordLayout(
246
+ checker,
247
+ procedure.input,
248
+ `${path}.input`,
249
+ false,
250
+ );
251
+ const output = recordLayout(
252
+ checker,
253
+ procedure.output,
254
+ `${path}.output`,
255
+ true,
256
+ );
257
+ const contract = contractCheck(() =>
258
+ serviceContract(
259
+ path,
260
+ kind,
261
+ { fields: input.fields },
262
+ { fields: output.fields },
263
+ ),
264
+ );
265
+ return {
266
+ contract,
267
+ input: record(input, `${pascalServicePath(path)}Input`),
268
+ output: record(output, `${pascalServicePath(path)}Output`),
269
+ };
270
+ });
271
+
194
272
  /**
195
273
  * Replaces each `createServiceClient<Router>()` call with an in-memory module of the called
196
274
  * procedures, read from the router's type: the server never runs and no file is written.
@@ -204,10 +282,7 @@ export const lowerServices = (
204
282
  const sources = new Map<string, Mapped>();
205
283
  const diagnostics: Diagnostic[] = [];
206
284
  const records = new Map<string, { name: string; layout: RecordLayout }>();
207
- const calls = new Map<
208
- string,
209
- { contract: ServiceContract; input: string; output: string }
210
- >();
285
+ const calls = new Map<string, ServiceCall>();
211
286
  const checker = program.getTypeChecker();
212
287
  const fail = (node: ts.Node, code: string, message: string) =>
213
288
  diagnostics.push(error(code, message, positions.node(node)));
@@ -224,9 +299,7 @@ export const lowerServices = (
224
299
  const clients = new Map<ts.Symbol, ts.Type>();
225
300
  /** The generated service module, and the first client's creation it stands for. */
226
301
  let module: { file: string; client: ts.CallExpression } | undefined;
227
- const sourceFiles = runtimeSources(program).filter(
228
- (source) => !source.isDeclarationFile,
229
- );
302
+ const sourceFiles = plcSources(program);
230
303
  for (const source of sourceFiles) {
231
304
  for (const statement of source.statements) {
232
305
  if (!ts.isVariableStatement(statement)) {
@@ -286,13 +359,8 @@ export const lowerServices = (
286
359
  ) {
287
360
  const clause = node.importClause;
288
361
  const bindings = clause?.namedBindings;
289
- const typeOnly =
290
- clause?.isTypeOnly ||
291
- (!clause?.name &&
292
- bindings &&
293
- ts.isNamedImports(bindings) &&
294
- bindings.elements.every((element) => element.isTypeOnly));
295
- if (!typeOnly && clause && bindings && ts.isNamedImports(bindings)) {
362
+ const runtime = runtimeImport(node, checker);
363
+ if (runtime && clause && bindings && ts.isNamedImports(bindings)) {
296
364
  const elements = bindings.elements.filter((element) => {
297
365
  const imported = symbolAt(checker, element.name);
298
366
  return !imported || !clients.has(imported);
@@ -326,7 +394,7 @@ export const lowerServices = (
326
394
  }
327
395
  }
328
396
  if (
329
- !typeOnly &&
397
+ runtime &&
330
398
  (node.moduleSpecifier.text.startsWith("node:") ||
331
399
  [
332
400
  "@tsplc/server",
@@ -358,6 +426,20 @@ export const lowerServices = (
358
426
  return;
359
427
  }
360
428
  }
429
+ // The client's binding is removed, so a type of it, as `typeof services`, has nothing to name.
430
+ if (clients.size && ts.isTypeQueryNode(node)) {
431
+ const named = ts.isQualifiedName(node.exprName)
432
+ ? undefined
433
+ : symbolAt(checker, node.exprName);
434
+ if (named && clients.has(named)) {
435
+ edits.push({
436
+ start: node.getStart(source),
437
+ end: node.end,
438
+ text: "unknown",
439
+ });
440
+ return;
441
+ }
442
+ }
361
443
  if (clients.size && ts.isPropertyAccessExpression(node)) {
362
444
  const parts: string[] = [];
363
445
  let root: ts.Expression = node;
@@ -378,47 +460,14 @@ export const lowerServices = (
378
460
  );
379
461
  return;
380
462
  }
381
- let call = calls.get(path);
382
- if (!call) {
383
- try {
384
- if (procedure.kind !== "query" && procedure.kind !== "mutation") {
385
- throw new Error(
386
- `${path}: subscriptions use a different transport; expose a query or mutation to the PLC.`,
387
- );
388
- }
389
- const input = recordLayout(
390
- checker,
391
- procedure.input,
392
- `${path}.input`,
393
- false,
394
- );
395
- const output = recordLayout(
396
- checker,
397
- procedure.output,
398
- `${path}.output`,
399
- true,
400
- );
401
- call = {
402
- contract: serviceContract(
403
- path,
404
- procedure.kind,
405
- { fields: input.fields },
406
- { fields: output.fields },
407
- ),
408
- input: record(input, `${pascalServicePath(path)}Input`),
409
- output: record(output, `${pascalServicePath(path)}Output`),
410
- };
411
- calls.set(path, call);
412
- } catch (cause) {
413
- fail(
414
- node,
415
- "PLC2001",
416
- cause instanceof Error ? cause.message : String(cause),
417
- );
418
- return;
419
- }
463
+ const call =
464
+ calls.get(path) ?? serviceCall(checker, path, procedure, record);
465
+ if (call instanceof WireLayoutError) {
466
+ fail(node, "PLC2001", call.message);
467
+ return;
420
468
  }
421
- const name = `tsplcService_${path.replaceAll(".", "_")}`;
469
+ calls.set(path, call);
470
+ const name = serviceExportName(path);
422
471
  const local = imports.get(name) ?? `tsplcRemote${imports.size}`;
423
472
  imports.set(name, local);
424
473
  edits.push({
@@ -435,15 +484,13 @@ export const lowerServices = (
435
484
  if (!edits.length) {
436
485
  continue;
437
486
  }
438
- let text = edited(source, edits);
439
- if (imports.size && module) {
440
- const path = relative(dirname(source.fileName), module.file).replaceAll(
441
- "\\",
442
- "/",
443
- );
444
- text = mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};\n`;
445
- }
446
- sources.set(source.fileName, text);
487
+ const text = edited(source, edits);
488
+ sources.set(
489
+ source.fileName,
490
+ imports.size && module
491
+ ? mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${importSpecifier(source.fileName, module.file)};\n`
492
+ : text,
493
+ );
447
494
  }
448
495
  if (module && options) {
449
496
  sources.set(
@@ -461,10 +508,7 @@ export const lowerServices = (
461
508
 
462
509
  const serviceModule = (
463
510
  records: ReadonlyMap<string, { name: string; layout: RecordLayout }>,
464
- calls: ReadonlyMap<
465
- string,
466
- { contract: ServiceContract; input: string; output: string }
467
- >,
511
+ calls: ReadonlyMap<string, ServiceCall>,
468
512
  options: ServiceOptions,
469
513
  ) => {
470
514
  const enums = new Map<ts.EnumDeclaration, string>();
@@ -485,7 +529,10 @@ const serviceModule = (
485
529
  case "string":
486
530
  return `STRING<${field.capacity}>`;
487
531
  case "enum":
488
- return enumName(enumeration!);
532
+ if (!enumeration) {
533
+ throw new Error("An enum wire field has no PLC enum declaration.");
534
+ }
535
+ return enumName(enumeration);
489
536
  }
490
537
  };
491
538
  const interfaces = [...records.values()].map(({ name, layout }) => {
@@ -510,19 +557,19 @@ const serviceModule = (
510
557
  options.transport === "http"
511
558
  ? `tsplcServiceFetch<${output}>(\`\${tsplcServiceBaseUrl}${servicePath(contract)}\`,{method:"POST",json:${request}})`
512
559
  : `tsplcServiceCall<${output},${input}>(${JSON.stringify(servicePath(contract))},${request})`;
513
- return `export const tsplcService_${contract.path.replaceAll(".", "_")}=async(${hasInput ? `input:${input}` : ""}):Promise<${output}>=>{return await ${operation};};`;
560
+ return `export const ${serviceExportName(contract.path)}=async(${hasInput ? `input:${input}` : ""}):Promise<${output}>=>{return await ${operation};};`;
514
561
  });
515
562
  const transport =
516
563
  options.transport === "http"
517
- ? `import {fetch as tsplcServiceFetch} from "@tsplc/compiler/async";\nimport {env as tsplcServiceEnv} from "@tsplc/compiler/config";`
518
- : `import {opcuaCall as tsplcServiceCall} from "@tsplc/compiler/async";`;
564
+ ? `import {fetch as tsplcServiceFetch} from "${sdkModules.async}";\nimport {env as tsplcServiceEnv} from "${sdkModules.config}";`
565
+ : `import {opcuaCall as tsplcServiceCall} from "${sdkModules.async}";`;
519
566
  const enumImports = [...enums].map(
520
567
  ([declaration, name]) =>
521
568
  `import type {${declaration.name.text} as ${name}} from ${JSON.stringify(declaration.getSourceFile().fileName)};`,
522
569
  );
523
570
  const baseUrl =
524
571
  options.transport === "http"
525
- ? `const tsplcServiceBaseUrl:STRING<512>=tsplcServiceEnv<STRING<512>>(${JSON.stringify(options.baseUrlEnv)});`
572
+ ? `const tsplcServiceBaseUrl:STRING<${baseUrlCapacity}>=tsplcServiceEnv<STRING<${baseUrlCapacity}>>(${JSON.stringify(options.baseUrlEnv)});`
526
573
  : "";
527
574
  return `${[
528
575
  transport,
@@ -537,10 +584,10 @@ const serviceModule = (
537
584
  export const serviceRecords = (
538
585
  program: ts.Program,
539
586
  lowering: { file: string | undefined; records: ReadonlyMap<string, string> },
540
- ) => {
587
+ ): ServiceRecord | null => {
541
588
  const source = lowering.file && program.getSourceFile(lowering.file);
542
589
  if (!source) {
543
- return undefined;
590
+ return null;
544
591
  }
545
592
  const checker = program.getTypeChecker();
546
593
  const declarations = new Map(
@@ -548,14 +595,14 @@ export const serviceRecords = (
548
595
  .filter(ts.isInterfaceDeclaration)
549
596
  .map((value) => [value.name.text, value]),
550
597
  );
551
- return (type: ts.Type): ts.Symbol | undefined => {
552
- let key: string;
553
- try {
554
- key = recordKey(recordLayout(checker, type, "record", false));
555
- } catch {
598
+ return (type) => {
599
+ const layout = wireLayoutOf(() =>
600
+ recordLayout(checker, type, "record", false),
601
+ );
602
+ if (layout instanceof WireLayoutError) {
556
603
  return undefined;
557
604
  }
558
- const name = lowering.records.get(key);
605
+ const name = lowering.records.get(recordKey(layout));
559
606
  const declaration = name === undefined ? undefined : declarations.get(name);
560
607
  return declaration && checker.getSymbolAtLocation(declaration.name);
561
608
  };