@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,1073 @@
1
+ import { dirname } from "node:path";
2
+ import {
3
+ aggregate,
4
+ type Diagnostic,
5
+ type Field,
6
+ instancedBlock,
7
+ isRadixLiteral,
8
+ layoutIssue,
9
+ maxNestingDepth,
10
+ maxScalarElements,
11
+ maxScalarElementsText,
12
+ maxStringCapacity,
13
+ type PlcType,
14
+ parseInteger,
15
+ pascalCase,
16
+ primitiveTypes,
17
+ } from "@tsplc/compiler/ir";
18
+ import { defaultStringLength, elementaryType, integerRange } from "@tsplc/iec";
19
+ import { generatedNamePattern } from "@tsplc/iec/st";
20
+ import ts from "typescript";
21
+ import { modulePath } from "./lowering-key";
22
+ import {
23
+ declaredBySdk,
24
+ isTelemetryDeclaration,
25
+ telemetryMethods,
26
+ unaliased,
27
+ valueSymbol,
28
+ } from "./sdk";
29
+
30
+ export interface ResolvedType {
31
+ type: string;
32
+ io?: "input" | "output";
33
+ mode?: "inOut";
34
+ }
35
+ export type TypeArgument =
36
+ | { kind: "type"; value: ResolvedType }
37
+ | { kind: "integer"; value: number };
38
+ export type TypeEnvironment = ReadonlyMap<ts.Symbol, TypeArgument>;
39
+ export type Fail = (node: ts.Node, code: string, message: string) => never;
40
+
41
+ // Array bounds and indexes are DINT, and so is every integer a layout takes as an argument and
42
+ // every PLC enum value.
43
+ const [lowestDint, highestDint] = integerRange(elementaryType("DINT"));
44
+ /** How many generic declarations may be expanding at once, which bounds recursive expansion. */
45
+ const maxSubstitutionDepth = 64;
46
+
47
+ /** What a Fail throws: one diagnostic that abandons the declaration or routine being analyzed. */
48
+ export class SemanticError extends Error {
49
+ constructor(readonly diagnostic: Diagnostic) {
50
+ super(diagnostic.message);
51
+ }
52
+ }
53
+
54
+ /** The PLC types an unannotated TypeScript `number` holds, whole or fractional, and a `bigint`. */
55
+ export const defaultNumericTypes = {
56
+ number: "DINT",
57
+ float: "LREAL",
58
+ bigint: "LINT",
59
+ } as const;
60
+
61
+ // The PLC type of an unannotated numeric literal: `number` means DINT unless it is fractional.
62
+ export const numericLiteralType = (text: string) => {
63
+ if (text.endsWith("n")) {
64
+ return defaultNumericTypes.bigint;
65
+ }
66
+ return /[.e]/i.test(text) && !isRadixLiteral(text)
67
+ ? defaultNumericTypes.float
68
+ : defaultNumericTypes.number;
69
+ };
70
+
71
+ /** The expression inside any parentheses, and inside non-null assertions when `nonNull` is set. */
72
+ export const unparenthesized = (
73
+ node: ts.Expression,
74
+ options?: { nonNull: boolean },
75
+ ): ts.Expression =>
76
+ ts.isParenthesizedExpression(node) ||
77
+ (options?.nonNull && ts.isNonNullExpression(node))
78
+ ? unparenthesized(node.expression, options)
79
+ : node;
80
+
81
+ /** `T` in a `Promise<T>` annotation. */
82
+ export const promisedType = (node: ts.TypeNode): ts.TypeNode | undefined =>
83
+ ts.isTypeReferenceNode(node) &&
84
+ ts.isIdentifier(node.typeName) &&
85
+ node.typeName.text === "Promise" &&
86
+ node.typeArguments?.length === 1
87
+ ? node.typeArguments[0]
88
+ : undefined;
89
+
90
+ /** The name of a record value's type: its alias or its named declaration; undefined for a scalar or an anonymous type. */
91
+ export const namedRecordText = (
92
+ checker: ts.TypeChecker,
93
+ node: ts.Expression,
94
+ ): string | undefined => {
95
+ const type = checker.getTypeAtLocation(node);
96
+ if (
97
+ !(type.flags & ts.TypeFlags.Object) ||
98
+ (!type.aliasSymbol && (!type.symbol || type.symbol.name === "__type"))
99
+ ) {
100
+ return undefined;
101
+ }
102
+ return checker.typeToString(
103
+ type,
104
+ node,
105
+ ts.TypeFormatFlags.NoTruncation |
106
+ ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
107
+ );
108
+ };
109
+
110
+ /** Whether a node only wraps the expression in it: parentheses, a non-null assertion or a type assertion. */
111
+ export const isWrapper = (
112
+ node: ts.Node,
113
+ ): node is
114
+ | ts.ParenthesizedExpression
115
+ | ts.NonNullExpression
116
+ | ts.AsExpression
117
+ | ts.SatisfiesExpression =>
118
+ ts.isParenthesizedExpression(node) ||
119
+ ts.isNonNullExpression(node) ||
120
+ ts.isAsExpression(node) ||
121
+ ts.isSatisfiesExpression(node);
122
+
123
+ /**
124
+ * The name of the field, parameter or variable an inline type or object literal is written for,
125
+ * through the arrays and unions it is an element or member of: `points` of `points: { x: DINT }[]`.
126
+ */
127
+ export const declaringName = (
128
+ node: ts.Node | undefined,
129
+ ): string | undefined => {
130
+ if (!node) {
131
+ return undefined;
132
+ }
133
+ if (
134
+ (ts.isPropertySignature(node) ||
135
+ ts.isPropertyDeclaration(node) ||
136
+ ts.isPropertyAssignment(node) ||
137
+ ts.isParameter(node) ||
138
+ ts.isVariableDeclaration(node)) &&
139
+ ts.isIdentifier(node.name)
140
+ ) {
141
+ return node.name.text;
142
+ }
143
+ if (
144
+ ts.isArrayTypeNode(node) ||
145
+ ts.isUnionTypeNode(node) ||
146
+ ts.isParenthesizedTypeNode(node) ||
147
+ ts.isTypeReferenceNode(node) ||
148
+ ts.isArrayLiteralExpression(node) ||
149
+ isWrapper(node)
150
+ ) {
151
+ return declaringName(node.parent);
152
+ }
153
+ return undefined;
154
+ };
155
+
156
+ /** Whether `type` is an aggregate (a record, array or block) rather than a scalar. */
157
+ export const isAggregateType = (type: ts.Type): boolean =>
158
+ Boolean(type.flags & ts.TypeFlags.Object);
159
+
160
+ // The source text of a numeric literal, negated literals included.
161
+ export function numericLiteral(node: ts.Expression): string | undefined {
162
+ const literal = unparenthesized(node);
163
+ if (ts.isNumericLiteral(literal) || ts.isBigIntLiteral(literal)) {
164
+ return literal.getText();
165
+ }
166
+ if (
167
+ ts.isPrefixUnaryExpression(literal) &&
168
+ literal.operator === ts.SyntaxKind.MinusToken
169
+ ) {
170
+ const operand = numericLiteral(literal.operand);
171
+ if (operand !== undefined) {
172
+ return operand.startsWith("-") ? operand.slice(1) : `-${operand}`;
173
+ }
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ /** The PLC type of storage declared without an annotation: only a numeric or boolean literal says it. */
179
+ export const inferredStorageType = (
180
+ initializer: ts.Expression,
181
+ ): string | undefined => {
182
+ if (
183
+ initializer.kind === ts.SyntaxKind.TrueKeyword ||
184
+ initializer.kind === ts.SyntaxKind.FalseKeyword
185
+ ) {
186
+ return "BOOL";
187
+ }
188
+ const literal = numericLiteral(initializer);
189
+ return literal === undefined ? undefined : numericLiteralType(literal);
190
+ };
191
+
192
+ /** The integer a literal names exactly; undefined when it has a fraction or is not a literal. */
193
+ const exactInteger = (text: string): bigint | undefined => {
194
+ try {
195
+ return parseInteger(text);
196
+ } catch {
197
+ return undefined;
198
+ }
199
+ };
200
+
201
+ /** The text of a numeric literal type, such as `4` or `-1`. */
202
+ const numericLiteralTypeText = (node: ts.TypeNode): string | undefined =>
203
+ ts.isLiteralTypeNode(node) &&
204
+ (ts.isNumericLiteral(node.literal) ||
205
+ ts.isPrefixUnaryExpression(node.literal))
206
+ ? node.literal.getText()
207
+ : undefined;
208
+
209
+ // The statically named callee of `name(...)` or `namespace.name(...)`.
210
+ export function calleeName(node: ts.Expression): ts.MemberName | undefined {
211
+ if (ts.isIdentifier(node)) {
212
+ return node;
213
+ }
214
+ return ts.isPropertyAccessExpression(node) ? node.name : undefined;
215
+ }
216
+
217
+ /** Whether a declaration carries a modifier keyword such as `export` or `async`. */
218
+ export const hasModifier = (
219
+ node: ts.HasModifiers,
220
+ kind: ts.ModifierSyntaxKind,
221
+ ): boolean =>
222
+ Boolean(node.modifiers?.some((modifier) => modifier.kind === kind));
223
+
224
+ /** Whether an identifier names a property, as in `a.name` or `{ name: value }`, rather than reading a variable. */
225
+ export const isPropertyName = (node: ts.Identifier): boolean =>
226
+ (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) ||
227
+ (ts.isPropertyAssignment(node.parent) && node.parent.name === node);
228
+
229
+ /** `name: value` or shorthand `name` in an object literal; undefined for spreads, methods and computed names. */
230
+ export function namedProperty(
231
+ property: ts.ObjectLiteralElementLike,
232
+ ): { name: string; value: ts.Expression } | undefined {
233
+ if (
234
+ !(
235
+ ts.isPropertyAssignment(property) ||
236
+ ts.isShorthandPropertyAssignment(property)
237
+ ) ||
238
+ !ts.isIdentifier(property.name)
239
+ ) {
240
+ return undefined;
241
+ }
242
+ return {
243
+ name: property.name.text,
244
+ value: ts.isPropertyAssignment(property)
245
+ ? property.initializer
246
+ : property.name,
247
+ };
248
+ }
249
+
250
+ export type TelemetryMethod = (typeof telemetryMethods)[number];
251
+
252
+ /** The declaration of a type parameter an environment binds. */
253
+ const typeParameter = (symbol: ts.Symbol): ts.Declaration => {
254
+ const [declaration] = symbol.declarations ?? [];
255
+ if (!declaration) {
256
+ throw new Error(`Type parameter ${symbol.name} has no declaration.`);
257
+ }
258
+ return declaration;
259
+ };
260
+
261
+ /** A service client's struct for a type naming a called procedure's record. */
262
+ export type ServiceRecord = (type: ts.Type) => ts.Symbol | undefined;
263
+
264
+ // The PLC layouts TypeScript annotations name. The checker resolves declarations; it never
265
+ // supplies erased numeric widths. Service records are the exception: `iec.*` schemas carry
266
+ // their widths as literal types.
267
+ export class TypeResolver {
268
+ private readonly layouts = new Map<string, PlcType>(
269
+ primitiveTypes.map((type) => [type.id, type]),
270
+ );
271
+ readonly types: ReadonlyMap<string, PlcType> = this.layouts;
272
+ private readonly blockTypes = new Map<ts.Symbol, string>();
273
+ private readonly standardTypes = new Map<string, string>();
274
+ readonly unions = new Set<string>();
275
+ private readonly active = new Set<string>();
276
+ /** Type literals' records by their fields. */
277
+ private readonly anonymousRecords = new Map<string, string>();
278
+ constructor(
279
+ private readonly checker: ts.TypeChecker,
280
+ private readonly root: string,
281
+ private readonly sdk: string,
282
+ private readonly fail: Fail,
283
+ private readonly serviceRecord: ServiceRecord | null,
284
+ ) {}
285
+
286
+ /** Registers a block class's layout before its fields resolve, so a recursive allocation finds it. */
287
+ declareBlock(symbol: ts.Symbol, block: string): string {
288
+ const id = `block:${block}`;
289
+ this.layouts.set(id, { id, kind: "block", block });
290
+ this.blockTypes.set(symbol, id);
291
+ return id;
292
+ }
293
+
294
+ /** Completes a collected block's layout with its output record. */
295
+ blockOutput(id: string, block: string, output: string): void {
296
+ this.layouts.set(id, { id, kind: "block", block, output });
297
+ }
298
+
299
+ /** Registers the SDK's standard block `name`, implemented by `block`, whose outputs form `output`. */
300
+ declareStandardBlock(
301
+ name: string,
302
+ block: string,
303
+ output: { id: string; fields: Field[] },
304
+ ): void {
305
+ this.layouts.set(output.id, {
306
+ id: output.id,
307
+ kind: "record",
308
+ fields: output.fields,
309
+ });
310
+ const id = `block:${block}`;
311
+ this.layouts.set(id, { id, kind: "block", block, output: output.id });
312
+ this.standardTypes.set(name, id);
313
+ }
314
+
315
+ /** The layout of the SDK's standard block `name`, such as `OnDelayTimer`. */
316
+ standardBlock(name: string): string | undefined {
317
+ return this.standardTypes.get(name);
318
+ }
319
+
320
+ /** How a routine receives `type`: records, arrays and blocks pass by reference, as objects do in TypeScript. */
321
+ parameterMode({ type, mode }: Pick<Field, "type" | "mode">) {
322
+ const layout = this.layouts.get(type);
323
+ return (
324
+ mode ??
325
+ (layout?.kind === "block" || aggregate(layout) ? "inOut" : undefined)
326
+ );
327
+ }
328
+
329
+ /** The symbol `node` reads, followed through import and export aliases. */
330
+ symbol(node: ts.Node): ts.Symbol {
331
+ const symbol = valueSymbol(this.checker, node);
332
+ if (!symbol) {
333
+ this.fail(node, "PLC1002", "This name has no PLC declaration.");
334
+ }
335
+ return unaliased(this.checker, symbol);
336
+ }
337
+
338
+ /** Declared by TypeScript's default library, such as `Record` or `Object`. */
339
+ standardLibrary(symbol: ts.Symbol): boolean {
340
+ return Boolean(
341
+ symbol.declarations?.every(
342
+ (declaration) =>
343
+ dirname(declaration.getSourceFile().fileName) ===
344
+ dirname(ts.getDefaultLibFilePath({})),
345
+ ),
346
+ );
347
+ }
348
+
349
+ sdkName(node: ts.Node): string | undefined {
350
+ const symbol = this.symbol(node);
351
+ return declaredBySdk(this.sdk, symbol) ? symbol.getName() : undefined;
352
+ }
353
+
354
+ /** The `@tsplc/compiler/telemetry` method a call names, such as `capture`. */
355
+ telemetryMethod(node: ts.CallExpression): TelemetryMethod | undefined {
356
+ if (!ts.isPropertyAccessExpression(node.expression)) {
357
+ return undefined;
358
+ }
359
+ const symbol = this.checker.getSymbolAtLocation(node.expression.name);
360
+ const declared = symbol?.declarations?.some((declaration) =>
361
+ isTelemetryDeclaration(this.sdk, declaration),
362
+ );
363
+ return declared
364
+ ? telemetryMethods.find((name) => name === symbol?.name)
365
+ : undefined;
366
+ }
367
+
368
+ id(node: ts.Node, name: string): string {
369
+ return `${modulePath(this.root, node.getSourceFile().fileName)}:${node.getStart()}:${name}`;
370
+ }
371
+
372
+ /**
373
+ * An inline type's id, named after the field, parameter or variable it is written for, else
374
+ * `fallback`. Type arguments it was resolved with go before the name, which stays the last segment.
375
+ */
376
+ private inlineId(
377
+ node: ts.Node,
378
+ fallback: string,
379
+ arguments_: string,
380
+ ): string {
381
+ const owner = declaringName(node.parent);
382
+ const name = owner === undefined ? fallback : pascalCase(owner);
383
+ return this.id(node, `${arguments_ ? `<${arguments_}>:` : ""}${name}`);
384
+ }
385
+
386
+ /**
387
+ * A type literal's record. Type literals with the same fields are one type, as TypeScript's
388
+ * structural types are, so a value passes between them unconverted; the first one resolved
389
+ * names it.
390
+ */
391
+ private typeLiteral(
392
+ node: ts.TypeLiteralNode,
393
+ environment: TypeEnvironment,
394
+ ): ResolvedType {
395
+ const fields = this.fields(node.members, environment);
396
+ const shape = JSON.stringify(fields);
397
+ const known = this.anonymousRecords.get(shape);
398
+ if (known !== undefined) {
399
+ return { type: known };
400
+ }
401
+ // Environment keys are admitted, declared type parameters with concrete bindings.
402
+ const arguments_ = [...environment]
403
+ .map(
404
+ ([symbol, value]) =>
405
+ `${this.id(typeParameter(symbol), symbol.name)}=${this.key(value)}`,
406
+ )
407
+ .sort()
408
+ .join(",");
409
+ const resolved = this.record(
410
+ node,
411
+ this.inlineId(node, "Fields", arguments_),
412
+ fields,
413
+ );
414
+ this.anonymousRecords.set(shape, resolved.type);
415
+ return resolved;
416
+ }
417
+
418
+ argument(node: ts.TypeNode, environment: TypeEnvironment): TypeArgument {
419
+ if (ts.isTypeReferenceNode(node)) {
420
+ const bound = environment.get(this.symbol(node.typeName));
421
+ if (bound && !node.typeArguments?.length) {
422
+ return bound;
423
+ }
424
+ }
425
+ // `(typeof table)["length"]` or `typeof table.length` has the literal type of an `as const` table.
426
+ const queried =
427
+ ts.isIndexedAccessTypeNode(node) || ts.isTypeQueryNode(node)
428
+ ? this.checker.getTypeFromTypeNode(node)
429
+ : undefined;
430
+ const text = queried?.isNumberLiteral()
431
+ ? String(queried.value)
432
+ : numericLiteralTypeText(node);
433
+ if (text !== undefined) {
434
+ const value =
435
+ exactInteger(text) ??
436
+ this.fail(
437
+ node,
438
+ "PLC2001",
439
+ "Layout arguments must be exact integer literals.",
440
+ );
441
+ if (value < lowestDint || value > highestDint) {
442
+ this.fail(
443
+ node,
444
+ "PLC2001",
445
+ "Layout argument is outside signed DINT range.",
446
+ );
447
+ }
448
+ return { kind: "integer", value: Number(value) };
449
+ }
450
+ return { kind: "type", value: this.resolve(node, environment) };
451
+ }
452
+
453
+ /**
454
+ * The environment a generic declaration's body resolves in, and the suffix that tells its
455
+ * specialization apart: each type parameter's argument in order, empty when it has none.
456
+ */
457
+ bindings(
458
+ parameters: readonly ts.TypeParameterDeclaration[] | undefined,
459
+ arguments_: readonly ts.TypeNode[] | undefined,
460
+ outer: TypeEnvironment,
461
+ node: ts.Node,
462
+ ): { environment: TypeEnvironment; suffix: string } {
463
+ const environment = new Map(outer);
464
+ const params = parameters ?? [];
465
+ const args = arguments_ ?? [];
466
+ if (args.length > params.length) {
467
+ this.fail(node, "PLC2001", "Too many concrete type arguments.");
468
+ }
469
+ const keys = params.map((parameter, index) => {
470
+ const argument = args[index] ?? parameter.default;
471
+ if (!argument) {
472
+ this.fail(
473
+ node,
474
+ "PLC2001",
475
+ "Generic PLC declarations require explicit concrete type arguments.",
476
+ );
477
+ }
478
+ const value = this.argument(argument, environment);
479
+ environment.set(this.symbol(parameter.name), value);
480
+ return this.key(value);
481
+ });
482
+ return { environment, suffix: keys.join(",") };
483
+ }
484
+
485
+ resolve(
486
+ node: ts.TypeNode,
487
+ environment: TypeEnvironment = new Map(),
488
+ ): ResolvedType {
489
+ if (node.kind === ts.SyntaxKind.BooleanKeyword) {
490
+ return { type: "BOOL" };
491
+ }
492
+ if (node.kind === ts.SyntaxKind.NumberKeyword) {
493
+ return { type: defaultNumericTypes.number };
494
+ }
495
+ if (node.kind === ts.SyntaxKind.StringKeyword) {
496
+ const id = `STRING<${defaultStringLength}>`;
497
+ this.layouts.set(id, {
498
+ id,
499
+ kind: "string",
500
+ capacity: defaultStringLength,
501
+ encoding: "utf8",
502
+ });
503
+ return { type: id };
504
+ }
505
+ if (ts.isParenthesizedTypeNode(node)) {
506
+ return this.resolve(node.type, environment);
507
+ }
508
+ if (ts.isTypeLiteralNode(node)) {
509
+ return this.typeLiteral(node, environment);
510
+ }
511
+ if (ts.isUnionTypeNode(node)) {
512
+ return this.union(node, this.inlineId(node, "Union", ""), environment);
513
+ }
514
+ if (ts.isIndexedAccessTypeNode(node)) {
515
+ const record = this.serviceRecord?.(
516
+ this.checker.getTypeFromTypeNode(node),
517
+ );
518
+ if (record) {
519
+ return this.declaration(record, undefined, environment, node);
520
+ }
521
+ }
522
+ if (!ts.isTypeReferenceNode(node)) {
523
+ this.fail(
524
+ node,
525
+ "PLC2001",
526
+ "Use an explicit supported PLC type; optional and dynamic layouts are unsupported.",
527
+ );
528
+ }
529
+ const symbol = this.symbol(node.typeName);
530
+ const bound = environment.get(symbol);
531
+ if (bound) {
532
+ if (bound.kind !== "type" || node.typeArguments?.length) {
533
+ this.fail(
534
+ node,
535
+ "PLC2001",
536
+ "An integer layout argument is not a storage type.",
537
+ );
538
+ }
539
+ return bound.value;
540
+ }
541
+ const official = this.sdkName(node.typeName);
542
+ const block =
543
+ this.blockTypes.get(symbol) ??
544
+ (official ? this.standardTypes.get(official) : undefined);
545
+ if (block) {
546
+ if (node.typeArguments?.length) {
547
+ this.fail(
548
+ node,
549
+ "PLC2001",
550
+ "Function block classes are concrete and take no type arguments.",
551
+ );
552
+ }
553
+ return { type: block };
554
+ }
555
+ if (official === "InOut") {
556
+ const inner = this.resolve(
557
+ this.soleTypeArgument(node, "InOut requires one concrete value type."),
558
+ environment,
559
+ );
560
+ if (inner.io || !this.isValue(inner)) {
561
+ this.fail(
562
+ node,
563
+ "PLC2001",
564
+ "InOut cannot nest or borrow a block instance.",
565
+ );
566
+ }
567
+ return { type: inner.type, mode: "inOut" };
568
+ }
569
+ if (official && this.layouts.has(official)) {
570
+ if (node.typeArguments?.length) {
571
+ this.fail(node, "PLC2001", "Scalar types take no type arguments.");
572
+ }
573
+ return { type: official };
574
+ }
575
+ if (official === "Input" || official === "Output") {
576
+ const inner = this.resolve(
577
+ this.soleTypeArgument(
578
+ node,
579
+ "I/O types need exactly one PLC type argument.",
580
+ ),
581
+ environment,
582
+ );
583
+ if (inner.io || inner.mode || this.hasReferences(inner.type)) {
584
+ this.fail(node, "PLC2001", "I/O type wrappers cannot be nested.");
585
+ }
586
+ return {
587
+ type: inner.type,
588
+ io: official === "Input" ? "input" : "output",
589
+ };
590
+ }
591
+ if (official === "FixedArray") {
592
+ const [element, length, lower, ...rest] = node.typeArguments ?? [];
593
+ if (!element || !length || rest.length) {
594
+ this.fail(
595
+ node,
596
+ "PLC2001",
597
+ "FixedArray needs element, length and optional lower bound.",
598
+ );
599
+ }
600
+ return this.fixedArray(
601
+ node,
602
+ this.resolve(element, environment),
603
+ this.argument(length, environment),
604
+ lower
605
+ ? this.argument(lower, environment)
606
+ : { kind: "integer", value: 0 },
607
+ );
608
+ }
609
+ // TypeScript's own `Record`; its keys are a contiguous enum.
610
+ if (symbol.name === "Record" && this.standardLibrary(symbol)) {
611
+ const [key, value] = node.typeArguments ?? [];
612
+ const index =
613
+ key && ts.isTypeReferenceNode(key)
614
+ ? this.layouts.get(this.resolve(key, environment).type)
615
+ : undefined;
616
+ if (index?.kind !== "enum" || !value) {
617
+ this.fail(
618
+ node,
619
+ "PLC2001",
620
+ "Record keys must be a numeric PLC enum; dynamic index signatures are unsupported.",
621
+ );
622
+ }
623
+ const values = index.members.map((member) => Number(member.value));
624
+ const lower = Math.min(...values);
625
+ if (Math.max(...values) - lower + 1 !== values.length) {
626
+ this.fail(
627
+ node,
628
+ "PLC2001",
629
+ "Record<Enum, T> needs enum member values without gaps.",
630
+ );
631
+ }
632
+ const element = this.resolve(value, environment);
633
+ if (element.io || !this.isValue(element)) {
634
+ this.fail(
635
+ node,
636
+ "PLC2001",
637
+ "Enum-keyed records need a plain value element.",
638
+ );
639
+ }
640
+ const id = `array<${element.type},${values.length},${lower},${index.id}>`;
641
+ this.layouts.set(id, {
642
+ id,
643
+ kind: "array",
644
+ element: element.type,
645
+ length: values.length,
646
+ lowerBound: lower,
647
+ index: index.id,
648
+ });
649
+ this.checkSize(id, node);
650
+ return { type: id };
651
+ }
652
+ if (official === "STRING" || official === "WSTRING") {
653
+ const capacity = this.argument(
654
+ this.soleTypeArgument(
655
+ node,
656
+ "Bounded strings require one capacity argument.",
657
+ ),
658
+ environment,
659
+ );
660
+ if (
661
+ capacity.kind !== "integer" ||
662
+ capacity.value < 1 ||
663
+ capacity.value > maxStringCapacity
664
+ ) {
665
+ this.fail(
666
+ node,
667
+ "PLC2001",
668
+ `String capacity must be 1..${maxStringCapacity}.`,
669
+ );
670
+ }
671
+ const id = `${official}<${capacity.value}>`;
672
+ this.layouts.set(id, {
673
+ id,
674
+ kind: "string",
675
+ capacity: capacity.value,
676
+ encoding: official === "STRING" ? "utf8" : "utf16",
677
+ });
678
+ return { type: id };
679
+ }
680
+ return this.declaration(symbol, node.typeArguments, environment, node);
681
+ }
682
+
683
+ private soleTypeArgument(
684
+ node: ts.TypeReferenceNode,
685
+ message: string,
686
+ ): ts.TypeNode {
687
+ const [argument, ...rest] = node.typeArguments ?? [];
688
+ if (!argument || rest.length) {
689
+ this.fail(node, "PLC2001", message);
690
+ }
691
+ return argument;
692
+ }
693
+
694
+ fixedArray(
695
+ node: ts.Node,
696
+ element: ResolvedType,
697
+ length: TypeArgument,
698
+ lower: TypeArgument,
699
+ ): ResolvedType {
700
+ if (
701
+ element.io ||
702
+ !(
703
+ this.isValue(element) ||
704
+ this.layouts.get(element.type)?.kind === "block"
705
+ ) ||
706
+ length.kind !== "integer" ||
707
+ lower.kind !== "integer" ||
708
+ length.value < 1 ||
709
+ length.value > maxScalarElements ||
710
+ BigInt(lower.value + length.value - 1) > highestDint
711
+ ) {
712
+ this.fail(
713
+ node,
714
+ "PLC2001",
715
+ "Fixed arrays need a supported element, positive bounded length and signed DINT bounds.",
716
+ );
717
+ }
718
+ const id = `array<${element.type},${length.value},${lower.value}>`;
719
+ this.layouts.set(id, {
720
+ id,
721
+ kind: "array",
722
+ element: element.type,
723
+ length: length.value,
724
+ lowerBound: lower.value,
725
+ });
726
+ this.checkSize(id, node);
727
+ return { type: id };
728
+ }
729
+
730
+ private declaration(
731
+ symbol: ts.Symbol,
732
+ arguments_: readonly ts.TypeNode[] | undefined,
733
+ environment: TypeEnvironment,
734
+ node: ts.Node,
735
+ ): ResolvedType {
736
+ const declarations = symbol.declarations ?? [];
737
+ if (declarations.filter(ts.isInterfaceDeclaration).length > 1) {
738
+ this.fail(
739
+ node,
740
+ "PLC2001",
741
+ "Interface declaration merging is unsupported; use one closed layout declaration.",
742
+ );
743
+ }
744
+ const declaration = declarations.find(
745
+ (item) =>
746
+ ts.isTypeAliasDeclaration(item) ||
747
+ ts.isInterfaceDeclaration(item) ||
748
+ ts.isEnumDeclaration(item),
749
+ );
750
+ if (!declaration) {
751
+ this.fail(
752
+ node,
753
+ "PLC2001",
754
+ "This type is not implemented by the PLC frontend.",
755
+ );
756
+ }
757
+ if (ts.isEnumDeclaration(declaration)) {
758
+ if (arguments_?.length) {
759
+ this.fail(node, "PLC2001", "Enums take no type arguments.");
760
+ }
761
+ return this.enumeration(declaration);
762
+ }
763
+ const { environment: bindings, suffix } = this.bindings(
764
+ declaration.typeParameters,
765
+ arguments_,
766
+ environment,
767
+ node,
768
+ );
769
+ const id = `${this.id(declaration, declaration.name.text)}${suffix ? `<${suffix}>` : ""}`;
770
+ if (this.active.has(id)) {
771
+ this.fail(
772
+ node,
773
+ "PLC2001",
774
+ "Recursive by-value PLC layouts are unsupported.",
775
+ );
776
+ }
777
+ if (this.layouts.has(id)) {
778
+ return { type: id };
779
+ }
780
+ if (this.active.size >= maxSubstitutionDepth) {
781
+ this.fail(
782
+ node,
783
+ "PLC2001",
784
+ `Type substitution exceeds ${maxSubstitutionDepth} levels; recursive expansion is unsupported.`,
785
+ );
786
+ }
787
+ this.active.add(id);
788
+ try {
789
+ if (ts.isTypeAliasDeclaration(declaration)) {
790
+ if (ts.isTypeLiteralNode(declaration.type)) {
791
+ return this.record(
792
+ declaration,
793
+ id,
794
+ this.fields(declaration.type.members, bindings),
795
+ );
796
+ }
797
+ if (ts.isUnionTypeNode(declaration.type)) {
798
+ return this.union(declaration.type, id, bindings);
799
+ }
800
+ return this.resolve(declaration.type, bindings);
801
+ }
802
+ const inherited: Field[] = [];
803
+ for (const heritage of declaration.heritageClauses ?? []) {
804
+ for (const base of heritage.types) {
805
+ const baseSymbol = this.symbol(base.expression);
806
+ const baseType = this.declaration(
807
+ baseSymbol,
808
+ base.typeArguments,
809
+ bindings,
810
+ base,
811
+ );
812
+ const layout = this.layouts.get(baseType.type);
813
+ if (layout?.kind !== "record") {
814
+ this.fail(base, "PLC2001", "Inherited layout must be a record.");
815
+ }
816
+ inherited.push(...layout.fields);
817
+ }
818
+ }
819
+ return this.record(
820
+ declaration,
821
+ id,
822
+ this.fields(declaration.members, bindings, inherited),
823
+ );
824
+ } finally {
825
+ this.active.delete(id);
826
+ }
827
+ }
828
+ // Specialization identity includes I/O and InOut modes: equal value widths alone
829
+ // must not merge a readonly value parameter with a mutable borrowed input.
830
+ key(argument: TypeArgument): string {
831
+ if (argument.kind === "integer") {
832
+ return String(argument.value);
833
+ }
834
+ const { type, io, mode } = argument.value;
835
+ return `${type}${io ? `:${io}` : ""}${mode ? `:${mode}` : ""}`;
836
+ }
837
+
838
+ /**
839
+ * A discriminated union is one fixed layout: a `kind` enum plus the fields of every variant.
840
+ * TypeScript's narrowing guards which fields a branch can read; a literal's unset fields are zero.
841
+ */
842
+ private union(
843
+ node: ts.UnionTypeNode,
844
+ id: string,
845
+ environment: TypeEnvironment,
846
+ ): ResolvedType {
847
+ const fields = new Map<string, Field>();
848
+ const kinds: string[] = [];
849
+ for (const variant of node.types) {
850
+ const members = ts.isTypeLiteralNode(variant)
851
+ ? variant.members
852
+ : undefined;
853
+ const tag = members?.find(
854
+ (member) =>
855
+ ts.isPropertySignature(member) && member.name.getText() === "kind",
856
+ );
857
+ const literal =
858
+ tag &&
859
+ ts.isPropertySignature(tag) &&
860
+ tag.type &&
861
+ ts.isLiteralTypeNode(tag.type)
862
+ ? tag.type.literal
863
+ : undefined;
864
+ if (
865
+ !members ||
866
+ !literal ||
867
+ !ts.isStringLiteral(literal) ||
868
+ !generatedNamePattern.test(literal.text)
869
+ ) {
870
+ this.fail(
871
+ variant,
872
+ "PLC2001",
873
+ 'Union variants are object types with an identifier string literal `kind`, such as { kind: "idle" }.',
874
+ );
875
+ }
876
+ if (kinds.includes(literal.text)) {
877
+ this.fail(variant, "PLC2001", "Duplicate union kind.");
878
+ }
879
+ kinds.push(literal.text);
880
+ for (const field of this.fields(
881
+ members.filter((member) => member !== tag),
882
+ environment,
883
+ )) {
884
+ const existing = fields.get(field.name);
885
+ if (existing && existing.type !== field.type) {
886
+ this.fail(
887
+ variant,
888
+ "PLC2001",
889
+ "Union variants may share a field only with the same type.",
890
+ );
891
+ }
892
+ fields.set(field.name, field);
893
+ }
894
+ }
895
+ const kindId = `${id}Kind`;
896
+ this.layouts.set(kindId, {
897
+ id: kindId,
898
+ kind: "enum",
899
+ base: "DINT",
900
+ members: kinds.map((name, value) => ({ name, value: String(value) })),
901
+ });
902
+ this.layouts.set(id, {
903
+ id,
904
+ kind: "record",
905
+ fields: [
906
+ { name: "kind", type: kindId, readonly: false },
907
+ ...fields.values(),
908
+ ],
909
+ });
910
+ this.unions.add(id);
911
+ this.checkSize(id, node);
912
+ return { type: id };
913
+ }
914
+
915
+ private record(node: ts.Node, id: string, fields: Field[]): ResolvedType {
916
+ if (!fields.length) {
917
+ this.fail(node, "PLC2001", "PLC records require at least one field.");
918
+ }
919
+ this.layouts.set(id, { id, kind: "record", fields });
920
+ this.checkSize(id, node);
921
+ return { type: id };
922
+ }
923
+
924
+ private fields(
925
+ members: readonly ts.TypeElement[],
926
+ environment: TypeEnvironment,
927
+ inherited: readonly Field[] = [],
928
+ ): Field[] {
929
+ const fields = [...inherited];
930
+ const names = new Set(fields.map((field) => field.name));
931
+ for (const member of members) {
932
+ if (
933
+ !ts.isPropertySignature(member) ||
934
+ !member.type ||
935
+ member.questionToken ||
936
+ !member.name ||
937
+ !ts.isIdentifier(member.name)
938
+ ) {
939
+ this.fail(
940
+ member,
941
+ "PLC2001",
942
+ "PLC records have named, required, explicitly typed fields; methods and index signatures are unsupported.",
943
+ );
944
+ }
945
+ if (names.has(member.name.text)) {
946
+ this.fail(member, "PLC2001", "Duplicate record field.");
947
+ }
948
+ const type = this.resolve(member.type, environment);
949
+ if (instancedBlock(type.type, this.types)) {
950
+ this.fail(
951
+ member,
952
+ "PLC2001",
953
+ "Block instances belong in module or private block fields, not value records.",
954
+ );
955
+ }
956
+ if (type.io) {
957
+ this.fail(
958
+ member,
959
+ "PLC2001",
960
+ "Logical I/O wrappers belong on ambient bindings, not fields.",
961
+ );
962
+ }
963
+ fields.push({
964
+ name: member.name.text,
965
+ type: type.type,
966
+ ...(type.mode && { mode: type.mode }),
967
+ readonly: hasModifier(member, ts.SyntaxKind.ReadonlyKeyword),
968
+ });
969
+ names.add(member.name.text);
970
+ }
971
+ return fields;
972
+ }
973
+
974
+ inputFields(node: ts.TypeNode): readonly Field[] {
975
+ if (ts.isTypeLiteralNode(node) && !node.members.length) {
976
+ return [];
977
+ }
978
+ const resolved = this.resolve(node);
979
+ const type = this.layouts.get(resolved.type);
980
+ if (resolved.io || resolved.mode || type?.kind !== "record") {
981
+ this.fail(
982
+ node,
983
+ "PLC2001",
984
+ "Block inputs require one closed record schema.",
985
+ );
986
+ }
987
+ if (type.fields.some((field) => this.hasReferences(field.type))) {
988
+ this.fail(
989
+ node,
990
+ "PLC2001",
991
+ "InOut belongs directly on input fields, not nested records.",
992
+ );
993
+ }
994
+ return type.fields;
995
+ }
996
+
997
+ // A plain value layout: no InOut borrow, nested borrow schema or block instance.
998
+ isValue(resolved: ResolvedType): boolean {
999
+ return (
1000
+ !resolved.mode &&
1001
+ !this.hasReferences(resolved.type) &&
1002
+ !instancedBlock(resolved.type, this.types)
1003
+ );
1004
+ }
1005
+
1006
+ hasReferences(id: string, seen = new Set<string>()): boolean {
1007
+ if (seen.has(id)) {
1008
+ return false;
1009
+ }
1010
+ seen.add(id);
1011
+ const type = this.layouts.get(id);
1012
+ if (type?.kind === "record") {
1013
+ return type.fields.some(
1014
+ (field) => field.mode || this.hasReferences(field.type, seen),
1015
+ );
1016
+ }
1017
+ return type?.kind === "array" && this.hasReferences(type.element, seen);
1018
+ }
1019
+
1020
+ enumeration(node: ts.EnumDeclaration): ResolvedType {
1021
+ const id = this.id(node, node.name.text);
1022
+ if (this.layouts.has(id)) {
1023
+ return { type: id };
1024
+ }
1025
+ if (!node.members.length) {
1026
+ this.fail(node, "PLC2001", "PLC enums cannot be empty.");
1027
+ }
1028
+ const members = node.members.map((member) => {
1029
+ if (!ts.isIdentifier(member.name)) {
1030
+ this.fail(member, "PLC2001", "Enum members require identifier names.");
1031
+ }
1032
+ const value = this.checker.getConstantValue(member);
1033
+ if (
1034
+ typeof value !== "number" ||
1035
+ !Number.isInteger(value) ||
1036
+ BigInt(value) < lowestDint ||
1037
+ BigInt(value) > highestDint
1038
+ ) {
1039
+ this.fail(
1040
+ member,
1041
+ "PLC2001",
1042
+ "PLC enum values must be compile-time DINT integers.",
1043
+ );
1044
+ }
1045
+ return { name: member.name.text, value: String(value) };
1046
+ });
1047
+ if (
1048
+ new Set(members.map((member) => member.value)).size !== members.length
1049
+ ) {
1050
+ this.fail(node, "PLC2001", "PLC enum members require distinct values.");
1051
+ }
1052
+ this.layouts.set(id, { id, kind: "enum", base: "DINT", members });
1053
+ return { type: id };
1054
+ }
1055
+
1056
+ private checkSize(id: string, node: ts.Node): void {
1057
+ const budget = layoutIssue(this.layouts, id);
1058
+ if (budget === "nesting") {
1059
+ this.fail(
1060
+ node,
1061
+ "PLC2001",
1062
+ `PLC layout nesting exceeds ${maxNestingDepth} levels.`,
1063
+ );
1064
+ }
1065
+ if (budget === "size") {
1066
+ this.fail(
1067
+ node,
1068
+ "PLC2001",
1069
+ `PLC layout exceeds ${maxScalarElementsText} scalar elements.`,
1070
+ );
1071
+ }
1072
+ }
1073
+ }