@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
@@ -2,23 +2,23 @@ import { mkdirSync, writeFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, join, relative, resolve } from "node:path";
4
4
  import { type Diagnostic, hasErrors, type PlcModule } from "@tsplc/compiler/ir";
5
+ import type { Environment } from "@tsplc/config";
6
+ import { generatedDirectory } from "@tsplc/config/project-files";
5
7
  import ts from "typescript";
6
8
  import { Analyzer, suppressionDiagnostics } from "./analyzer";
7
9
  import { type AsyncLowering, lowerAsync } from "./async";
8
10
  import { lowerEnvironment } from "./configuration";
9
11
  import { lowerConstFunctions } from "./const-functions";
10
12
  import { lowerControlFlow } from "./control-flow";
13
+ import { dialectUses } from "./dialect-names";
11
14
  import { lowerElaboration } from "./elaborate/index";
12
- import { lowerExposure } from "./exposure";
15
+ import { declarationKey, typeKey } from "./lowering-key";
13
16
  import { runtimeSources } from "./module-graph";
14
17
  import { type Mapped, Positions, sourceSpan } from "./positions";
15
18
  import { lowerPromises } from "./promises";
16
- import { inSdk, sdkFor } from "./sdk";
19
+ import { dialectFor, inSdk, sdkFor } from "./sdk";
17
20
  import { lowerServices, type ServiceOptions, serviceRecords } from "./services";
18
21
 
19
- /** The host environment a compilation reads, as `env()` values and endpoint settings. */
20
- export type CompileEnvironment = Readonly<Record<string, string | undefined>>;
21
-
22
22
  /** What a compilation writes or adds to help debug the compiler itself. */
