@tsplc/compiler 0.2.16 → 0.2.18

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -1,592 +1,886 @@
1
1
  import ts from "typescript";
2
2
  import { dirname, relative, resolve } from "node:path";
3
+ import { elementaryType, integerRange } from "@tsplc/iec";
4
+ import { declaredBySdk, unaliased } from "./sdk.ts";
3
5
  import {
4
- instancedBlock,
5
- primitiveTypes,
6
- parseInteger,
7
- type PlcType,
8
- type Field,
9
- type MathHelper,
6
+ instancedBlock,
7
+ maxNestingDepth,
8
+ maxScalarElements,
9
+ type Diagnostic,
10
+ primitiveTypes,
11
+ parseInteger,
12
+ type PlcType,
13
+ type Field,
14
+ type MathHelper,
10
15
  } from "@tsplc/compiler/ir";
11
16
 
12
17
  export interface ResolvedType {
13
- type: string;
14
- io?: "input" | "output";
15
- mode?: "inOut";
18
+ type: string;
19
+ io?: "input" | "output";
20
+ mode?: "inOut";
16
21
  }
17
22
  export type TypeArgument =
18
- { kind: "type"; value: ResolvedType } | { kind: "integer"; value: number };
23
+ { kind: "type"; value: ResolvedType } | { kind: "integer"; value: number };
19
24
  export type TypeEnvironment = ReadonlyMap<ts.Symbol, TypeArgument>;
20
25
  export type Fail = (node: ts.Node, code: string, message: string) => never;
21
26
 
27
+ // Array bounds and indexes are DINT, and so is every integer a layout takes as an argument.
28
+ const [firstIndex, lastIndex] = integerRange(elementaryType("DINT"));
29
+ // PLC enums have a DINT base.
30
+ const [lowestEnumValue, highestEnumValue] = integerRange(
31
+ elementaryType("DINT"),
32
+ );
33
+
34
+ /** What a Fail throws: one diagnostic that abandons the declaration or routine being analyzed. */
35
+ export class SemanticError extends Error {
36
+ constructor(readonly diagnostic: Diagnostic) {
37
+ super(diagnostic.message);
38
+ }
39
+ }
40
+
22
41
  // The PLC type of an unannotated numeric literal: `number` means DINT unless it is fractional.
23
- export const numericLiteralType = (text: string) =>
24
- text.endsWith("n") ? "LINT" : /[.e]/i.test(text) && !/^[-]?0[xob]/i.test(text) ? "LREAL" : "DINT";
42
+ export const numericLiteralType = (text: string) => {
43
+ if (text.endsWith("n")) {
44
+ return "LINT";
45
+ }
46
+ return /[.e]/i.test(text) && !/^[-]?0[xob]/i.test(text) ? "LREAL" : "DINT";
47
+ };
48
+
49
+ /** The expression inside any parentheses. */
50
+ export const unparenthesized = (node: ts.Expression): ts.Expression =>
51
+ ts.isParenthesizedExpression(node) ? unparenthesized(node.expression) : node;
52
+
53
+ // The source text of a numeric literal, negated literals included.
54
+ export function numericLiteral(node: ts.Expression): string | undefined {
55
+ const literal = unparenthesized(node);
56
+ if (ts.isNumericLiteral(literal) || ts.isBigIntLiteral(literal)) {
57
+ return literal.getText();
58
+ }
59
+ if (
60
+ ts.isPrefixUnaryExpression(literal) &&
61
+ literal.operator === ts.SyntaxKind.MinusToken
62
+ ) {
63
+ const operand = numericLiteral(literal.operand);
64
+ if (operand !== undefined) {
65
+ return operand.startsWith("-") ? operand.slice(1) : `-${operand}`;
66
+ }
67
+ }
68
+ return undefined;
69
+ }
70
+
71
+ /** The text of a numeric literal type, such as `4` or `-1`. */
72
+ const numericLiteralTypeText = (node: ts.TypeNode): string | undefined =>
73
+ ts.isLiteralTypeNode(node) &&
74
+ (ts.isNumericLiteral(node.literal) ||
75
+ ts.isPrefixUnaryExpression(node.literal))
76
+ ? node.literal.getText()
77
+ : undefined;
25
78
 
26
79
  // The statically named callee of `name(...)` or `namespace.name(...)`.
27
80
  export function calleeName(node: ts.Expression): ts.MemberName | undefined {
28
- if (ts.isIdentifier(node)) return node;
29
- return ts.isPropertyAccessExpression(node) ? node.name : undefined;
81
+ if (ts.isIdentifier(node)) {
82
+ return node;
83
+ }
84
+ return ts.isPropertyAccessExpression(node) ? node.name : undefined;
85
+ }
86
+
87
+ /** Whether a declaration carries a modifier keyword such as `export` or `async`. */
88
+ export const hasModifier = (
89
+ node: ts.HasModifiers,
90
+ kind: ts.ModifierSyntaxKind,
91
+ ): boolean =>
92
+ Boolean(node.modifiers?.some((modifier) => modifier.kind === kind));
93
+
94
+ /** `name: value` or shorthand `name` in an object literal; undefined for spreads, methods and computed names. */
95
+ export function namedProperty(
96
+ property: ts.ObjectLiteralElementLike,
97
+ ): { name: string; value: ts.Expression } | undefined {
98
+ if (
99
+ !(
100
+ ts.isPropertyAssignment(property) ||
101
+ ts.isShorthandPropertyAssignment(property)
102
+ ) ||
103
+ !ts.isIdentifier(property.name)
104
+ ) {
105
+ return undefined;
106
+ }
107
+ return {
108
+ name: property.name.text,
109
+ value: ts.isPropertyAssignment(property)
110
+ ? property.initializer
111
+ : property.name,
112
+ };
30
113
  }
31
114
 
32
- const telemetryMethods = ["capture", "info", "warn", "error", "captureException", "text"] as const;
33
- type TelemetryMethod = (typeof telemetryMethods)[number];
115
+ const telemetryMethods = [
116
+ "capture",
117
+ "info",
118
+ "warn",
119
+ "error",
120
+ "captureException",
121
+ "text",
122
+ ] as const;
123
+ export type TelemetryMethod = (typeof telemetryMethods)[number];
34
124
 
35
125
  // This is the sole owner of TypeScript annotation substitution and PLC layouts.
36
126
  // The checker resolves declarations; it never supplies erased numeric widths.
37
127
  // Service records are the exception: `iec.*` schemas carry their widths as literal types.
