@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) 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 +6558 -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 +16076 -0
  12. package/dist/index.js.map +61 -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 +1078 -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-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,578 @@
1
+ import {
2
+ defaultValue,
3
+ type FunctionBlock,
4
+ instancedBlock,
5
+ type Retention,
6
+ type SourceSpan,
7
+ type StandardBlock,
8
+ standardBlocks,
9
+ type Variable,
10
+ } from "@tsplc/compiler/ir";
11
+ import ts from "typescript";
12
+ import {
13
+ calleeName,
14
+ type Fail,
15
+ hasModifier,
16
+ inferredStorageType,
17
+ SemanticError,
18
+ type TypeResolver,
19
+ } from "./types";
20
+
21
+ export interface BlockSource {
22
+ block: FunctionBlock;
23
+ /** The block's layout. */
24
+ type: string;
25
+ /** The body of its `execute` method. */
26
+ body: ts.Block;
27
+ methods: readonly ts.MethodDeclaration[];
28
+ inputSymbol: ts.Symbol;
29
+ inputBindings: ReadonlyMap<string, Variable>;
30
+ fieldBindings: ReadonlyMap<ts.Symbol, Variable>;
31
+ initializers: ReadonlyMap<Variable, ts.Expression>;
32
+ }
33
+ /** The SDK call an initializer is wrapped in to keep its storage through restarts, and what it keeps. */
34
+ const retentionCalls: ReadonlyMap<string, Retention> = new Map([
35
+ ["persist", "persist"],
36
+ ["retain", "retain"],
37
+ ]);
38
+
39
+ export function storageInitializer(
40
+ node: ts.Expression,
41
+ types: TypeResolver,
42
+ fail: Fail,
43
+ ): { value: ts.Expression; retention: Retention } {
44
+ if (!ts.isCallExpression(node)) {
45
+ return { value: node, retention: "none" };
46
+ }
47
+ const callee = calleeName(node.expression);
48
+ const name = callee && types.sdkName(callee);
49
+ const retention = name && retentionCalls.get(name);
50
+ if (!name || !retention) {
51
+ return { value: node, retention: "none" };
52
+ }
53
+ const [value, ...rest] = node.arguments;
54
+ if (!value || rest.length || (node.typeArguments?.length ?? 0) > 1) {
55
+ fail(node, "PLC3004", `${name} requires one static storage initializer.`);
56
+ }
57
+ return { value, retention };
58
+ }
59
+
60
+ /** How deep block instances may nest inside one another's state. */
61
+ const maxInstanceNesting = 64;
62
+
63
+ const isStandardBlock = (name: string): name is StandardBlock =>
64
+ Object.hasOwn(standardBlocks, name);
65
+
66
+ export class BlockResolver {
67
+ readonly definitions = new Map<string, FunctionBlock>();
68
+ readonly sources = new Map<ts.Symbol, BlockSource>();
69
+ private readonly declarations = new Map<ts.Symbol, ts.ClassDeclaration>();
70
+ /** Classes whose collection failed, so another instance reports nothing new. */
71
+ private readonly failures = new Map<ts.Symbol, SemanticError>();
72
+ private readonly active = new Set<ts.Symbol>();
73
+ constructor(
74
+ private readonly types: TypeResolver,
75
+ private readonly origin: (node: ts.Node) => SourceSpan,
76
+ private readonly fail: Fail,
77
+ sdkSpan: SourceSpan,
78
+ ) {
79
+ for (const name of Object.keys(standardBlocks).filter(isStandardBlock)) {
80
+ const schema = standardBlocks[name];
81
+ const id = `stdlib:${name}`;
82
+ const output = `${id}:out`;
83
+ const variable = (
84
+ label: string,
85
+ type: string,
86
+ storage: Variable["storage"],
87
+ ): Variable => ({
88
+ id: `${id}:${label}`,
89
+ name: label,
90
+ type,
91
+ storage,
92
+ mutable: false,
93
+ retention: "none",
94
+ span: sdkSpan,
95
+ ...(storage === "blockOutput" && {
96
+ initial: defaultValue(type, types.types),
97
+ }),
98
+ });
99
+ const block: FunctionBlock = {
100
+ id,
101
+ name,
102
+ inputs: schema.inputs.map(([label, , type]) =>
103
+ variable(label, type, "parameter"),
104
+ ),
105
+ outputs: schema.outputs.map(([label, , type]) =>
106
+ variable(label, type, "blockOutput"),
107
+ ),
108
+ state: [],
109
+ locals: [],
110
+ body: [],
111
+ result: output,
112
+ standard: name,
113
+ span: sdkSpan,
114
+ };
115
+ this.definitions.set(id, block);
116
+ types.declareStandardBlock(name, id, {
117
+ id: output,
118
+ fields: block.outputs.map((field) => ({
119
+ name: field.name,
120
+ type: field.type,
121
+ readonly: true,
122
+ })),
123
+ });
124
+ }
125
+ }
126
+
127
+ /** Makes named classes allocatable; `collect` reports a class without a name. */
128
+ index(nodes: readonly ts.ClassDeclaration[]): void {
129
+ for (const node of nodes) {
130
+ if (node.name) {
131
+ this.declarations.set(this.types.symbol(node.name), node);
132
+ }
133
+ }
134
+ }
135
+
136
+ instanceType(node: ts.NewExpression): string {
137
+ const name = calleeName(node.expression);
138
+ if (node.arguments?.length || node.typeArguments?.length || !name) {
139
+ this.fail(
140
+ node,
141
+ "PLC1007",
142
+ "Block instances use a concrete zero-argument constructor at static storage declarations.",
143
+ );
144
+ }
145
+ const official = this.types.sdkName(name);
146
+ const standard = official && this.types.standardBlock(official);
147
+ if (standard) {
148
+ return standard;
149
+ }
150
+ const declaration = this.declarations.get(this.types.symbol(name));
151
+ if (!declaration) {
152
+ this.fail(
153
+ node,
154
+ "PLC1007",
155
+ "Only recognized static function block allocation is supported.",
156
+ );
157
+ }
158
+ return this.collect(declaration).type;
159
+ }
160
+
161
+ /**
162
+ * `FixedArray<Block, N>` storage allocated with `defaultValue`; its elements are static
163
+ * instances. The allocation names the type, so an annotation is optional but must agree.
164
+ */
165
+ instanceArrayType(
166
+ annotation: ts.TypeNode | undefined,
167
+ value: ts.Expression,
168
+ ): string | undefined {
169
+ const blockArray = (type: string) =>
170
+ this.types.types.get(type)?.kind === "array" &&
171
+ instancedBlock(type, this.types.types)
172
+ ? type
173
+ : undefined;
174
+ const declared = annotation && this.types.resolve(annotation).type;
175
+ if (declared && !blockArray(declared)) {
176
+ return undefined;
177
+ }
178
+ const callee = ts.isCallExpression(value) && calleeName(value.expression);
179
+ const allocated =
180
+ callee &&
181
+ this.types.sdkName(callee) === "defaultValue" &&
182
+ value.typeArguments?.length === 1
183
+ ? value.typeArguments[0]
184
+ : undefined;
185
+ const allocation = allocated && this.types.resolve(allocated).type;
186
+ if (!declared) {
187
+ return allocation && blockArray(allocation);
188
+ }
189
+ if (allocation !== declared) {
190
+ this.fail(
191
+ value,
192
+ "PLC1007",
193
+ "Block arrays allocate with defaultValue<FixedArray<Block, N>>() of their declared type.",
194
+ );
195
+ }
196
+ return declared;
197
+ }
198
+
199
+ collect(node: ts.ClassDeclaration): BlockSource {
200
+ if (!node.name) {
201
+ this.fail(node, "PLC1001", "Function block classes need names.");
202
+ }
203
+ const symbol = this.types.symbol(node.name);
204
+ const collected = this.sources.get(symbol);
205
+ if (collected) {
206
+ return collected;
207
+ }
208
+ const failure = this.failures.get(symbol);
209
+ if (failure) {
210
+ throw failure;
211
+ }
212
+ try {
213
+ return this.collectClass(node, node.name, symbol);
214
+ } catch (cause) {
215
+ if (cause instanceof SemanticError) {
216
+ this.failures.set(symbol, cause);
217
+ }
218
+ throw cause;
219
+ }
220
+ }
221
+
222
+ private collectClass(
223
+ node: ts.ClassDeclaration,
224
+ name: ts.Identifier,
225
+ symbol: ts.Symbol,
226
+ ): BlockSource {
227
+ if (this.active.has(symbol) || this.active.size >= maxInstanceNesting) {
228
+ this.fail(
229
+ node,
230
+ "PLC1007",
231
+ "Recursive or excessively nested block instance layout.",
232
+ );
233
+ }
234
+ if (
235
+ node.typeParameters?.length ||
236
+ node.modifiers?.some(
237
+ (modifier) =>
238
+ modifier.kind === ts.SyntaxKind.Decorator ||
239
+ modifier.kind === ts.SyntaxKind.AbstractKeyword,
240
+ )
241
+ ) {
242
+ this.fail(
243
+ node,
244
+ "PLC1001",
245
+ "Block classes are concrete; generic classes and decorators are unsupported.",
246
+ );
247
+ }
248
+ const [heritage, ...otherHeritage] = node.heritageClauses ?? [];
249
+ const [base, ...otherBases] = heritage?.types ?? [];
250
+ if (
251
+ otherHeritage.length ||
252
+ heritage?.token !== ts.SyntaxKind.ExtendsKeyword ||
253
+ !base ||
254
+ otherBases.length
255
+ ) {
256
+ this.fail(
257
+ node,
258
+ "PLC1001",
259
+ "Function block classes extend the canonical FunctionBlock marker only.",
260
+ );
261
+ }
262
+ const [inputNode, outputNode, ...otherSchemas] = base.typeArguments ?? [];
263
+ if (
264
+ this.types.sdkName(base.expression) !== "FunctionBlock" ||
265
+ !inputNode ||
266
+ otherSchemas.length
267
+ ) {
268
+ this.fail(
269
+ base,
270
+ "PLC1001",
271
+ "Extend FunctionBlock<Inputs, Outputs> with concrete schemas.",
272
+ );
273
+ }
274
+ // Register identity before nested fields; the active set rejects recursive allocation.
275
+ this.active.add(symbol);
276
+ const id = this.types.id(node, name.text);
277
+ const typeId = this.types.declareBlock(symbol, id);
278
+ try {
279
+ const inputFields = this.types.inputFields(inputNode);
280
+ const result = outputNode && this.outputRecord(outputNode);
281
+ const fieldBindings = new Map<ts.Symbol, Variable>();
282
+ const initializers = new Map<Variable, ts.Expression>();
283
+ const state: Variable[] = [];
284
+ let execute: { method: ts.MethodDeclaration; body: ts.Block } | undefined;
285
+ const methods: ts.MethodDeclaration[] = [];
286
+ for (const member of node.members) {
287
+ if (ts.isMethodDeclaration(member)) {
288
+ if (ts.isIdentifier(member.name) && member.name.text !== "execute") {
289
+ if (
290
+ !member.body ||
291
+ member.asteriskToken ||
292
+ member.questionToken ||
293
+ member.typeParameters?.length ||
294
+ ["update", "out"].includes(member.name.text) ||
295
+ member.modifiers?.some(
296
+ (modifier) =>
297
+ ![
298
+ ts.SyntaxKind.PublicKeyword,
299
+ ts.SyntaxKind.PrivateKeyword,
300
+ ts.SyntaxKind.ProtectedKeyword,
301
+ ].includes(modifier.kind),
302
+ )
303
+ ) {
304
+ this.fail(
305
+ member,
306
+ "PLC1001",
307
+ "Block methods require concrete instance implementations without generics or overloads.",
308
+ );
309
+ }
310
+ methods.push(member);
311
+ continue;
312
+ }
313
+ if (
314
+ execute ||
315
+ !ts.isIdentifier(member.name) ||
316
+ member.name.text !== "execute" ||
317
+ !member.body ||
318
+ member.asteriskToken ||
319
+ member.modifiers?.some(
320
+ (modifier) =>
321
+ ![
322
+ ts.SyntaxKind.ProtectedKeyword,
323
+ ts.SyntaxKind.OverrideKeyword,
324
+ ].includes(modifier.kind),
325
+ ) ||
326
+ !hasModifier(member, ts.SyntaxKind.ProtectedKeyword)
327
+ ) {
328
+ this.fail(
329
+ member,
330
+ "PLC1001",
331
+ "A block implements one protected execute method.",
332
+ );
333
+ }
334
+ execute = { method: member, body: member.body };
335
+ continue;
336
+ }
337
+ const field = this.collectStateField(member, id);
338
+ state.push(field.variable);
339
+ fieldBindings.set(field.symbol, field.variable);
340
+ if (field.initializer) {
341
+ initializers.set(field.variable, field.initializer);
342
+ }
343
+ }
344
+ const parameter = execute?.method.parameters[0];
345
+ if (
346
+ !execute ||
347
+ !parameter ||
348
+ execute.method.parameters.length !== 1 ||
349
+ execute.method.typeParameters?.length
350
+ ) {
351
+ this.fail(
352
+ node,
353
+ "PLC1001",
354
+ "Block execute requires one concrete input record parameter.",
355
+ );
356
+ }
357
+ const { method, body } = execute;
358
+ if (
359
+ !ts.isIdentifier(parameter.name) ||
360
+ !parameter.type ||
361
+ parameter.initializer ||
362
+ parameter.questionToken ||
363
+ parameter.dotDotDotToken
364
+ ) {
365
+ this.fail(
366
+ parameter,
367
+ "PLC2001",
368
+ "Block execute requires one named, explicitly typed input parameter.",
369
+ );
370
+ }
371
+ const methodFields = this.types.inputFields(parameter.type);
372
+ if (JSON.stringify(methodFields) !== JSON.stringify(inputFields)) {
373
+ this.fail(
374
+ parameter,
375
+ "PLC2001",
376
+ "execute input schema differs from its FunctionBlock marker.",
377
+ );
378
+ }
379
+ if (
380
+ !method.type ||
381
+ (result
382
+ ? this.types.resolve(method.type).type !== result
383
+ : method.type.kind !== ts.SyntaxKind.VoidKeyword)
384
+ ) {
385
+ this.fail(
386
+ method,
387
+ "PLC2001",
388
+ "execute return annotation must match the complete output record, or void when there are no outputs.",
389
+ );
390
+ }
391
+ const inputs = inputFields.map((field) => {
392
+ const mode = this.types.parameterMode(field);
393
+ return {
394
+ id: `${id}:input:${field.name}`,
395
+ name: field.name,
396
+ type: field.type,
397
+ storage: "parameter" as const,
398
+ mutable: mode === "inOut",
399
+ retention: "none" as const,
400
+ span: this.origin(parameter),
401
+ ...(mode && { mode }),
402
+ };
403
+ });
404
+ const outputType = result && this.types.types.get(result);
405
+ const outputs: Variable[] =
406
+ outputType && outputType.kind === "record"
407
+ ? outputType.fields.map((field) => ({
408
+ id: `${id}:output:${field.name}`,
409
+ name: field.name,
410
+ type: field.type,
411
+ storage: "blockOutput",
412
+ mutable: false,
413
+ retention: "none",
414
+ initial: defaultValue(field.type, this.types.types),
415
+ span: this.origin(method),
416
+ }))
417
+ : [];
418
+ const block: FunctionBlock = {
419
+ id,
420
+ name: name.text,
421
+ inputs,
422
+ outputs,
423
+ state,
424
+ locals: [],
425
+ body: [],
426
+ span: this.origin(node),
427
+ ...(result && { result }),
428
+ };
429
+ this.definitions.set(id, block);
430
+ if (result) {
431
+ this.types.blockOutput(typeId, id, result);
432
+ }
433
+ const source: BlockSource = {
434
+ block,
435
+ type: typeId,
436
+ body,
437
+ methods,
438
+ inputSymbol: this.types.symbol(parameter.name),
439
+ inputBindings: new Map(
440
+ inputs.map((variable) => [variable.name, variable]),
441
+ ),
442
+ fieldBindings,
443
+ initializers,
444
+ };
445
+ this.sources.set(symbol, source);
446
+ return source;
447
+ } finally {
448
+ this.active.delete(symbol);
449
+ }
450
+ }
451
+ /** The record an output schema names; undefined for `{}`, a block without outputs. */
452
+ private outputRecord(node: ts.TypeNode): string | undefined {
453
+ if (ts.isTypeLiteralNode(node) && !node.members.length) {
454
+ return undefined;
455
+ }
456
+ const resolved = this.types.resolve(node);
457
+ if (
458
+ resolved.io ||
459
+ resolved.mode ||
460
+ this.types.hasReferences(resolved.type) ||
461
+ this.types.types.get(resolved.type)?.kind !== "record"
462
+ ) {
463
+ this.fail(
464
+ node,
465
+ "PLC2001",
466
+ "Block outputs require a closed value record.",
467
+ );
468
+ }
469
+ return resolved.type;
470
+ }
471
+
472
+ private collectStateField(
473
+ member: ts.ClassElement,
474
+ id: string,
475
+ ): {
476
+ variable: Variable;
477
+ symbol: ts.Symbol;
478
+ initializer?: ts.Expression;
479
+ } {
480
+ if (
481
+ !ts.isPropertyDeclaration(member) ||
482
+ !ts.isIdentifier(member.name) ||
483
+ !member.initializer ||
484
+ member.questionToken ||
485
+ member.exclamationToken ||
486
+ !hasModifier(member, ts.SyntaxKind.PrivateKeyword) ||
487
+ member.modifiers?.some(
488
+ (modifier) =>
489
+ ![
490
+ ts.SyntaxKind.PrivateKeyword,
491
+ ts.SyntaxKind.ReadonlyKeyword,
492
+ ].includes(modifier.kind),
493
+ )
494
+ ) {
495
+ this.fail(
496
+ member,
497
+ "PLC1001",
498
+ "Block state uses private initialized instance fields; constructors, static fields and decorators are unsupported.",
499
+ );
500
+ }
501
+ const initial = storageInitializer(
502
+ member.initializer,
503
+ this.types,
504
+ this.fail,
505
+ );
506
+ const type = this.stateType(member, initial.value);
507
+ const instance = Boolean(instancedBlock(type, this.types.types));
508
+ if (
509
+ this.types.types.get(type)?.kind === "block" &&
510
+ !ts.isNewExpression(initial.value)
511
+ ) {
512
+ this.fail(
513
+ member,
514
+ "PLC1007",
515
+ "Block instances require static constructor initialization.",
516
+ );
517
+ }
518
+ const variable: Variable = {
519
+ id: `${id}:field:${member.name.text}`,
520
+ name: member.name.text,
521
+ type,
522
+ storage: instance ? "instance" : "field",
523
+ mutable: !instance && !hasModifier(member, ts.SyntaxKind.ReadonlyKeyword),
524
+ retention: initial.retention,
525
+ span: this.origin(member),
526
+ };
527
+ return {
528
+ variable,
529
+ symbol: this.types.symbol(member.name),
530
+ ...(!instance && { initializer: initial.value }),
531
+ };
532
+ }
533
+
534
+ /** A state field's type: the block or block array it allocates, its annotation, or its literal's type. */
535
+ private stateType(
536
+ member: ts.PropertyDeclaration,
537
+ value: ts.Expression,
538
+ ): string {
539
+ if (ts.isNewExpression(value)) {
540
+ const instance = this.instanceType(value);
541
+ if (member.type && this.types.resolve(member.type).type !== instance) {
542
+ this.fail(
543
+ member,
544
+ "PLC2001",
545
+ "Instance annotation differs from its constructor.",
546
+ );
547
+ }
548
+ return instance;
549
+ }
550
+ const instanceArray = this.instanceArrayType(member.type, value);
551
+ if (instanceArray) {
552
+ return instanceArray;
553
+ }
554
+ if (!member.type) {
555
+ return (
556
+ inferredStorageType(value) ??
557
+ this.fail(
558
+ member,
559
+ "PLC2001",
560
+ "Annotate private numeric and aggregate state explicitly.",
561
+ )
562
+ );
563
+ }
564
+ const annotation = this.types.resolve(member.type);
565
+ if (
566
+ annotation.io ||
567
+ annotation.mode ||
568
+ this.types.hasReferences(annotation.type)
569
+ ) {
570
+ this.fail(
571
+ member,
572
+ "PLC2001",
573
+ "Borrow and I/O wrappers cannot be stored in block state.",
574
+ );
575
+ }
576
+ return annotation.type;
577
+ }
578
+ }
@@ -0,0 +1,83 @@
1
+ import { type Diagnostic, error } from "@tsplc/compiler/ir";
2
+ import { type Environment, plainValue } from "@tsplc/config";
3
+ import ts from "typescript";
4
+ import { plcSources } from "./module-graph";
5
+ import { type Edit, edited, type Mapped, type Positions } from "./positions";
6
+ import { namesSdk } from "./sdk";
7
+
8
+ /** Whether `node` is the initializer of a module-level const, where configuration is read once. */
9
+ const inModuleConst = (node: ts.Node): boolean => {
10
+ const owner = ts.findAncestor(
11
+ node.parent,
12
+ (item) => ts.isVariableDeclaration(item) || ts.isFunctionLike(item),
13
+ );
14
+ return (
15
+ owner !== undefined &&
16
+ ts.isVariableDeclaration(owner) &&
17
+ ts.isVariableDeclarationList(owner.parent) &&
18
+ Boolean(owner.parent.flags & ts.NodeFlags.Const) &&
19
+ ts.isVariableStatement(owner.parent.parent) &&
20
+ ts.isSourceFile(owner.parent.parent.parent)
21
+ );
22
+ };
23
+
24
+ export const lowerEnvironment = (
25
+ program: ts.Program,
26
+ sdk: string,
27
+ positions: Positions,
28
+ environment: Environment,
29
+ ) => {
30
+ const checker = program.getTypeChecker();
31
+ const sources = new Map<string, Mapped>();
32
+ const diagnostics: Diagnostic[] = [];
33
+ /** Each environment value an `env()` call reads, by name. */
34
+ const read: Record<string, string> = {};
35
+ for (const source of plcSources(program)) {
36
+ const edits: Edit[] = [];
37
+ const visit = (node: ts.Node): void => {
38
+ if (ts.isCallExpression(node)) {
39
+ if (namesSdk(checker, sdk, node.expression, "env")) {
40
+ const reject = (message: string) =>
41
+ diagnostics.push(error("PLC1011", message, positions.node(node)));
42
+ const [name, ...rest] = node.arguments;
43
+ if (
44
+ !inModuleConst(node) ||
45
+ !name ||
46
+ rest.length ||
47
+ !ts.isStringLiteral(name) ||
48
+ node.typeArguments?.length !== 1
49
+ ) {
50
+ reject(
51
+ "env<STRING<N>> requires a literal environment name in module-level const configuration.",
52
+ );
53
+ return;
54
+ }
55
+ const value = environment[name.text];
56
+ if (!value) {
57
+ reject(`Required environment value ${name.text} is missing.`);
58
+ return;
59
+ }
60
+ if (!plainValue.safeParse(value).success) {
61
+ reject(
62
+ `Environment value ${name.text} contains an unsupported NUL byte.`,
63
+ );
64
+ return;
65
+ }
66
+ read[name.text] = value;
67
+ edits.push({
68
+ start: node.getStart(source),
69
+ end: node.end,
70
+ text: JSON.stringify(value),
71
+ });
72
+ return;
73
+ }
74
+ }
75
+ ts.forEachChild(node, visit);
76
+ };
77
+ visit(source);
78
+ if (edits.length) {
79
+ sources.set(source.fileName, edited(source, edits));
80
+ }
81
+ }
82
+ return { sources, diagnostics, read };
83
+ };