23
23
  export interface CompileDebug {
24
24
  /** Writes every module the compiler generates or rewrites here, as the next step reads it. */
@@ -28,7 +28,7 @@ export interface CompileDebug {
28
28
  }
29
29
 
30
30
  /** The documented switches: `TSPLC_LOWERED=<directory>` and `TSPLC_DEBUG=1`. */
31
- const compileDebug = (environment: CompileEnvironment): CompileDebug => ({
31
+ const compileDebug = (environment: Environment): CompileDebug => ({
32
32
  lowered: environment.TSPLC_LOWERED || null,
33
33
  stackTraces: Boolean(environment.TSPLC_DEBUG),
34
34
  });
@@ -39,7 +39,19 @@ export interface FrontendOptions {
39
39
  tsconfig: string;
40
40
  programs: Readonly<Record<string, { module: string; export: string }>>;
41
41
  /** What `env()` reads, and the debug switches; this process's environment by default. */
42
- environment?: CompileEnvironment;
42
+ environment?: Environment;
43
+ /**
44
+ * The state paths the config's `io` binds. The hardware writes them, so the object each starts
45
+ * from is state even where scan code only reads it.
46
+ */
47
+ io: readonly BoundPath[];
48
+ }
49
+
50
+ /** A state path the config's `io` binds, and the input address the hardware writes it from. */
51
+ export interface BoundPath {
52
+ path: string;
53
+ /** The `%I` address of an input, which scan code can't assign; null for an output. */
54
+ input: string | null;
43
55
  }
44
56
 
45
57
  export interface FrontendResult {
@@ -49,7 +61,7 @@ export interface FrontendResult {
49
61
 
50
62
  function tsDiagnostic(
51
63
  diagnostic: ts.Diagnostic,
52
- locate = sourceSpan,
64
+ locate: typeof sourceSpan,
53
65
  ): Diagnostic {
54
66
  const result: Diagnostic = {
55
67
  origin: "typescript",
@@ -83,35 +95,57 @@ export const typeCheckOnly: ts.CompilerOptions = {
83
95
  tsBuildInfoFile: undefined,
84
96
  };
85
97
 
98
+ /** Compiles a program's PLC TypeScript into the PLC model: plain TypeScript, never the dialect. */
86
99
  export function analyze(options: FrontendOptions): FrontendResult {
100
+ return compileFrontend(options, "rejected");
101
+ }
102
+
103
+ /**
104
+ * Compiles source that may be written in the tsPLC dialect, the language plain programs lower
105
+ * into. No command reaches it: the compiler's tests write the dialect to drive its later stages.
106
+ */
107
+ export function analyzeDialect(options: FrontendOptions): FrontendResult {
108
+ return compileFrontend(options, "accepted");
109
+ }
110
+
111
+ /**
112
+ * The frontend. With the dialect `rejected`, every program is plain TypeScript that elaboration
113
+ * compiles from its setup; `accepted`, a program elaborates only when it declares a plain class.
114
+ */
115
+ function compileFrontend(
116
+ options: FrontendOptions,
117
+ dialect: "rejected" | "accepted",
118
+ ): FrontendResult {
87
119
  const environment = options.environment ?? { ...process.env };
88
120
  const debug = compileDebug(environment);
89
121
  const filename = resolve(options.tsconfig);
122
+ const root = dirname(filename);
90
123
  const config = ts.readConfigFile(filename, ts.sys.readFile);
91
124
  if (config.error) {
92
- return { diagnostics: [tsDiagnostic(config.error)] };
125
+ return { diagnostics: [tsDiagnostic(config.error, sourceSpan)] };
93
126
  }
94
127
  const parsed = ts.parseJsonConfigFileContent(
95
128
  config.config,
96
129
  ts.sys,
97
- dirname(filename),
130
+ root,
98
131
  undefined,
99
132
  filename,
100
133
  );
101
134
  if (parsed.errors.length) {
102
135
  return {
103
- diagnostics: parsed.errors.map((diagnostic) => tsDiagnostic(diagnostic)),
136
+ diagnostics: parsed.errors.map((diagnostic) =>
137
+ tsDiagnostic(diagnostic, sourceSpan),
138
+ ),
104
139
  };
105
140
  }
106
141
  const programFiles = Object.values(options.programs).map((entry) =>
107
- resolve(dirname(filename), entry.module),
142
+ resolve(root, entry.module),
108
143
  );
109
144
  // Full-stack builds follow entry imports; standalone projects retain explicit tsconfig globals.
110
145
  const scope = options.sourceScope ?? (options.services ? "entry" : "project");
111
146
  // The project's own ambient declarations; a shared base tsconfig's typings are for the host runtime.
112
147
  const ambient = parsed.fileNames.filter(
113
- (file) =>
114
- /\.d\.[cm]?ts$/.test(file) && file.startsWith(`${dirname(filename)}/`),
148
+ (file) => /\.d\.[cm]?ts$/.test(file) && file.startsWith(`${root}/`),
115
149
  );
116
150
  const projectFiles = scope === "project" ? parsed.fileNames : ambient;
117
151
  const compilerOptions: ts.CompilerOptions = {
@@ -136,11 +170,13 @@ export function analyze(options: FrontendOptions): FrontendResult {
136
170
  delete compilerOptions.rootDir;
137
171
  delete compilerOptions.outDir;
138
172
  const sdk = sdkFor(filename, compilerOptions);
139
- const rootNames = [...new Set([...projectFiles, ...programFiles, sdk])];
173
+ const rootNames = [
174
+ ...new Set([...projectFiles, ...programFiles, sdk, dialectFor(sdk)]),
175
+ ];
140
176
  const virtualSources = new Map<string, string>();
141
177
  // Lowering also adds modules, such as the service client, that exist only here.
142
178
  const host = loweringHost(compilerOptions, virtualSources);
143
- let program = ts.createProgram(rootNames, compilerOptions, host);
179
+ const program = ts.createProgram(rootNames, compilerOptions, host);
144
180
  const plcFiles = (program: ts.Program) => {
145
181
  const files = new Set(runtimeSources(program));
146
182
  for (const source of program.getSourceFiles()) {
@@ -151,29 +187,43 @@ export function analyze(options: FrontendOptions): FrontendResult {
151
187
  return files;
152
188
  };
153
189
  const positions = new Positions();
190
+ const generated = (file: ts.SourceFile) =>
191
+ virtualSources.has(file.fileName) &&
192
+ file.fileName.includes(`/${generatedDirectory}/`);
154
193
  // Only PLC files: a type-only import of the server router brings the server's sources along.
155
- const sourceDiagnostics = (program: ts.Program) =>
194
+ const sourceDiagnostics = (
195
+ program: ts.Program,
196
+ files: ReadonlySet<ts.SourceFile>,
197
+ ) =>
156
198
  [
157
199
  ...program.getConfigFileParsingDiagnostics(),
158
200
  ...program.getOptionsDiagnostics(),
159
201
  ...program.getGlobalDiagnostics(),
160
- ...[...plcFiles(program)].flatMap((file) => [
202
+ ...[...files].flatMap((file) => [
161
203
  ...program.getSyntacticDiagnostics(file),
162
204
  ...program.getSemanticDiagnostics(file),
163
205
  ]),
164
- ].map((diagnostic) => tsDiagnostic(diagnostic, positions.span));
165
- const diagnostics = sourceDiagnostics(program);
206
+ ]
207
+ .filter(
208
+ (diagnostic) => !storesGeneratedGlobal(program, diagnostic, generated),
209
+ )
210
+ .map((diagnostic) => tsDiagnostic(diagnostic, positions.span));
211
+ const files = plcFiles(program);
212
+ const diagnostics = sourceDiagnostics(program, files);
166
213
  if (
167
214
  program
168
215
  .getSyntacticDiagnostics()
169
- .some((item) => !item.file || plcFiles(program).has(item.file))
216
+ .some((item) => !item.file || files.has(item.file))
170
217
  ) {
171
218
  return { diagnostics };
172
219
  }
173
- const apply = (lowering: {
174
- sources: Map<string, Mapped>;
175
- diagnostics: Diagnostic[];
176
- }): boolean => {
220
+ if (dialect === "rejected") {
221
+ const uses = dialectUses(program, sdk, positions);
222
+ if (uses.length) {
223
+ return { diagnostics: [...diagnostics, ...uses] };
224
+ }
225
+ }
226
+ const lowerings = new LoweringPipeline(program, (program, lowering) => {
177
227
  diagnostics.push(...lowering.diagnostics);
178
228
  for (const source of runtimeSources(program)) {
179
229
  if (lowering.sources.has(source.fileName)) {
@@ -184,87 +234,177 @@ export function analyze(options: FrontendOptions): FrontendResult {
184
234
  lowering.diagnostics.length ||
185
235
  (lowering.sources.size && hasErrors(diagnostics))
186
236
  ) {
187
- return false;
237
+ return undefined;
238
+ }
239
+ if (!lowering.sources.size) {
240
+ return program;
241
+ }
242
+ positions.record(lowering.sources, program);
243
+ for (const [path, text] of lowering.sources) {
244
+ virtualSources.set(path, text.text);
188
245
  }
189
- if (lowering.sources.size) {
190
- positions.record(lowering.sources, program);
246
+ if (debug.lowered) {
191
247
  for (const [path, text] of lowering.sources) {
192
- virtualSources.set(path, text.text);
248
+ const target = join(debug.lowered, relative(root, path));
249
+ mkdirSync(dirname(target), { recursive: true });
250
+ writeFileSync(target, text.text);
193
251
  }
194
- if (debug.lowered) {
195
- for (const [path, text] of lowering.sources) {
196
- const target = join(debug.lowered, relative(dirname(filename), path));
197
- mkdirSync(dirname(target), { recursive: true });
198
- writeFileSync(target, text.text);
199
- }
200
- }
201
- program = ts.createProgram({
202
- rootNames,
203
- options: compilerOptions,
204
- host,
205
- oldProgram: program,
206
- });
207
- diagnostics.push(...sourceDiagnostics(program));
208
252
  }
209
- return true;
210
- };
211
- const elaboration = lowerElaboration(
212
- program,
213
- sdk,
214
- options.programs,
215
- dirname(filename),
216
- positions,
217
- debug,
253
+ const lowered = ts.createProgram({
254
+ rootNames,
255
+ options: compilerOptions,
256
+ host,
257
+ oldProgram: program,
258
+ });
259
+ diagnostics.push(...sourceDiagnostics(lowered, plcFiles(lowered)));
260
+ return lowered;
261
+ });
262
+ // A plain program's setup reads the configuration this resolves. The pass runs again below for
263
+ // the reads that the services pass generates.
264
+ const configuration = lowerings.run((program) =>
265
+ lowerEnvironment(program, sdk, positions, environment),
218
266
  );
219
- if (!apply(elaboration)) {
220
- return { diagnostics };
221
- }
222
- if (!apply(lowerControlFlow(program))) {
223
- return { diagnostics };
224
- }
225
- const services = lowerServices(program, sdk, positions, options.services);
226
- if (!apply(services)) {
227
- return { diagnostics };
228
- }
229
- const exposure = lowerExposure(program, sdk, positions);
230
- if (!apply(exposure)) {
231
- return { diagnostics };
232
- }
233
- if (!apply(lowerEnvironment(program, sdk, positions, environment))) {
234
- return { diagnostics };
235
- }
236
- if (!apply(lowerConstFunctions(program, positions))) {
237
- return { diagnostics };
238
- }
239
- const promises = lowerPromises(program, sdk, positions, dirname(filename));
240
- if (!apply(promises)) {
241
- return { diagnostics };
242
- }
243
- const lowering = lowerAsync(program, sdk, positions, dirname(filename));
244
- for (const [key, value] of promises.runtimeBlocks) {
245
- lowering.blocks.set(key, value);
246
- }
247
- if (!apply(lowering)) {
267
+ const elaboration =
268
+ configuration &&
269
+ lowerings.run((program) =>
270
+ lowerElaboration(program, sdk, options.programs, root, positions, {
271
+ debug,
272
+ configuration: configuration.read,
273
+ always: dialect === "rejected",
274
+ io: options.io,
275
+ }),
276
+ );
277
+ lowerings.run(lowerControlFlow);
278
+ const services = lowerings.run((program) =>
279
+ lowerServices(program, sdk, positions, options.services),
280
+ );
281
+ lowerings.run((program) =>
282
+ lowerEnvironment(program, sdk, positions, environment),
283
+ );
284
+ lowerings.run((program) => lowerConstFunctions(program, positions));
285
+ const promises = lowerings.run((program) =>
286
+ lowerPromises(program, sdk, positions, root),
287
+ );
288
+ const lowering = lowerings.run((program) =>
289
+ lowerAsync(program, sdk, positions, root),
290
+ );
291
+ const lowered = lowerings.program;
292
+ if (!lowered || !elaboration || !services || !promises || !lowering) {
248
293
  return { diagnostics };
249
294
  }
250
295
  const analyzer = new Analyzer(
251
- program,
296
+ lowered,
252
297
  host,
253
- dirname(filename),
298
+ root,
254
299
  sdk,
255
300
  diagnostics,
256
301
  positions,
257
- serviceRecords(program, services),
302
+ serviceRecords(lowered, services),
258
303
  );
259
304
  const module = analyzer.run({ ...options.programs, ...lowering.programs });
260
- attachLowerings(module, dirname(filename), {
261
- elaboration,
262
- exposure,
263
- lowering,
264
- });
305
+ attachLowerings(module, root, { elaboration, promises, lowering });
265
306
  return hasErrors(diagnostics) ? { diagnostics } : { module, diagnostics };
266
307
  }
267
308
 
309
+ /**
310
+ * Whether a diagnostic is TypeScript refusing a lowered module's write to a global of a module
311
+ * elaboration generated, through its namespace import. A namespace import is read-only in
312
+ * TypeScript, but each generated module is a global variable list, and the PLC assigns its
313
+ * variables from any program.
314
+ */
315
+ function storesGeneratedGlobal(
316
+ program: ts.Program,
317
+ diagnostic: ts.Diagnostic,
318
+ generated: (file: ts.SourceFile) => boolean,
319
+ ): boolean {
320
+ const { file, start, length } = diagnostic;
321
+ if (
322
+ diagnostic.code !== readOnlyAssignment ||
323
+ !file ||
324
+ start === undefined ||
325
+ length === undefined
326
+ ) {
327
+ return false;
328
+ }
329
+ const target = reportedAccess(file, start, start + length);
330
+ if (!target || !ts.isIdentifier(target.expression)) {
331
+ return false;
332
+ }
333
+ const checker = program.getTypeChecker();
334
+ const namespace = checker
335
+ .getSymbolAtLocation(target.expression)
336
+ ?.declarations?.find(ts.isNamespaceImport);
337
+ const source =
338
+ namespace &&
339
+ checker.getSymbolAtLocation(namespace.parent.parent.moduleSpecifier)
340
+ ?.valueDeclaration;
341
+ return Boolean(source && ts.isSourceFile(source) && generated(source));
342
+ }
343
+
344
+ /** TS2540: "Cannot assign to '…' because it is a read-only property." */
345
+ const readOnlyAssignment = 2540;
346
+
347
+ /** The property access whose name a diagnostic spans from `start` to `end`, if it spans one. */
348
+ function reportedAccess(
349
+ file: ts.SourceFile,
350
+ start: number,
351
+ end: number,
352
+ ): ts.PropertyAccessExpression | undefined {
353
+ const visit = (node: ts.Node): ts.PropertyAccessExpression | undefined => {
354
+ if (
355
+ ts.isPropertyAccessExpression(node) &&
356
+ node.name.getStart(file) === start &&
357
+ node.name.end === end
358
+ ) {
359
+ return node;
360
+ }
361
+ return node.pos <= start && end <= node.end
362
+ ? ts.forEachChild(node, visit)
363
+ : undefined;
364
+ };
365
+ return ts.forEachChild(file, visit);
366
+ }
367
+
368
+ /** What every lowering pass returns: the modules it rewrote or generated, and what it rejected. */
369
+ interface Lowering {
370
+ sources: ReadonlyMap<string, Mapped>;
371
+ diagnostics: readonly Diagnostic[];
372
+ }
373
+
374
+ /**
375
+ * Runs the lowering passes in order, each over the program the one before it produced. `next`
376
+ * takes a pass's result to the program the following pass reads, or to undefined when the pass
377
+ * failed; the passes after a failure do not run.
378
+ */
379
+ class LoweringPipeline {
380
+ private current: ts.Program | undefined;
381
+
382
+ constructor(
383
+ program: ts.Program,
384
+ private readonly next: (
385
+ program: ts.Program,
386
+ lowering: Lowering,
387
+ ) => ts.Program | undefined,
388
+ ) {
389
+ this.current = program;
390
+ }
391
+
392
+ /** The program the passes produced; undefined once one has failed. */
393
+ get program(): ts.Program | undefined {
394
+ return this.current;
395
+ }
396
+
397
+ /** The result of `pass` over the current program; undefined when it or an earlier pass failed. */
398
+ run<T extends Lowering>(pass: (program: ts.Program) => T): T | undefined {
399
+ if (!this.current) {
400
+ return undefined;
401
+ }
402
+ const lowering = pass(this.current);
403
+ this.current = this.next(this.current, lowering);
404
+ return this.current && lowering;
405
+ }
406
+ }
407
+
268
408
  /**
269
409
  * The compiler host of every lowering pass: lowered and generated modules are read from
270
410
  * `virtualSources`, and everything else from disk. Each pass builds a new program, so the host
@@ -311,7 +451,7 @@ function loweringHost(
311
451
  }
312
452
 
313
453
  /**
314
- * The lowerings record what they generated by `<file>:<name>`. The analyzed model's
454
+ * The lowerings record what they generated by lowering key. The analyzed model's
315
455
  * spans point at the user's files, but its ids still start with the lowered module
316
456
  * each item was declared in, so the records are matched back by id.
317
457
  */
@@ -320,37 +460,23 @@ function attachLowerings(
320
460
  root: string,
321
461
  {
322
462
  elaboration,
323
- exposure,
463
+ promises,
324
464
  lowering,
325
465
  }: {
326
466
  elaboration: ReturnType<typeof lowerElaboration>;
327
- exposure: ReturnType<typeof lowerExposure>;
467
+ promises: ReturnType<typeof lowerPromises>;
328
468
  lowering: AsyncLowering;
329
469
  },
330
470
  ): void {
331
- const declared = (item: { id: string; name: string }) =>
332
- `${resolve(root, item.id.slice(0, item.id.indexOf(":")))}:${item.name}`;
333
- for (const variable of module.variables) {
334
- const item = exposure.variables.get(declared(variable));
335
- if (item) {
336
- variable.exposure = item;
337
- }
338
- }
339
471
  for (const fn of module.functions) {
340
- const origin = elaboration.origins.get(declared(fn));
472
+ const origin = elaboration.origins.get(declarationKey(root, fn));
341
473
  if (origin) {
342
474
  fn.origin = origin;
343
475
  }
344
476
  }
345
477
  module.types = module.types.map((type) => {
346
478
  const literals =
347
- type.kind === "enum" &&
348
- elaboration.literals.get(
349
- declared({
350
- id: type.id,
351
- name: type.id.slice(type.id.lastIndexOf(":") + 1),
352
- }),
353
- );
479
+ type.kind === "enum" && elaboration.literals.get(typeKey(root, type.id));
354
480
  return type.kind === "enum" && literals
355
481
  ? {
356
482
  ...type,
@@ -362,12 +488,13 @@ function attachLowerings(
362
488
  : type;
363
489
  });
364
490
  for (const block of module.blocks) {
365
- const runtime = lowering.blocks.get(declared(block));
491
+ const key = declarationKey(root, block);
492
+ const runtime = promises.runtimeBlocks.get(key) ?? lowering.blocks.get(key);
366
493
  if (runtime) {
367
494
  block.runtime = runtime;
368
495
  }
369
- const job = lowering.jobs.get(declared(block));
370
- const origin = elaboration.origins.get(declared(block));
496
+ const job = lowering.jobs.get(key);
497
+ const origin = elaboration.origins.get(key);
371
498
  if (job) {
372
499
  block.job = origin ? { ...job, ...origin } : job;
373
500
  }
@@ -406,5 +533,5 @@ export function checkHostConfig(file: string): readonly Diagnostic[] {
406
533
  });
407
534
  return ts
408
535
  .getPreEmitDiagnostics(program)
409
- .map((diagnostic) => tsDiagnostic(diagnostic));
536
+ .map((diagnostic) => tsDiagnostic(diagnostic, sourceSpan));
410
537
  }
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
+ export type { Environment as CompileEnvironment } from "@tsplc/config";
1
2
  export {
2
3
  analyze,
3
- type CompileEnvironment,
4
+ type BoundPath,
4
5
  checkHostConfig,
5
6
  type FrontendOptions,
6
7
  type FrontendResult,