38
128
  export class TypeResolver {
39
- readonly types = new Map<string, PlcType>(primitiveTypes.map((type) => [type.id, type]));
40
- readonly blockTypes = new Map<ts.Symbol, string>();
41
- readonly standardTypes = new Map<string, string>();
42
- readonly unions = new Set<string>();
43
- private readonly active = new Set<string>();
44
- constructor(
45
- private readonly checker: ts.TypeChecker,
46
- private readonly root: string,
47
- private readonly sdk: string,
48
- private readonly fail: Fail,
49
- /** The service client's struct for a type naming a called procedure's record. */
50
- private readonly serviceRecord?: (type: ts.Type) => ts.Symbol | undefined,
51
- ) {}
52
- symbol(node: ts.Node): ts.Symbol {
53
- // An object shorthand has a property symbol and a separate value binding.
54
- // PLC loads and intrinsic provenance must follow the value, including imports.
55
- let symbol =
56
- ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node
57
- ? this.checker.getShorthandAssignmentValueSymbol(node.parent)
58
- : this.checker.getSymbolAtLocation(node);
59
- if (!symbol) this.fail(node, "PLC1002", "This name has no PLC declaration.");
60
- while (symbol.flags & ts.SymbolFlags.Alias) symbol = this.checker.getAliasedSymbol(symbol);
61
- return symbol;
62
- }
129
+ readonly types = new Map<string, PlcType>(
130
+ primitiveTypes.map((type) => [type.id, type]),
131
+ );
132
+ readonly blockTypes = new Map<ts.Symbol, string>();
133
+ readonly standardTypes = new Map<string, string>();
134
+ readonly unions = new Set<string>();
135
+ private readonly active = new Set<string>();
136
+ constructor(
137
+ private readonly checker: ts.TypeChecker,
138
+ private readonly root: string,
139
+ private readonly sdk: string,
140
+ private readonly fail: Fail,
141
+ /** The service client's struct for a type naming a called procedure's record. */
142
+ private readonly serviceRecord?: (type: ts.Type) => ts.Symbol | undefined,
143
+ ) {}
144
+ symbol(node: ts.Node): ts.Symbol {
145
+ // An object shorthand has a property symbol and a separate value binding.
146
+ // PLC loads and intrinsic provenance must follow the value, including imports.
147
+ const symbol =
148
+ ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node
149
+ ? this.checker.getShorthandAssignmentValueSymbol(node.parent)
150
+ : this.checker.getSymbolAtLocation(node);
151
+ if (!symbol) {
152
+ this.fail(node, "PLC1002", "This name has no PLC declaration.");
153
+ }
154
+ return unaliased(this.checker, symbol);
155
+ }
63
156
 
64
- /** Declared by TypeScript's default library, such as `Record` or `Object`. */
65
- standardLibrary(symbol: ts.Symbol): boolean {
66
- return Boolean(
67
- symbol.declarations?.every(
68
- (declaration) =>
69
- dirname(declaration.getSourceFile().fileName) === dirname(ts.getDefaultLibFilePath({})),
70
- ),
71
- );
72
- }
157
+ /** Declared by TypeScript's default library, such as `Record` or `Object`. */
158
+ standardLibrary(symbol: ts.Symbol): boolean {
159
+ return Boolean(
160
+ symbol.declarations?.every(
161
+ (declaration) =>
162
+ dirname(declaration.getSourceFile().fileName) ===
163
+ dirname(ts.getDefaultLibFilePath({})),
164
+ ),
165
+ );
166
+ }
73
167
 
74
- sdkName(node: ts.Node): string | undefined {
75
- const symbol = this.symbol(node);
76
- return symbol.declarations?.some((declaration) =>
77
- declaration.getSourceFile().fileName.startsWith(`${dirname(this.sdk)}/`),
78
- )
79
- ? symbol.getName()
80
- : undefined;
81
- }
168
+ sdkName(node: ts.Node): string | undefined {
169
+ const symbol = this.symbol(node);
170
+ return declaredBySdk(this.sdk, symbol) ? symbol.getName() : undefined;
171
+ }
82
172
 
83
- /** The `@tsplc/compiler/telemetry` method a call names, such as `capture`. */
84
- telemetryMethod(node: ts.CallExpression): TelemetryMethod | undefined {
85
- if (!ts.isPropertyAccessExpression(node.expression)) return undefined;
86
- const symbol = this.checker.getSymbolAtLocation(node.expression.name);
87
- const declared = symbol?.declarations?.some(
88
- (declaration) =>
89
- declaration.getSourceFile().fileName === `${dirname(this.sdk)}/telemetry.d.ts`,
90
- );
91
- return declared ? telemetryMethods.find((name) => name === symbol?.name) : undefined;
92
- }
173
+ /** The `@tsplc/compiler/telemetry` method a call names, such as `capture`. */
174
+ telemetryMethod(node: ts.CallExpression): TelemetryMethod | undefined {
175
+ if (!ts.isPropertyAccessExpression(node.expression)) {
176
+ return undefined;
177
+ }
178
+ const symbol = this.checker.getSymbolAtLocation(node.expression.name);
179
+ const declared = symbol?.declarations?.some(
180
+ (declaration) =>
181
+ declaration.getSourceFile().fileName ===
182
+ `${dirname(this.sdk)}/telemetry.d.ts`,
183
+ );
184
+ return declared
185
+ ? telemetryMethods.find((name) => name === symbol?.name)
186
+ : undefined;
187
+ }
93
188
 
94
- /** `min`, `max` or `clamp` from the SDK's `@tsplc/compiler/math`. */
95
- mathHelper(node: ts.Node, name: string): MathHelper | undefined {
96
- return resolve(node.getSourceFile().fileName) ===
97
- resolve(dirname(this.sdk), "../stdlib/math.ts") &&
98
- (name === "min" || name === "max" || name === "clamp")
99
- ? name
100
- : undefined;
101
- }
189
+ /** `min`, `max` or `clamp` from the SDK's `@tsplc/compiler/math`. */
190
+ mathHelper(node: ts.Node, name: string): MathHelper | undefined {
191
+ return resolve(node.getSourceFile().fileName) ===
192
+ resolve(dirname(this.sdk), "../stdlib/math.ts") &&
193
+ (name === "min" || name === "max" || name === "clamp")
194
+ ? name
195
+ : undefined;
196
+ }
102
197
 
103
- id(node: ts.Node, name: string): string {
104
- return `${relative(this.root, node.getSourceFile().fileName).replaceAll("\\", "/")}:${node.getStart()}:${name}`;
105
- }
198
+ id(node: ts.Node, name: string): string {
199
+ return `${relative(this.root, node.getSourceFile().fileName).replaceAll("\\", "/")}:${node.getStart()}:${name}`;
200
+ }
106
201
 
107
- argument(node: ts.TypeNode, environment: TypeEnvironment): TypeArgument {
108
- if (ts.isTypeReferenceNode(node)) {
109
- const bound = environment.get(this.symbol(node.typeName));
110
- if (bound && !node.typeArguments?.length) return bound;
111
- }
112
- // `(typeof table)["length"]` or `typeof table.length` has the literal type of an `as const` table.
113
- const queried =
114
- ts.isIndexedAccessTypeNode(node) || ts.isTypeQueryNode(node)
115
- ? this.checker.getTypeFromTypeNode(node)
116
- : undefined;
117
- const text = queried?.isNumberLiteral()
118
- ? String(queried.value)
119
- : ts.isLiteralTypeNode(node) &&
120
- (ts.isNumericLiteral(node.literal) || ts.isPrefixUnaryExpression(node.literal))
121
- ? node.literal.getText()
122
- : undefined;
123
- if (text !== undefined) {
124
- let value: bigint;
125
- try {
126
- value = parseInteger(text);
127
- } catch {
128
- this.fail(node, "PLC2001", "Layout arguments must be exact integer literals.");
129
- }
130
- if (value < -2147483648n || value > 2147483647n)
131
- this.fail(node, "PLC2001", "Layout argument is outside signed DINT range.");
132
- return { kind: "integer", value: Number(value) };
133
- }
134
- return { kind: "type", value: this.resolve(node, environment) };
135
- }
202
+ argument(node: ts.TypeNode, environment: TypeEnvironment): TypeArgument {
203
+ if (ts.isTypeReferenceNode(node)) {
204
+ const bound = environment.get(this.symbol(node.typeName));
205
+ if (bound && !node.typeArguments?.length) {
206
+ return bound;
207
+ }
208
+ }
209
+ // `(typeof table)["length"]` or `typeof table.length` has the literal type of an `as const` table.
210
+ const queried =
211
+ ts.isIndexedAccessTypeNode(node) || ts.isTypeQueryNode(node)
212
+ ? this.checker.getTypeFromTypeNode(node)
213
+ : undefined;
214
+ const text = queried?.isNumberLiteral()
215
+ ? String(queried.value)
216
+ : numericLiteralTypeText(node);
217
+ if (text !== undefined) {
218
+ let value: bigint;
219
+ try {
220
+ value = parseInteger(text);
221
+ } catch {
222
+ this.fail(
223
+ node,
224
+ "PLC2001",
225
+ "Layout arguments must be exact integer literals.",
226
+ );
227
+ }
228
+ if (value < firstIndex || value > lastIndex) {
229
+ this.fail(
230
+ node,
231
+ "PLC2001",
232
+ "Layout argument is outside signed DINT range.",
233
+ );
234
+ }
235
+ return { kind: "integer", value: Number(value) };
236
+ }
237
+ return { kind: "type", value: this.resolve(node, environment) };
238
+ }
136
239
 
137
- bindings(
138
- parameters: readonly ts.TypeParameterDeclaration[] | undefined,
139
- arguments_: readonly ts.TypeNode[] | undefined,
140
- outer: TypeEnvironment,
141
- node: ts.Node,
142
- ): Map<ts.Symbol, TypeArgument> {
143
- const result = new Map(outer),
144
- params = parameters ?? [],
145
- args = arguments_ ?? [];
146
- if (args.length > params.length)
147
- this.fail(node, "PLC2001", "Too many concrete type arguments.");
148
- params.forEach((parameter, index) => {
149
- const argument = args[index] ?? parameter.default;
150
- if (!argument)
151
- this.fail(
152
- node,
153
- "PLC2001",
154
- "Generic PLC declarations require explicit concrete type arguments.",
155
- );
156
- result.set(this.symbol(parameter.name), this.argument(argument, result));
157
- });
158
- return result;
159
- }
240
+ bindings(
241
+ parameters: readonly ts.TypeParameterDeclaration[] | undefined,
242
+ arguments_: readonly ts.TypeNode[] | undefined,
243
+ outer: TypeEnvironment,
244
+ node: ts.Node,
245
+ ): Map<ts.Symbol, TypeArgument> {
246
+ const result = new Map(outer);
247
+ const params = parameters ?? [];
248
+ const args = arguments_ ?? [];
249
+ if (args.length > params.length) {
250
+ this.fail(node, "PLC2001", "Too many concrete type arguments.");
251
+ }
252
+ params.forEach((parameter, index) => {
253
+ const argument = args[index] ?? parameter.default;
254
+ if (!argument) {
255
+ this.fail(
256
+ node,
257
+ "PLC2001",
258
+ "Generic PLC declarations require explicit concrete type arguments.",
259
+ );
260
+ }
261
+ result.set(this.symbol(parameter.name), this.argument(argument, result));
262
+ });
263
+ return result;
264
+ }
160
265
 
161
- resolve(node: ts.TypeNode, environment: TypeEnvironment = new Map()): ResolvedType {
162
- if (node.kind === ts.SyntaxKind.BooleanKeyword) return { type: "BOOL" };
163
- if (node.kind === ts.SyntaxKind.NumberKeyword) return { type: "DINT" };
164
- if (node.kind === ts.SyntaxKind.StringKeyword) {
165
- const id = "STRING<80>";
166
- this.types.set(id, { id, kind: "string", capacity: 80, encoding: "utf8" });
167
- return { type: id };
168
- }
169
- if (ts.isParenthesizedTypeNode(node)) return this.resolve(node.type, environment);
170
- if (ts.isTypeLiteralNode(node)) {
171
- // Environment keys are admitted, declared type parameters with concrete bindings.
172
- const arguments_ = [...environment]
173
- .map(
174
- ([symbol, value]) =>
175
- `${this.id(symbol.declarations![0]!, symbol.name)}=${this.key(value)}`,
176
- )
177
- .sort()
178
- .join(",");
179
- return this.record(
180
- node,
181
- `${this.id(node, "record")}${arguments_ ? `<${arguments_}>` : ""}`,
182
- node.members,
183
- environment,
184
- );
185
- }
186
- if (ts.isUnionTypeNode(node)) return this.union(node, this.id(node, "Union"), environment);
187
- if (ts.isIndexedAccessTypeNode(node)) {
188
- const record = this.serviceRecord?.(this.checker.getTypeFromTypeNode(node));
189
- if (record) return this.declaration(record, undefined, environment, node);
190
- }
191
- if (!ts.isTypeReferenceNode(node))
192
- this.fail(
193
- node,
194
- "PLC2001",
195
- "Use an explicit supported PLC type; optional and dynamic layouts are unsupported.",
196
- );
197
- const symbol = this.symbol(node.typeName),
198
- bound = environment.get(symbol);
199
- if (bound) {
200
- if (bound.kind !== "type" || node.typeArguments?.length)
201
- this.fail(node, "PLC2001", "An integer layout argument is not a storage type.");
202
- return bound.value;
203
- }
204
- const official = this.sdkName(node.typeName);
205
- const block =
206
- this.blockTypes.get(symbol) ?? (official ? this.standardTypes.get(official) : undefined);
207
- if (block) {
208
- if (node.typeArguments?.length)
209
- this.fail(
210
- node,
211
- "PLC2001",
212
- "Function block classes are concrete and take no type arguments.",
213
- );
214
- return { type: block };
215
- }
216
- if (official === "InOut") {
217
- if (node.typeArguments?.length !== 1)
218
- this.fail(node, "PLC2001", "InOut requires one concrete value type.");
219
- const inner = this.resolve(node.typeArguments[0]!, environment);
220
- if (inner.io || !this.isValue(inner))
221
- this.fail(node, "PLC2001", "InOut cannot nest or borrow a block instance.");
222
- return { type: inner.type, mode: "inOut" };
223
- }
224
- if (official && this.types.has(official)) {
225
- if (node.typeArguments?.length)
226
- this.fail(node, "PLC2001", "Scalar types take no type arguments.");
227
- return { type: official };
228
- }
229
- if (official === "Input" || official === "Output") {
230
- if (node.typeArguments?.length !== 1)
231
- this.fail(node, "PLC2001", "I/O types need exactly one PLC type argument.");
232
- const inner = this.resolve(node.typeArguments[0]!, environment);
233
- if (inner.io || inner.mode || this.hasReferences(inner.type))
234
- this.fail(node, "PLC2001", "I/O type wrappers cannot be nested.");
235
- return { type: inner.type, io: official === "Input" ? "input" : "output" };
236
- }
237
- if (official === "FixedArray") {
238
- const args = node.typeArguments;
239
- if (!args || args.length < 2 || args.length > 3)
240
- this.fail(node, "PLC2001", "FixedArray needs element, length and optional lower bound.");
241
- return this.fixedArray(
242
- node,
243
- this.resolve(args[0]!, environment),
244
- this.argument(args[1]!, environment),
245
- args[2] ? this.argument(args[2], environment) : { kind: "integer", value: 0 },
246
- );
247
- }
248
- // TypeScript's own `Record`; its keys are a contiguous enum.
249
- if (symbol.name === "Record" && this.standardLibrary(symbol)) {
250
- const [key, value] = node.typeArguments ?? [];
251
- const index =
252
- key && ts.isTypeReferenceNode(key)
253
- ? this.types.get(this.resolve(key, environment).type)
254
- : undefined;
255
- if (index?.kind !== "enum")
256
- this.fail(
257
- node,
258
- "PLC2001",
259
- "Record keys must be a numeric PLC enum; dynamic index signatures are unsupported.",
260
- );
261
- const values = index.members.map((member) => Number(member.value));
262
- const lower = Math.min(...values);
263
- if (Math.max(...values) - lower + 1 !== values.length)
264
- this.fail(node, "PLC2001", "Record<Enum, T> needs enum member values without gaps.");
265
- const element = this.resolve(value!, environment);
266
- if (element.io || !this.isValue(element))
267
- this.fail(node, "PLC2001", "Enum-keyed records need a plain value element.");
268
- const id = `array<${element.type},${values.length},${lower},${index.id}>`;
269
- this.types.set(id, {
270
- id,
271
- kind: "array",
272
- element: element.type,
273
- length: values.length,
274
- lowerBound: lower,
275
- index: index.id,
276
- });
277
- this.checkSize(id, node);
278
- return { type: id };
279
- }
280
- if (official === "STRING" || official === "WSTRING") {
281
- if (node.typeArguments?.length !== 1)
282
- this.fail(node, "PLC2001", "Bounded strings require one capacity argument.");
283
- const capacity = this.argument(node.typeArguments[0]!, environment);
284
- if (capacity.kind !== "integer" || capacity.value < 1 || capacity.value > 65535)
285
- this.fail(node, "PLC2001", "String capacity must be 1..65535.");
286
- const id = `${official}<${capacity.value}>`;
287
- this.types.set(id, {
288
- id,
289
- kind: "string",
290
- capacity: capacity.value,
291
- encoding: official === "STRING" ? "utf8" : "utf16",
292
- });
293
- return { type: id };
294
- }
295
- return this.declaration(symbol, node.typeArguments, environment, node);
296
- }
266
+ resolve(
267
+ node: ts.TypeNode,
268
+ environment: TypeEnvironment = new Map(),
269
+ ): ResolvedType {
270
+ if (node.kind === ts.SyntaxKind.BooleanKeyword) {
271
+ return { type: "BOOL" };
272
+ }
273
+ if (node.kind === ts.SyntaxKind.NumberKeyword) {
274
+ return { type: "DINT" };
275
+ }
276
+ if (node.kind === ts.SyntaxKind.StringKeyword) {
277
+ const id = "STRING<80>";
278
+ this.types.set(id, {
279
+ id,
280
+ kind: "string",
281
+ capacity: 80,
282
+ encoding: "utf8",
283
+ });
284
+ return { type: id };
285
+ }
286
+ if (ts.isParenthesizedTypeNode(node)) {
287
+ return this.resolve(node.type, environment);
288
+ }
289
+ if (ts.isTypeLiteralNode(node)) {
290
+ // Environment keys are admitted, declared type parameters with concrete bindings.
291
+ const arguments_ = [...environment]
292
+ .map(
293
+ ([symbol, value]) =>
294
+ `${this.id(symbol.declarations![0]!, symbol.name)}=${this.key(value)}`,
295
+ )
296
+ .sort()
297
+ .join(",");
298
+ return this.record(
299
+ node,
300
+ `${this.id(node, "record")}${arguments_ ? `<${arguments_}>` : ""}`,
301
+ node.members,
302
+ environment,
303
+ );
304
+ }
305
+ if (ts.isUnionTypeNode(node)) {
306
+ return this.union(node, this.id(node, "Union"), environment);
307
+ }
308
+ if (ts.isIndexedAccessTypeNode(node)) {
309
+ const record = this.serviceRecord?.(
310
+ this.checker.getTypeFromTypeNode(node),
311
+ );
312
+ if (record) {
313
+ return this.declaration(record, undefined, environment, node);
314
+ }
315
+ }
316
+ if (!ts.isTypeReferenceNode(node)) {
317
+ this.fail(
318
+ node,
319
+ "PLC2001",
320
+ "Use an explicit supported PLC type; optional and dynamic layouts are unsupported.",
321
+ );
322
+ }
323
+ const symbol = this.symbol(node.typeName);
324
+ const bound = environment.get(symbol);
325
+ if (bound) {
326
+ if (bound.kind !== "type" || node.typeArguments?.length) {
327
+ this.fail(
328
+ node,
329
+ "PLC2001",
330
+ "An integer layout argument is not a storage type.",
331
+ );
332
+ }
333
+ return bound.value;
334
+ }
335
+ const official = this.sdkName(node.typeName);
336
+ const block =
337
+ this.blockTypes.get(symbol) ??
338
+ (official ? this.standardTypes.get(official) : undefined);
339
+ if (block) {
340
+ if (node.typeArguments?.length) {
341
+ this.fail(
342
+ node,
343
+ "PLC2001",
344
+ "Function block classes are concrete and take no type arguments.",
345
+ );
346
+ }
347
+ return { type: block };
348
+ }
349
+ if (official === "InOut") {
350
+ if (node.typeArguments?.length !== 1) {
351
+ this.fail(node, "PLC2001", "InOut requires one concrete value type.");
352
+ }
353
+ const inner = this.resolve(node.typeArguments[0]!, environment);
354
+ if (inner.io || !this.isValue(inner)) {
355
+ this.fail(
356
+ node,
357
+ "PLC2001",
358
+ "InOut cannot nest or borrow a block instance.",
359
+ );
360
+ }
361
+ return { type: inner.type, mode: "inOut" };
362
+ }
363
+ if (official && this.types.has(official)) {
364
+ if (node.typeArguments?.length) {
365
+ this.fail(node, "PLC2001", "Scalar types take no type arguments.");
366
+ }
367
+ return { type: official };
368
+ }
369
+ if (official === "Input" || official === "Output") {
370
+ if (node.typeArguments?.length !== 1) {
371
+ this.fail(
372
+ node,
373
+ "PLC2001",
374
+ "I/O types need exactly one PLC type argument.",
375
+ );
376
+ }
377
+ const inner = this.resolve(node.typeArguments[0]!, environment);
378
+ if (inner.io || inner.mode || this.hasReferences(inner.type)) {
379
+ this.fail(node, "PLC2001", "I/O type wrappers cannot be nested.");
380
+ }
381
+ return {
382
+ type: inner.type,
383
+ io: official === "Input" ? "input" : "output",
384
+ };
385
+ }
386
+ if (official === "FixedArray") {
387
+ const args = node.typeArguments;
388
+ if (!args || args.length < 2 || args.length > 3) {
389
+ this.fail(
390
+ node,
391
+ "PLC2001",
392
+ "FixedArray needs element, length and optional lower bound.",
393
+ );
394
+ }
395
+ return this.fixedArray(
396
+ node,
397
+ this.resolve(args[0]!, environment),
398
+ this.argument(args[1]!, environment),
399
+ args[2]
400
+ ? this.argument(args[2], environment)
401
+ : { kind: "integer", value: 0 },
402
+ );
403
+ }
404
+ // TypeScript's own `Record`; its keys are a contiguous enum.
405
+ if (symbol.name === "Record" && this.standardLibrary(symbol)) {
406
+ const [key, value] = node.typeArguments ?? [];
407
+ const index =
408
+ key && ts.isTypeReferenceNode(key)
409
+ ? this.types.get(this.resolve(key, environment).type)
410
+ : undefined;
411
+ if (index?.kind !== "enum") {
412
+ this.fail(
413
+ node,
414
+ "PLC2001",
415
+ "Record keys must be a numeric PLC enum; dynamic index signatures are unsupported.",
416
+ );
417
+ }
418
+ const values = index.members.map((member) => Number(member.value));
419
+ const lower = Math.min(...values);
420
+ if (Math.max(...values) - lower + 1 !== values.length) {
421
+ this.fail(
422
+ node,
423
+ "PLC2001",
424
+ "Record<Enum, T> needs enum member values without gaps.",
425
+ );
426
+ }
427
+ const element = this.resolve(value!, environment);
428
+ if (element.io || !this.isValue(element)) {
429
+ this.fail(
430
+ node,
431
+ "PLC2001",
432
+ "Enum-keyed records need a plain value element.",
433
+ );
434
+ }
435
+ const id = `array<${element.type},${values.length},${lower},${index.id}>`;
436
+ this.types.set(id, {
437
+ id,
438
+ kind: "array",
439
+ element: element.type,
440
+ length: values.length,
441
+ lowerBound: lower,
442
+ index: index.id,
443
+ });
444
+ this.checkSize(id, node);
445
+ return { type: id };
446
+ }
447
+ if (official === "STRING" || official === "WSTRING") {
448
+ if (node.typeArguments?.length !== 1) {
449
+ this.fail(
450
+ node,
451
+ "PLC2001",
452
+ "Bounded strings require one capacity argument.",
453
+ );
454
+ }
455
+ const capacity = this.argument(node.typeArguments[0]!, environment);
456
+ if (
457
+ capacity.kind !== "integer" ||
458
+ capacity.value < 1 ||
459
+ capacity.value > 65535
460
+ ) {
461
+ this.fail(node, "PLC2001", "String capacity must be 1..65535.");
462
+ }
463
+ const id = `${official}<${capacity.value}>`;
464
+ this.types.set(id, {
465
+ id,
466
+ kind: "string",
467
+ capacity: capacity.value,
468
+ encoding: official === "STRING" ? "utf8" : "utf16",
469
+ });
470
+ return { type: id };
471
+ }
472
+ return this.declaration(symbol, node.typeArguments, environment, node);
473
+ }
297
474
 
298
- fixedArray(
299
- node: ts.Node,
300
- element: ResolvedType,
301
- length: TypeArgument,
302
- lower: TypeArgument,
303
- ): ResolvedType {
304
- if (
305
- element.io ||
306
- !(this.isValue(element) || this.types.get(element.type)?.kind === "block") ||
307
- length.kind !== "integer" ||
308
- lower.kind !== "integer" ||
309
- length.value < 1 ||
310
- length.value > 1_000_000 ||
311
- lower.value + length.value - 1 > 2147483647
312
- )
313
- this.fail(
314
- node,
315
- "PLC2001",
316
- "Fixed arrays need a supported element, positive bounded length and signed DINT bounds.",
317
- );
318
- const id = `array<${element.type},${length.value},${lower.value}>`;
319
- this.types.set(id, {
320
- id,
321
- kind: "array",
322
- element: element.type,
323
- length: length.value,
324
- lowerBound: lower.value,
325
- });
326
- this.checkSize(id, node);
327
- return { type: id };
328
- }
475
+ fixedArray(
476
+ node: ts.Node,
477
+ element: ResolvedType,
478
+ length: TypeArgument,
479
+ lower: TypeArgument,
480
+ ): ResolvedType {
481
+ if (
482
+ element.io ||
483
+ !(
484
+ this.isValue(element) || this.types.get(element.type)?.kind === "block"
485
+ ) ||
486
+ length.kind !== "integer" ||
487
+ lower.kind !== "integer" ||
488
+ length.value < 1 ||
489
+ length.value > maxScalarElements ||
490
+ BigInt(lower.value + length.value - 1) > lastIndex
491
+ ) {
492
+ this.fail(
493
+ node,
494
+ "PLC2001",
495
+ "Fixed arrays need a supported element, positive bounded length and signed DINT bounds.",
496
+ );
497
+ }
498
+ const id = `array<${element.type},${length.value},${lower.value}>`;
499
+ this.types.set(id, {
500
+ id,
501
+ kind: "array",
502
+ element: element.type,
503
+ length: length.value,
504
+ lowerBound: lower.value,
505
+ });
506
+ this.checkSize(id, node);
507
+ return { type: id };
508
+ }
329
509
 
330
- private declaration(
331
- symbol: ts.Symbol,
332
- arguments_: readonly ts.TypeNode[] | undefined,
333
- environment: TypeEnvironment,
334
- node: ts.Node,
335
- ): ResolvedType {
336
- const declarations = symbol.declarations ?? [];
337
- if (declarations.filter(ts.isInterfaceDeclaration).length > 1)
338
- this.fail(
339
- node,
340
- "PLC2001",
341
- "Interface declaration merging is unsupported; use one closed layout declaration.",
342
- );
343
- const declaration = declarations.find(
344
- (item) =>
345
- ts.isTypeAliasDeclaration(item) ||
346
- ts.isInterfaceDeclaration(item) ||
347
- ts.isEnumDeclaration(item),
348
- );
349
- if (!declaration)
350
- this.fail(node, "PLC2001", "This type is not implemented by the PLC frontend.");
351
- if (ts.isEnumDeclaration(declaration)) {
352
- if (arguments_?.length) this.fail(node, "PLC2001", "Enums take no type arguments.");
353
- return this.enumeration(declaration);
354
- }
355
- const bindings = this.bindings(declaration.typeParameters, arguments_, environment, node);
356
- const suffix = (declaration.typeParameters ?? [])
357
- .map((parameter) => this.key(bindings.get(this.symbol(parameter.name))!))
358
- .join(",");
359
- const id = `${this.id(declaration, declaration.name.text)}${suffix ? `<${suffix}>` : ""}`;
360
- if (this.active.has(id))
361
- this.fail(node, "PLC2001", "Recursive by-value PLC layouts are unsupported.");
362
- if (this.types.has(id)) return { type: id };
363
- if (this.active.size >= 64)
364
- this.fail(
365
- node,
366
- "PLC2001",
367
- "Type substitution exceeds 64 levels; recursive expansion is unsupported.",
368
- );
369
- this.active.add(id);
370
- try {
371
- if (ts.isTypeAliasDeclaration(declaration)) {
372
- if (ts.isTypeLiteralNode(declaration.type))
373
- return this.record(declaration, id, declaration.type.members, bindings);
374
- if (ts.isUnionTypeNode(declaration.type)) return this.union(declaration.type, id, bindings);
375
- return this.resolve(declaration.type, bindings);
376
- }
377
- const inherited: Field[] = [];
378
- for (const heritage of declaration.heritageClauses ?? []) {
379
- for (const base of heritage.types) {
380
- const baseSymbol = this.symbol(base.expression);
381
- const baseType = this.declaration(baseSymbol, base.typeArguments, bindings, base);
382
- const layout = this.types.get(baseType.type);
383
- if (layout?.kind !== "record")
384
- this.fail(base, "PLC2001", "Inherited layout must be a record.");
385
- inherited.push(...layout.fields);
386
- }
387
- }
388
- return this.record(declaration, id, declaration.members, bindings, inherited);
389
- } finally {
390
- this.active.delete(id);
391
- }
392
- }
393
- // Specialization identity includes I/O and InOut modes: equal value widths alone
394
- // must not merge a readonly value parameter with a mutable borrowed input.
395
- key(argument: TypeArgument): string {
396
- if (argument.kind === "integer") return String(argument.value);
397
- const { type, io, mode } = argument.value;
398
- return `${type}${io ? `:${io}` : ""}${mode ? `:${mode}` : ""}`;
399
- }
510
+ private declaration(
511
+ symbol: ts.Symbol,
512
+ arguments_: readonly ts.TypeNode[] | undefined,
513
+ environment: TypeEnvironment,
514
+ node: ts.Node,
515
+ ): ResolvedType {
516
+ const declarations = symbol.declarations ?? [];
517
+ if (declarations.filter(ts.isInterfaceDeclaration).length > 1) {
518
+ this.fail(
519
+ node,
520
+ "PLC2001",
521
+ "Interface declaration merging is unsupported; use one closed layout declaration.",
522
+ );
523
+ }
524
+ const declaration = declarations.find(
525
+ (item) =>
526
+ ts.isTypeAliasDeclaration(item) ||
527
+ ts.isInterfaceDeclaration(item) ||
528
+ ts.isEnumDeclaration(item),
529
+ );
530
+ if (!declaration) {
531
+ this.fail(
532
+ node,
533
+ "PLC2001",
534
+ "This type is not implemented by the PLC frontend.",
535
+ );
536
+ }
537
+ if (ts.isEnumDeclaration(declaration)) {
538
+ if (arguments_?.length) {
539
+ this.fail(node, "PLC2001", "Enums take no type arguments.");
540
+ }
541
+ return this.enumeration(declaration);
542
+ }
543
+ const bindings = this.bindings(
544
+ declaration.typeParameters,
545
+ arguments_,
546
+ environment,
547
+ node,
548
+ );
549
+ const suffix = (declaration.typeParameters ?? [])
550
+ .map((parameter) => this.key(bindings.get(this.symbol(parameter.name))!))
551
+ .join(",");
552
+ const id = `${this.id(declaration, declaration.name.text)}${suffix ? `<${suffix}>` : ""}`;
553
+ if (this.active.has(id)) {
554
+ this.fail(
555
+ node,
556
+ "PLC2001",
557
+ "Recursive by-value PLC layouts are unsupported.",
558
+ );
559
+ }
560
+ if (this.types.has(id)) {
561
+ return { type: id };
562
+ }
563
+ if (this.active.size >= 64) {
564
+ this.fail(
565
+ node,
566
+ "PLC2001",
567
+ "Type substitution exceeds 64 levels; recursive expansion is unsupported.",
568
+ );
569
+ }
570
+ this.active.add(id);
571
+ try {
572
+ if (ts.isTypeAliasDeclaration(declaration)) {
573
+ if (ts.isTypeLiteralNode(declaration.type)) {
574
+ return this.record(
575
+ declaration,
576
+ id,
577
+ declaration.type.members,
578
+ bindings,
579
+ );
580
+ }
581
+ if (ts.isUnionTypeNode(declaration.type)) {
582
+ return this.union(declaration.type, id, bindings);
583
+ }
584
+ return this.resolve(declaration.type, bindings);
585
+ }
586
+ const inherited: Field[] = [];
587
+ for (const heritage of declaration.heritageClauses ?? []) {
588
+ for (const base of heritage.types) {
589
+ const baseSymbol = this.symbol(base.expression);
590
+ const baseType = this.declaration(
591
+ baseSymbol,
592
+ base.typeArguments,
593
+ bindings,
594
+ base,
595
+ );
596
+ const layout = this.types.get(baseType.type);
597
+ if (layout?.kind !== "record") {
598
+ this.fail(base, "PLC2001", "Inherited layout must be a record.");
599
+ }
600
+ inherited.push(...layout.fields);
601
+ }
602
+ }
603
+ return this.record(
604
+ declaration,
605
+ id,
606
+ declaration.members,
607
+ bindings,
608
+ inherited,
609
+ );
610
+ } finally {
611
+ this.active.delete(id);
612
+ }
613
+ }
614
+ // Specialization identity includes I/O and InOut modes: equal value widths alone
615
+ // must not merge a readonly value parameter with a mutable borrowed input.
616
+ key(argument: TypeArgument): string {
617
+ if (argument.kind === "integer") {
618
+ return String(argument.value);
619
+ }
620
+ const { type, io, mode } = argument.value;
621
+ return `${type}${io ? `:${io}` : ""}${mode ? `:${mode}` : ""}`;
622
+ }
400
623
 
401
- /**
402
- * A discriminated union is one fixed layout: a `kind` enum plus the fields of every variant.
403
- * TypeScript's narrowing guards which fields a branch can read; a literal's unset fields are zero.
404
- */
405
- private union(node: ts.UnionTypeNode, id: string, environment: TypeEnvironment): ResolvedType {
406
- const fields = new Map<string, Field>();
407
- const kinds: string[] = [];
408
- for (const variant of node.types) {
409
- const members = ts.isTypeLiteralNode(variant) ? variant.members : undefined;
410
- const tag = members?.find(
411
- (member) => ts.isPropertySignature(member) && member.name.getText() === "kind",
412
- );
413
- const literal =
414
- tag && ts.isPropertySignature(tag) && tag.type && ts.isLiteralTypeNode(tag.type)
415
- ? tag.type.literal
416
- : undefined;
417
- if (
418
- !members ||
419
- !literal ||
420
- !ts.isStringLiteral(literal) ||
421
- !/^[A-Za-z]\w*$/.test(literal.text)
422
- )
423
- this.fail(
424
- variant,
425
- "PLC2001",
426
- 'Union variants are object types with an identifier string literal `kind`, such as { kind: "idle" }.',
427
- );
428
- if (kinds.includes(literal.text)) this.fail(variant, "PLC2001", "Duplicate union kind.");
429
- kinds.push(literal.text);
430
- for (const field of this.fields(
431
- members.filter((member) => member !== tag),
432
- environment,
433
- )) {
434
- const existing = fields.get(field.name);
435
- if (existing && existing.type !== field.type)
436
- this.fail(
437
- variant,
438
- "PLC2001",
439
- "Union variants may share a field only with the same type.",
440
- );
441
- fields.set(field.name, field);
442
- }
443
- }
444
- const kindId = `${id}Kind`;
445
- this.types.set(kindId, {
446
- id: kindId,
447
- kind: "enum",
448
- base: "DINT",
449
- members: kinds.map((name, value) => ({ name, value: String(value) })),
450
- });
451
- this.types.set(id, {
452
- id,
453
- kind: "record",
454
- fields: [{ name: "kind", type: kindId, readonly: false }, ...fields.values()],
455
- });
456
- this.unions.add(id);
457
- this.checkSize(id, node);
458
- return { type: id };
459
- }
624
+ /**
625
+ * A discriminated union is one fixed layout: a `kind` enum plus the fields of every variant.
626
+ * TypeScript's narrowing guards which fields a branch can read; a literal's unset fields are zero.
627
+ */
628
+ private union(
629
+ node: ts.UnionTypeNode,
630
+ id: string,
631
+ environment: TypeEnvironment,
632
+ ): ResolvedType {
633
+ const fields = new Map<string, Field>();
634
+ const kinds: string[] = [];
635
+ for (const variant of node.types) {
636
+ const members = ts.isTypeLiteralNode(variant)
637
+ ? variant.members
638
+ : undefined;
639
+ const tag = members?.find(
640
+ (member) =>
641
+ ts.isPropertySignature(member) && member.name.getText() === "kind",
642
+ );
643
+ const literal =
644
+ tag &&
645
+ ts.isPropertySignature(tag) &&
646
+ tag.type &&
647
+ ts.isLiteralTypeNode(tag.type)
648
+ ? tag.type.literal
649
+ : undefined;
650
+ if (
651
+ !members ||
652
+ !literal ||
653
+ !ts.isStringLiteral(literal) ||
654
+ !/^[A-Za-z]\w*$/.test(literal.text)
655
+ ) {
656
+ this.fail(
657
+ variant,
658
+ "PLC2001",
659
+ 'Union variants are object types with an identifier string literal `kind`, such as { kind: "idle" }.',
660
+ );
661
+ }
662
+ if (kinds.includes(literal.text)) {
663
+ this.fail(variant, "PLC2001", "Duplicate union kind.");
664
+ }
665
+ kinds.push(literal.text);
666
+ for (const field of this.fields(
667
+ members.filter((member) => member !== tag),
668
+ environment,
669
+ )) {
670
+ const existing = fields.get(field.name);
671
+ if (existing && existing.type !== field.type) {
672
+ this.fail(
673
+ variant,
674
+ "PLC2001",
675
+ "Union variants may share a field only with the same type.",
676
+ );
677
+ }
678
+ fields.set(field.name, field);
679
+ }
680
+ }
681
+ const kindId = `${id}Kind`;
682
+ this.types.set(kindId, {
683
+ id: kindId,
684
+ kind: "enum",
685
+ base: "DINT",
686
+ members: kinds.map((name, value) => ({ name, value: String(value) })),
687
+ });
688
+ this.types.set(id, {
689
+ id,
690
+ kind: "record",
691
+ fields: [
692
+ { name: "kind", type: kindId, readonly: false },
693
+ ...fields.values(),
694
+ ],
695
+ });
696
+ this.unions.add(id);
697
+ this.checkSize(id, node);
698
+ return { type: id };
699
+ }
460
700
 
461
- private record(
462
- node: ts.Node,
463
- id: string,
464
- members: readonly ts.TypeElement[],
465
- environment: TypeEnvironment,
466
- inherited: readonly Field[] = [],
467
- ): ResolvedType {
468
- const fields = this.fields(members, environment, inherited);
469
- if (!fields.length) this.fail(node, "PLC2001", "PLC records require at least one field.");
470
- this.types.set(id, { id, kind: "record", fields });
471
- this.checkSize(id, node);
472
- return { type: id };
473
- }
701
+ private record(
702
+ node: ts.Node,
703
+ id: string,
704
+ members: readonly ts.TypeElement[],
705
+ environment: TypeEnvironment,
706
+ inherited: readonly Field[] = [],
707
+ ): ResolvedType {
708
+ const fields = this.fields(members, environment, inherited);
709
+ if (!fields.length) {
710
+ this.fail(node, "PLC2001", "PLC records require at least one field.");
711
+ }
712
+ this.types.set(id, { id, kind: "record", fields });
713
+ this.checkSize(id, node);
714
+ return { type: id };
715
+ }
474
716
 
475
- private fields(
476
- members: readonly ts.TypeElement[],
477
- environment: TypeEnvironment,
478
- inherited: readonly Field[] = [],
479
- ): Field[] {
480
- const fields = [...inherited],
481
- names = new Set(fields.map((field) => field.name));
482
- for (const member of members) {
483
- if (
484
- !ts.isPropertySignature(member) ||
485
- !member.type ||
486
- member.questionToken ||
487
- !member.name ||
488
- !ts.isIdentifier(member.name)
489
- )
490
- this.fail(
491
- member,
492
- "PLC2001",
493
- "PLC records have named, required, explicitly typed fields; methods and index signatures are unsupported.",
494
- );
495
- if (names.has(member.name.text)) this.fail(member, "PLC2001", "Duplicate record field.");
496
- const type = this.resolve(member.type, environment);
497
- if (instancedBlock(type.type, this.types))
498
- this.fail(
499
- member,
500
- "PLC2001",
501
- "Block instances belong in module or private block fields, not value records.",
502
- );
503
- if (type.io)
504
- this.fail(
505
- member,
506
- "PLC2001",
507
- "Logical I/O wrappers belong on ambient bindings, not fields.",
508
- );
509
- fields.push({
510
- name: member.name.text,
511
- type: type.type,
512
- ...(type.mode && { mode: type.mode }),
513
- readonly: Boolean(
514
- member.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword),
515
- ),
516
- });
517
- names.add(member.name.text);
518
- }
519
- return fields;
520
- }
717
+ private fields(
718
+ members: readonly ts.TypeElement[],
719
+ environment: TypeEnvironment,
720
+ inherited: readonly Field[] = [],
721
+ ): Field[] {
722
+ const fields = [...inherited];
723
+ const names = new Set(fields.map((field) => field.name));
724
+ for (const member of members) {
725
+ if (
726
+ !ts.isPropertySignature(member) ||
727
+ !member.type ||
728
+ member.questionToken ||
729
+ !member.name ||
730
+ !ts.isIdentifier(member.name)
731
+ ) {
732
+ this.fail(
733
+ member,
734
+ "PLC2001",
735
+ "PLC records have named, required, explicitly typed fields; methods and index signatures are unsupported.",
736
+ );
737
+ }
738
+ if (names.has(member.name.text)) {
739
+ this.fail(member, "PLC2001", "Duplicate record field.");
740
+ }
741
+ const type = this.resolve(member.type, environment);
742
+ if (instancedBlock(type.type, this.types)) {
743
+ this.fail(
744
+ member,
745
+ "PLC2001",
746
+ "Block instances belong in module or private block fields, not value records.",
747
+ );
748
+ }
749
+ if (type.io) {
750
+ this.fail(
751
+ member,
752
+ "PLC2001",
753
+ "Logical I/O wrappers belong on ambient bindings, not fields.",
754
+ );
755
+ }
756
+ fields.push({
757
+ name: member.name.text,
758
+ type: type.type,
759
+ ...(type.mode && { mode: type.mode }),
760
+ readonly: Boolean(
761
+ member.modifiers?.some(
762
+ (modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword,
763
+ ),
764
+ ),
765
+ });
766
+ names.add(member.name.text);
767
+ }
768
+ return fields;
769
+ }
521
770
 
522
- inputFields(node: ts.TypeNode): readonly Field[] {
523
- if (ts.isTypeLiteralNode(node) && !node.members.length) return [];
524
- const resolved = this.resolve(node),
525
- type = this.types.get(resolved.type);
526
- if (resolved.io || resolved.mode || type?.kind !== "record")
527
- this.fail(node, "PLC2001", "Block inputs require one closed record schema.");
528
- if (type.fields.some((field) => this.hasReferences(field.type)))
529
- this.fail(node, "PLC2001", "InOut belongs directly on input fields, not nested records.");
530
- return type.fields;
531
- }
771
+ inputFields(node: ts.TypeNode): readonly Field[] {
772
+ if (ts.isTypeLiteralNode(node) && !node.members.length) {
773
+ return [];
774
+ }
775
+ const resolved = this.resolve(node);
776
+ const type = this.types.get(resolved.type);
777
+ if (resolved.io || resolved.mode || type?.kind !== "record") {
778
+ this.fail(
779
+ node,
780
+ "PLC2001",
781
+ "Block inputs require one closed record schema.",
782
+ );
783
+ }
784
+ if (type.fields.some((field) => this.hasReferences(field.type))) {
785
+ this.fail(
786
+ node,
787
+ "PLC2001",
788
+ "InOut belongs directly on input fields, not nested records.",
789
+ );
790
+ }
791
+ return type.fields;
792
+ }
532
793
 
533
- // A plain value layout: no InOut borrow, nested borrow schema or block instance.
534
- isValue(resolved: ResolvedType): boolean {
535
- return (
536
- !resolved.mode &&
537
- !this.hasReferences(resolved.type) &&
538
- !instancedBlock(resolved.type, this.types)
539
- );
540
- }
794
+ // A plain value layout: no InOut borrow, nested borrow schema or block instance.
795
+ isValue(resolved: ResolvedType): boolean {
796
+ return (
797
+ !resolved.mode &&
798
+ !this.hasReferences(resolved.type) &&
799
+ !instancedBlock(resolved.type, this.types)
800
+ );
801
+ }
541
802
 
542
- hasReferences(id: string, seen = new Set<string>()): boolean {
543
- if (seen.has(id)) return false;
544
- seen.add(id);
545
- const type = this.types.get(id);
546
- return type?.kind === "record"
547
- ? type.fields.some((field) => field.mode || this.hasReferences(field.type, seen))
548
- : type?.kind === "array"
549
- ? this.hasReferences(type.element, seen)
550
- : false;
551
- }
803
+ hasReferences(id: string, seen = new Set<string>()): boolean {
804
+ if (seen.has(id)) {
805
+ return false;
806
+ }
807
+ seen.add(id);
808
+ const type = this.types.get(id);
809
+ if (type?.kind === "record") {
810
+ return type.fields.some(
811
+ (field) => field.mode || this.hasReferences(field.type, seen),
812
+ );
813
+ }
814
+ return type?.kind === "array" && this.hasReferences(type.element, seen);
815
+ }
552
816
 
553
- enumeration(node: ts.EnumDeclaration): ResolvedType {
554
- const id = this.id(node, node.name.text);
555
- if (this.types.has(id)) return { type: id };
556
- if (!node.members.length) this.fail(node, "PLC2001", "PLC enums cannot be empty.");
557
- const members = node.members.map((member) => {
558
- if (!ts.isIdentifier(member.name))
559
- this.fail(member, "PLC2001", "Enum members require identifier names.");
560
- const value = this.checker.getConstantValue(member);
561
- if (
562
- typeof value !== "number" ||
563
- !Number.isInteger(value) ||
564
- value < -2147483648 ||
565
- value > 2147483647
566
- )
567
- this.fail(member, "PLC2001", "PLC enum values must be compile-time DINT integers.");
568
- return { name: member.name.text, value: String(value) };
569
- });
570
- if (new Set(members.map((member) => member.value)).size !== members.length)
571
- this.fail(node, "PLC2001", "PLC enum members require distinct values.");
572
- this.types.set(id, { id, kind: "enum", base: "DINT", members });
573
- return { type: id };
574
- }
817
+ enumeration(node: ts.EnumDeclaration): ResolvedType {
818
+ const id = this.id(node, node.name.text);
819
+ if (this.types.has(id)) {
820
+ return { type: id };
821
+ }
822
+ if (!node.members.length) {
823
+ this.fail(node, "PLC2001", "PLC enums cannot be empty.");
824
+ }
825
+ const members = node.members.map((member) => {
826
+ if (!ts.isIdentifier(member.name)) {
827
+ this.fail(member, "PLC2001", "Enum members require identifier names.");
828
+ }
829
+ const value = this.checker.getConstantValue(member);
830
+ if (
831
+ typeof value !== "number" ||
832
+ !Number.isInteger(value) ||
833
+ BigInt(value) < lowestEnumValue ||
834
+ BigInt(value) > highestEnumValue
835
+ ) {
836
+ this.fail(
837
+ member,
838
+ "PLC2001",
839
+ "PLC enum values must be compile-time DINT integers.",
840
+ );
841
+ }
842
+ return { name: member.name.text, value: String(value) };
843
+ });
844
+ if (
845
+ new Set(members.map((member) => member.value)).size !== members.length
846
+ ) {
847
+ this.fail(node, "PLC2001", "PLC enum members require distinct values.");
848
+ }
849
+ this.types.set(id, { id, kind: "enum", base: "DINT", members });
850
+ return { type: id };
851
+ }
575
852
 
576
- private checkSize(id: string, node: ts.Node): void {
577
- const count = (typeId: string, depth: number): number => {
578
- if (depth > 64) this.fail(node, "PLC2001", "PLC layout nesting exceeds 64 levels.");
579
- const type = this.types.get(typeId)!;
580
- const size =
581
- type.kind === "array"
582
- ? type.length * count(type.element, depth + 1)
583
- : type.kind === "record"
584
- ? type.fields.reduce((total, field) => total + count(field.type, depth + 1), 0)
585
- : 1;
586
- if (size > 1_000_000)
587
- this.fail(node, "PLC2001", "PLC layout exceeds one million scalar elements.");
588
- return size;
589
- };
590
- count(id, 0);
591
- }
853
+ private checkSize(id: string, node: ts.Node): void {
854
+ const count = (typeId: string, depth: number): number => {
855
+ if (depth > maxNestingDepth) {
856
+ this.fail(
857
+ node,
858
+ "PLC2001",
859
+ `PLC layout nesting exceeds ${maxNestingDepth} levels.`,
860
+ );
861
+ }
862
+ const size = scalars(this.types.get(typeId)!, depth + 1);
863
+ if (size > maxScalarElements) {
864
+ this.fail(
865
+ node,
866
+ "PLC2001",
867
+ "PLC layout exceeds one million scalar elements.",
868
+ );
869
+ }
870
+ return size;
871
+ };
872
+ const scalars = (type: PlcType, depth: number): number => {
873
+ if (type.kind === "array") {
874
+ return type.length * count(type.element, depth);
875
+ }
876
+ if (type.kind === "record") {
877
+ return type.fields.reduce(
878
+ (total, field) => total + count(field.type, depth),
879
+ 0,
880
+ );
881
+ }
882
+ return 1;
883
+ };
884
+ count(id, 0);
885
+ }
592
886
  }