@tsplc/tmp-compiler 0.0.0-stage → 0.6.3

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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6563 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16198 -0
  12. package/dist/index.js.map +62 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1090 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,779 @@
1
+ import { resolve } from "node:path";
2
+ import {
3
+ aggregate,
4
+ type Diagnostic,
5
+ error,
6
+ type PlcFunction,
7
+ type PlcModule,
8
+ type PlcProgram,
9
+ type Variable,
10
+ } from "@tsplc/compiler/ir";
11
+ import ts from "typescript";
12
+ import { BlockResolver, storageInitializer } from "./blocks";
13
+ import type { Uncompiled } from "./elaborate/reduce";
14
+ import {
15
+ type AnalysisContext,
16
+ ExpressionLowering,
17
+ type LoweringScope,
18
+ } from "./expressions";
19
+ import { runtimeImport, runtimeSources } from "./module-graph";
20
+ import type { Positions } from "./positions";
21
+ import { methodAccess, RoutineTable } from "./routines";
22
+ import { inSdk, unaliased } from "./sdk";
23
+ import { StatementLowering } from "./statements";
24
+ import {
25
+ type Fail,
26
+ hasModifier,
27
+ inferredStorageType,
28
+ type ResolvedType,
29
+ SemanticError,
30
+ type ServiceRecord,
31
+ TypeResolver,
32
+ } from "./types";
33
+ import type { FrontendOptions } from "./typescript";
34
+
35
+ /** What a module variable's initializer and keyword establish about its storage. */
36
+ interface StorageFacts {
37
+ instance: string | undefined;
38
+ table: ResolvedType | undefined;
39
+ immutable: boolean;
40
+ initializer: ts.Expression | undefined;
41
+ }
42
+
43
+ export const suppressionDiagnostics = (
44
+ source: ts.SourceFile,
45
+ positions: Positions,
46
+ ): Diagnostic[] => {
47
+ const diagnostics: Diagnostic[] = [];
48
+ const scanner = ts.createScanner(
49
+ ts.ScriptTarget.Latest,
50
+ false,
51
+ ts.LanguageVariant.Standard,
52
+ source.text,
53
+ );
54
+ for (
55
+ let token = scanner.scan();
56
+ token !== ts.SyntaxKind.EndOfFileToken;
57
+ token = scanner.scan()
58
+ ) {
59
+ if (
60
+ token !== ts.SyntaxKind.SingleLineCommentTrivia &&
61
+ token !== ts.SyntaxKind.MultiLineCommentTrivia
62
+ ) {
63
+ continue;
64
+ }
65
+ const match =
66
+ /(?<=(?:^|\n)\s*(?:\/\/+|\/\*+|\*)\s*)@ts-(?:nocheck|ignore|expect-error)\b/.exec(
67
+ scanner.getTokenText(),
68
+ );
69
+ if (!match) {
70
+ continue;
71
+ }
72
+ const start = scanner.getTokenPos() + match.index;
73
+ diagnostics.push(
74
+ error(
75
+ "PLC1009",
76
+ "TypeScript diagnostic suppression is not allowed in PLC source.",
77
+ positions.span(source, start, start + match[0].length),
78
+ ),
79
+ );
80
+ }
81
+ return diagnostics;
82
+ };
83
+
84
+ export class Analyzer {
85
+ private readonly checker: ts.TypeChecker;
86
+ private readonly resolver: TypeResolver;
87
+ private readonly routines: RoutineTable;
88
+ private readonly blocks: BlockResolver;
89
+ private readonly globalVariables: Variable[] = [];
90
+ private readonly sources: readonly ts.SourceFile[];
91
+ private readonly context: AnalysisContext;
92
+ /** Lowers module and block initializers, which run before any routine. */
93
+ private readonly moduleScope: ExpressionLowering;
94
+
95
+ constructor(
96
+ private readonly program: ts.Program,
97
+ private readonly host: ts.ModuleResolutionHost,
98
+ private readonly root: string,
99
+ private readonly sdk: string,
100
+ private readonly diagnostics: Diagnostic[],
101
+ private readonly positions: Positions,
102
+ serviceRecord: ServiceRecord | null,
103
+ /** What of each module elaboration rewrote is PLC code, where that is not all of it. */
104
+ private readonly reduced: ReadonlyMap<string, Uncompiled>,
105
+ ) {
106
+ this.checker = program.getTypeChecker();
107
+ this.resolver = new TypeResolver(
108
+ this.checker,
109
+ root,
110
+ sdk,
111
+ this.fail,
112
+ serviceRecord,
113
+ );
114
+ this.routines = new RoutineTable(
115
+ this.checker,
116
+ this.resolver,
117
+ positions,
118
+ this.fail,
119
+ );
120
+ const sdkSource = program.getSourceFile(sdk);
121
+ if (!sdkSource) {
122
+ throw new Error(`The program does not include the SDK ${sdk}.`);
123
+ }
124
+ this.blocks = new BlockResolver(
125
+ this.resolver,
126
+ positions.node,
127
+ this.fail,
128
+ positions.node(sdkSource),
129
+ );
130
+ this.context = {
131
+ checker: this.checker,
132
+ resolver: this.resolver,
133
+ blocks: this.blocks,
134
+ routines: this.routines,
135
+ positions,
136
+ fail: this.fail,
137
+ };
138
+ this.moduleScope = new ExpressionLowering(this.context, {
139
+ fn: undefined,
140
+ block: undefined,
141
+ environment: new Map(),
142
+ variables: new Map(),
143
+ });
144
+ const roots = new Set(program.getRootFileNames());
145
+ this.sources = runtimeSources(program).filter(
146
+ (source) =>
147
+ source.fileName !== sdk &&
148
+ !inSdk(sdk, source.fileName) &&
149
+ !program.isSourceFileDefaultLibrary(source) &&
150
+ (!source.isDeclarationFile || roots.has(source.fileName)),
151
+ );
152
+ }
153
+
154
+ private readonly fail: Fail = (node, code, message) => {
155
+ throw new SemanticError(error(code, message, this.positions.node(node)));
156
+ };
157
+
158
+ /** Runs `action`, reporting the diagnostic it fails with unless an earlier action reported it. */
159
+ private guard(action: () => void): void {
160
+ try {
161
+ action();
162
+ } catch (cause) {
163
+ if (!(cause instanceof SemanticError)) {
164
+ throw cause;
165
+ }
166
+ if (!this.diagnostics.includes(cause.diagnostic)) {
167
+ this.diagnostics.push(cause.diagnostic);
168
+ }
169
+ }
170
+ }
171
+
172
+ run(entries: FrontendOptions["programs"]): PlcModule {
173
+ // Collect every declaration before resolving initializers and routine bodies.
174
+ // Generic calls can enqueue more helpers, so resolve entry points last.
175
+ this.collectDeclarations();
176
+ this.initializeStorage();
177
+ this.analyzeBlockBodies();
178
+ this.analyzePendingFunctions();
179
+ const programs = this.resolvePrograms(entries);
180
+
181
+ return {
182
+ types: [...this.resolver.types.values()],
183
+ variables: this.globalVariables,
184
+ functions: [...this.routines.instances.values()],
185
+ blocks: [...this.blocks.definitions.values()],
186
+ programs,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * A module's statements that are PLC code. A module elaboration cut down is there for
192
+ * TypeScript, but for the constants a module of constants reads; the entry module it wrote also
193
+ * declares, for other modules to import, names that are no code of its own.
194
+ */
195
+ private statements(source: ts.SourceFile): readonly ts.Statement[] {
196
+ const part = this.reduced.get(source.fileName);
197
+ if (!part) {
198
+ return source.statements;
199
+ }
200
+ const names = (statement: ts.Statement): string[] => {
201
+ if (ts.isVariableStatement(statement)) {
202
+ return statement.declarationList.declarations.map((declaration) =>
203
+ declaration.name.getText(),
204
+ );
205
+ }
206
+ return ts.isEnumDeclaration(statement) ? [statement.name.text] : [];
207
+ };
208
+ return source.statements.filter((statement) =>
209
+ "compiled" in part
210
+ ? ts.isVariableStatement(statement) &&
211
+ names(statement).some((name) => part.compiled.has(name))
212
+ : !names(statement).some((name) => part.declared.has(name)),
213
+ );
214
+ }
215
+
216
+ private collectDeclarations(): void {
217
+ const classes = this.sources.flatMap((source) =>
218
+ this.statements(source).filter(ts.isClassDeclaration),
219
+ );
220
+ this.blocks.index(classes);
221
+ for (const node of classes) {
222
+ this.guard(() => this.blocks.collect(node));
223
+ }
224
+ for (const source of this.blocks.sources.values()) {
225
+ for (const method of source.methods) {
226
+ this.guard(() =>
227
+ this.routines.declareMethod(
228
+ this.resolver.symbol(method.name),
229
+ method,
230
+ { block: source.block.id, access: methodAccess(method) },
231
+ ),
232
+ );
233
+ }
234
+ }
235
+ for (const source of this.sources) {
236
+ this.diagnostics.push(...suppressionDiagnostics(source, this.positions));
237
+ for (const statement of this.statements(source)) {
238
+ this.guard(() => this.declaration(statement));
239
+ }
240
+ }
241
+ }
242
+
243
+ private initializeStorage(): void {
244
+ for (const source of this.sources) {
245
+ for (const statement of this.statements(source)) {
246
+ if (ts.isVariableStatement(statement) && !source.isDeclarationFile) {
247
+ this.guard(() => {
248
+ for (const declaration of statement.declarationList.declarations) {
249
+ if (!declaration.initializer) {
250
+ this.fail(
251
+ declaration,
252
+ "PLC3001",
253
+ "Persistent PLC state requires a constant initializer.",
254
+ );
255
+ }
256
+ const variable = this.moduleScope
257
+ .bySymbol()
258
+ .get(this.resolver.symbol(declaration.name));
259
+ if (!variable || variable.storage === "instance") {
260
+ continue;
261
+ }
262
+ const initializer = storageInitializer(
263
+ declaration.initializer,
264
+ this.resolver,
265
+ this.fail,
266
+ ).value;
267
+ const inferred = variable.type === "inferred";
268
+ const expression = this.moduleScope.expression(
269
+ initializer,
270
+ inferred ? undefined : variable.type,
271
+ );
272
+ variable.type = expression.type;
273
+ if (
274
+ inferred &&
275
+ variable.storage === "constant" &&
276
+ aggregate(this.resolver.types.get(variable.type))
277
+ ) {
278
+ variable.storage = "module";
279
+ }
280
+ if (
281
+ variable.retention !== "none" &&
282
+ variable.storage === "constant"
283
+ ) {
284
+ this.fail(
285
+ declaration,
286
+ "PLC3004",
287
+ `${variable.retention} requires mutable persistent storage or a static block instance.`,
288
+ );
289
+ }
290
+ const value = this.moduleScope.constant(
291
+ this.moduleScope.implicitCopy(expression),
292
+ );
293
+ if (!value) {
294
+ this.fail(
295
+ declaration.initializer,
296
+ "PLC3001",
297
+ "Persistent initializers must be compile-time constants.",
298
+ );
299
+ }
300
+ variable.initial = value;
301
+ }
302
+ });
303
+ }
304
+ }
305
+ }
306
+ }
307
+
308
+ private analyzeBlockBodies(): void {
309
+ for (const source of this.blocks.sources.values()) {
310
+ this.guard(() => {
311
+ for (const [variable, node] of source.initializers) {
312
+ const value = this.moduleScope.constant(
313
+ this.moduleScope.expression(node, variable.type),
314
+ );
315
+ if (!value) {
316
+ this.fail(
317
+ node,
318
+ "PLC3001",
319
+ "Block state requires a compile-time constant initializer.",
320
+ );
321
+ }
322
+ variable.initial = value;
323
+ }
324
+ const { block } = source;
325
+ const routine = this.routineBody(
326
+ {
327
+ id: block.id,
328
+ name: block.name,
329
+ parameters: block.inputs,
330
+ locals: [],
331
+ body: [],
332
+ span: block.span,
333
+ ...(block.result && { result: block.result }),
334
+ },
335
+ source.fieldBindings,
336
+ source.body,
337
+ { block: source, environment: new Map() },
338
+ );
339
+ block.locals = routine.locals;
340
+ block.body = routine.body;
341
+ });
342
+ }
343
+ }
344
+
345
+ private analyzePendingFunctions(): void {
346
+ // A worklist allows explicit generic instances to share source without sharing locals.
347
+ // Lowering a body can append instances, which this loop then reaches.
348
+ for (const instance of this.routines.pending) {
349
+ this.guard(() => {
350
+ const block = instance.fn.owner
351
+ ? [...this.blocks.sources.values()].find(
352
+ (source) => source.block.id === instance.fn.owner?.block,
353
+ )
354
+ : undefined;
355
+ const fn = this.routineBody(
356
+ instance.fn,
357
+ [...(block?.fieldBindings ?? []), ...instance.parameters],
358
+ instance.body,
359
+ { block, environment: instance.environment },
360
+ );
361
+ this.routines.complete(instance, fn);
362
+ });
363
+ }
364
+ }
365
+
366
+ private routineBody(
367
+ fn: PlcFunction,
368
+ bindings: Iterable<readonly [ts.Symbol, Variable]>,
369
+ body: ts.Block,
370
+ scope: Pick<LoweringScope, "block" | "environment">,
371
+ ): PlcFunction {
372
+ const expressions = new ExpressionLowering(this.context, {
373
+ ...scope,
374
+ fn,
375
+ variables: this.moduleScope.bySymbol(),
376
+ });
377
+ for (const [symbol, variable] of bindings) {
378
+ expressions.bind(symbol, variable);
379
+ }
380
+ const statements = new StatementLowering(this.context, expressions, fn);
381
+ return { ...fn, ...statements.lowerRoutine(body) };
382
+ }
383
+
384
+ private resolvePrograms(entries: FrontendOptions["programs"]): PlcProgram[] {
385
+ const programs: PlcProgram[] = [];
386
+ for (const [name, entry] of Object.entries(entries)) {
387
+ const source = this.program.getSourceFile(
388
+ resolve(this.root, entry.module),
389
+ );
390
+ if (!source) {
391
+ this.diagnostics.push(
392
+ error("PLC4001", `Program source not found: ${entry.module}.`),
393
+ );
394
+ continue;
395
+ }
396
+ this.guard(() => {
397
+ const moduleSymbol = this.checker.getSymbolAtLocation(source);
398
+ const exported =
399
+ moduleSymbol &&
400
+ this.checker
401
+ .getExportsOfModule(moduleSymbol)
402
+ .find((symbol) => symbol.name === entry.export);
403
+ if (!exported) {
404
+ this.fail(
405
+ source,
406
+ "PLC4001",
407
+ `Program export ${entry.export} was not found.`,
408
+ );
409
+ }
410
+ const fn = this.routines.functions.get(
411
+ unaliased(this.checker, exported),
412
+ );
413
+ if (!fn || fn.parameters.length || fn.result) {
414
+ this.fail(
415
+ source,
416
+ "PLC4001",
417
+ "Program entry must be an implemented parameterless void function.",
418
+ );
419
+ }
420
+ programs.push({ id: `program:${name}`, name, entry: fn.id });
421
+ });
422
+ }
423
+ return programs;
424
+ }
425
+
426
+ private dependency(node: ts.ImportDeclaration | ts.ExportDeclaration): void {
427
+ if (!node.moduleSpecifier) {
428
+ return;
429
+ }
430
+ if (!ts.isStringLiteral(node.moduleSpecifier)) {
431
+ this.fail(node, "PLC1001", "Only static module imports are supported.");
432
+ }
433
+ const resolved = ts.resolveModuleName(
434
+ node.moduleSpecifier.text,
435
+ node.getSourceFile().fileName,
436
+ this.program.getCompilerOptions(),
437
+ this.host,
438
+ ).resolvedModule;
439
+ if (!resolved) {
440
+ this.fail(
441
+ node.moduleSpecifier,
442
+ "PLC1008",
443
+ "This dependency could not be resolved to PLC source.",
444
+ );
445
+ }
446
+ if (!runtimeImport(node, this.checker)) {
447
+ return;
448
+ }
449
+ const source = this.program.getSourceFile(resolved.resolvedFileName);
450
+ if (source && !source.isDeclarationFile) {
451
+ return;
452
+ }
453
+ if (inSdk(this.sdk, resolved.resolvedFileName)) {
454
+ return;
455
+ }
456
+ const authoredIo =
457
+ source &&
458
+ this.sources.includes(source) &&
459
+ source.statements.some(ts.isVariableStatement) &&
460
+ source.statements.every(
461
+ (statement) =>
462
+ ts.isTypeAliasDeclaration(statement) ||
463
+ ts.isEmptyStatement(statement) ||
464
+ (ts.isVariableStatement(statement) &&
465
+ statement.declarationList.declarations.every(
466
+ (declaration) =>
467
+ declaration.type && this.resolver.resolve(declaration.type).io,
468
+ )),
469
+ );
470
+ if (authoredIo) {
471
+ return;
472
+ }
473
+ this.fail(
474
+ node.moduleSpecifier,
475
+ "PLC1008",
476
+ "Runtime dependencies need PLC TypeScript implementation source; JavaScript and declaration-only value imports are unsupported.",
477
+ );
478
+ }
479
+
480
+ private declaration(statement: ts.Statement): void {
481
+ if (
482
+ ts.isImportDeclaration(statement) ||
483
+ ts.isExportDeclaration(statement)
484
+ ) {
485
+ this.dependency(statement);
486
+ return;
487
+ }
488
+ if (
489
+ ts.isClassDeclaration(statement) ||
490
+ ts.isTypeAliasDeclaration(statement) ||
491
+ ts.isInterfaceDeclaration(statement) ||
492
+ ts.isEmptyStatement(statement)
493
+ ) {
494
+ return;
495
+ }
496
+ if (ts.isEnumDeclaration(statement)) {
497
+ this.resolver.enumeration(statement);
498
+ return;
499
+ }
500
+ if (ts.isVariableStatement(statement)) {
501
+ this.moduleVariables(statement);
502
+ return;
503
+ }
504
+ if (ts.isFunctionDeclaration(statement)) {
505
+ if (!statement.name || !statement.body) {
506
+ this.fail(
507
+ statement,
508
+ "PLC1001",
509
+ "PLC functions need a name and an implementation.",
510
+ );
511
+ }
512
+ if (hasModifier(statement, ts.SyntaxKind.AsyncKeyword)) {
513
+ this.fail(
514
+ statement,
515
+ "PLC1007",
516
+ "Async execution is not supported in PLC scan code.",
517
+ );
518
+ }
519
+ if (statement.asteriskToken) {
520
+ this.fail(
521
+ statement,
522
+ "PLC1007",
523
+ "Generators are not supported in PLC scan code.",
524
+ );
525
+ }
526
+ this.routines.declareFunction(
527
+ this.resolver.symbol(statement.name),
528
+ statement,
529
+ );
530
+ return;
531
+ }
532
+ this.fail(
533
+ statement,
534
+ "PLC1001",
535
+ `${ts.SyntaxKind[statement.kind]} is not supported in PLC source.`,
536
+ );
537
+ }
538
+
539
+ private moduleVariables(statement: ts.VariableStatement): void {
540
+ if (
541
+ !(
542
+ statement.declarationList.flags &
543
+ (ts.NodeFlags.Let | ts.NodeFlags.Const)
544
+ )
545
+ ) {
546
+ this.fail(statement, "PLC1001", "Use let or const instead of var.");
547
+ }
548
+ const immutable = Boolean(
549
+ statement.declarationList.flags & ts.NodeFlags.Const,
550
+ );
551
+ for (const declaration of statement.declarationList.declarations) {
552
+ if (!ts.isIdentifier(declaration.name)) {
553
+ this.fail(
554
+ declaration.name,
555
+ "PLC1001",
556
+ "Destructuring declarations are not supported.",
557
+ );
558
+ }
559
+ const initializer =
560
+ declaration.initializer &&
561
+ storageInitializer(declaration.initializer, this.resolver, this.fail);
562
+ const table =
563
+ initializer && this.tableType(declaration, initializer.value);
564
+ const instance =
565
+ initializer &&
566
+ this.allocatedBlock(declaration, initializer.value, table);
567
+ if (table && !immutable) {
568
+ this.fail(
569
+ declaration,
570
+ "PLC2001",
571
+ "A readonly table is a const declaration.",
572
+ );
573
+ }
574
+ const type = this.storageType(declaration, {
575
+ instance,
576
+ table,
577
+ immutable,
578
+ initializer: initializer?.value,
579
+ });
580
+ const ambient = declaration.getSourceFile().isDeclarationFile;
581
+ if (type.mode || this.resolver.hasReferences(type.type)) {
582
+ this.fail(
583
+ declaration,
584
+ "PLC2001",
585
+ "Borrow schemas cannot be stored as values.",
586
+ );
587
+ }
588
+ if (this.resolver.types.get(type.type)?.kind === "block" && !instance) {
589
+ this.fail(
590
+ declaration,
591
+ "PLC1007",
592
+ "Block instances require a static constructor initializer.",
593
+ );
594
+ }
595
+ if (
596
+ instance &&
597
+ (!immutable ||
598
+ (declaration.type &&
599
+ this.resolver.resolve(declaration.type).type !== instance))
600
+ ) {
601
+ this.fail(
602
+ declaration,
603
+ "PLC2001",
604
+ "Static block instances require const bindings and matching annotations.",
605
+ );
606
+ }
607
+ const retention = initializer?.retention ?? "none";
608
+ if (
609
+ retention !== "none" &&
610
+ (ambient ||
611
+ (immutable &&
612
+ type.type !== "inferred" &&
613
+ !instance &&
614
+ !aggregate(this.resolver.types.get(type.type))))
615
+ ) {
616
+ this.fail(
617
+ declaration,
618
+ "PLC3004",
619
+ `${retention} requires mutable persistent storage or a static block instance.`,
620
+ );
621
+ }
622
+ if (ambient && !type.io) {
623
+ this.fail(
624
+ declaration,
625
+ "PLC4002",
626
+ "Ambient PLC variables must declare Input or Output.",
627
+ );
628
+ }
629
+ if (!ambient && type.io) {
630
+ this.fail(
631
+ declaration,
632
+ "PLC4002",
633
+ "Logical I/O belongs in an ambient declaration file.",
634
+ );
635
+ }
636
+ if (type.io === "input" && !immutable) {
637
+ this.fail(declaration, "PLC4002", "Inputs must use declare const.");
638
+ }
639
+ if (type.io === "output" && immutable) {
640
+ this.fail(declaration, "PLC4002", "Outputs must use declare let.");
641
+ }
642
+ const variable: Variable = {
643
+ id: this.resolver.id(declaration, declaration.name.text),
644
+ name: declaration.name.text,
645
+ type: type.type,
646
+ storage: this.storageClass(type, { instance, table, immutable }),
647
+ mutable: !immutable,
648
+ retention,
649
+ ...(hasModifier(statement, ts.SyntaxKind.ExportKeyword) && {
650
+ exported: true as const,
651
+ }),
652
+ span: this.positions.node(declaration),
653
+ };
654
+ this.moduleScope.bind(this.resolver.symbol(declaration.name), variable);
655
+ this.globalVariables.push(variable);
656
+ }
657
+ }
658
+
659
+ /** The block a static instance or instance-array initializer allocates. */
660
+ private allocatedBlock(
661
+ declaration: ts.VariableDeclaration,
662
+ initializer: ts.Expression,
663
+ table: ResolvedType | undefined,
664
+ ): string | undefined {
665
+ if (ts.isNewExpression(initializer)) {
666
+ return this.blocks.instanceType(initializer);
667
+ }
668
+ return table
669
+ ? undefined
670
+ : this.blocks.instanceArrayType(declaration.type, initializer);
671
+ }
672
+
673
+ /** An unannotated const takes its initializer's type once initializers resolve. */
674
+ private storageType(
675
+ declaration: ts.VariableDeclaration,
676
+ { instance, table, immutable, initializer }: StorageFacts,
677
+ ): ResolvedType {
678
+ if (instance) {
679
+ return { type: instance };
680
+ }
681
+ if (table) {
682
+ return table;
683
+ }
684
+ if (declaration.type) {
685
+ return this.resolver.resolve(declaration.type);
686
+ }
687
+ if (immutable) {
688
+ return { type: "inferred" };
689
+ }
690
+ // Without an initializer, initializing storage reports the missing one.
691
+ if (!initializer) {
692
+ return { type: "BOOL" };
693
+ }
694
+ return {
695
+ type:
696
+ inferredStorageType(initializer) ??
697
+ this.fail(declaration, "PLC2001", "Annotate PLC storage explicitly."),
698
+ };
699
+ }
700
+
701
+ /** A const record or array keeps mutable fields, so only scalars and readonly tables are constants. */
702
+ private storageClass(
703
+ type: ResolvedType,
704
+ { instance, table, immutable }: Omit<StorageFacts, "initializer">,
705
+ ): Variable["storage"] {
706
+ if (instance) {
707
+ return "instance";
708
+ }
709
+ if (type.io) {
710
+ return type.io;
711
+ }
712
+ return immutable &&
713
+ (table || !aggregate(this.resolver.types.get(type.type)))
714
+ ? "constant"
715
+ : "module";
716
+ }
717
+
718
+ /**
719
+ * `const table: readonly T[] = [...]` or `const table = [...] as const satisfies readonly T[]`,
720
+ * also spelled `ReadonlyArray<T>`, is a constant `FixedArray<T, N>` whose length is the
721
+ * literal's element count.
722
+ */
723
+ private tableType(
724
+ declaration: ts.VariableDeclaration,
725
+ initializer: ts.Expression,
726
+ ): ResolvedType | undefined {
727
+ const satisfied = ts.isSatisfiesExpression(initializer)
728
+ ? initializer
729
+ : undefined;
730
+ const annotation = declaration.type ?? satisfied?.type;
731
+ if (!annotation) {
732
+ return undefined;
733
+ }
734
+ const element = this.readonlyElement(annotation);
735
+ if (!element) {
736
+ return undefined;
737
+ }
738
+ const literal = withoutConstAssertion(satisfied?.expression ?? initializer);
739
+ if (!ts.isArrayLiteralExpression(literal)) {
740
+ this.fail(
741
+ declaration,
742
+ "PLC2001",
743
+ "A readonly table is initialized by an array literal.",
744
+ );
745
+ }
746
+ return this.resolver.fixedArray(
747
+ annotation,
748
+ this.resolver.resolve(element),
749
+ { kind: "integer", value: literal.elements.length },
750
+ { kind: "integer", value: 0 },
751
+ );
752
+ }
753
+
754
+ /** The element type of `readonly T[]` or the standard `ReadonlyArray<T>`. */
755
+ private readonlyElement(annotation: ts.TypeNode): ts.TypeNode | undefined {
756
+ if (
757
+ ts.isTypeOperatorNode(annotation) &&
758
+ annotation.operator === ts.SyntaxKind.ReadonlyKeyword &&
759
+ ts.isArrayTypeNode(annotation.type)
760
+ ) {
761
+ return annotation.type.elementType;
762
+ }
763
+ if (
764
+ ts.isTypeReferenceNode(annotation) &&
765
+ annotation.typeName.getText() === "ReadonlyArray" &&
766
+ annotation.typeArguments?.length === 1 &&
767
+ this.resolver.standardLibrary(this.resolver.symbol(annotation.typeName))
768
+ ) {
769
+ return annotation.typeArguments[0];
770
+ }
771
+ return undefined;
772
+ }
773
+ }
774
+
775
+ const withoutConstAssertion = (node: ts.Expression): ts.Expression =>
776
+ ts.isParenthesizedExpression(node) ||
777
+ (ts.isAsExpression(node) && ts.isConstTypeReference(node.type))
778
+ ? withoutConstAssertion(node.expression)
779
+ : node;