@tsplc/compiler 0.5.13 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -1,19 +1,31 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
- import { dirname, relative, resolve } from "node:path";
1
+ import { dirname } from "node:path";
3
2
  import {
3
+ aggregate,
4
4
  type Diagnostic,
5
5
  type Field,
6
6
  instancedBlock,
7
- type MathHelper,
7
+ isRadixLiteral,
8
+ layoutIssue,
8
9
  maxNestingDepth,
9
10
  maxScalarElements,
11
+ maxScalarElementsText,
12
+ maxStringCapacity,
10
13
  type PlcType,
11
14
  parseInteger,
15
+ pascalCase,
12
16
  primitiveTypes,
13
17
  } from "@tsplc/compiler/ir";
14
- import { elementaryType, integerRange } from "@tsplc/iec";
18
+ import { defaultStringLength, elementaryType, integerRange } from "@tsplc/iec";
19
+ import { generatedNamePattern } from "@tsplc/iec/st";
15
20
  import ts from "typescript";
16
- import { declaredBySdk, unaliased } from "./sdk";
21
+ import { modulePath } from "./lowering-key";
22
+ import {
23
+ declaredBySdk,
24
+ isTelemetryDeclaration,
25
+ telemetryMethods,
26
+ unaliased,
27
+ valueSymbol,
28
+ } from "./sdk";
17
29
 
18
30
  export interface ResolvedType {
19
31
  type: string;
@@ -26,12 +38,11 @@ export type TypeArgument =
26
38
  export type TypeEnvironment = ReadonlyMap<ts.Symbol, TypeArgument>;
27
39
  export type Fail = (node: ts.Node, code: string, message: string) => never;
28
40
 
29
- // Array bounds and indexes are DINT, and so is every integer a layout takes as an argument.
30
- const [firstIndex, lastIndex] = integerRange(elementaryType("DINT"));
31
- // PLC enums have a DINT base.
32
- const [lowestEnumValue, highestEnumValue] = integerRange(
33
- elementaryType("DINT"),
34
- );
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;
35
46
 
36
47
  /** What a Fail throws: one diagnostic that abandons the declaration or routine being analyzed. */
37
48
  export class SemanticError extends Error {
@@ -40,17 +51,111 @@ export class SemanticError extends Error {
40
51
  }
41
52
  }
42
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
+
43
61
  // The PLC type of an unannotated numeric literal: `number` means DINT unless it is fractional.
44
62
  export const numericLiteralType = (text: string) => {
45
63
  if (text.endsWith("n")) {
46
- return "LINT";
64
+ return defaultNumericTypes.bigint;
47
65
  }
48
- return /[.e]/i.test(text) && !/^[-]?0[xob]/i.test(text) ? "LREAL" : "DINT";
66
+ return /[.e]/i.test(text) && !isRadixLiteral(text)
67
+ ? defaultNumericTypes.float
68
+ : defaultNumericTypes.number;
49
69
  };
50
70
 
51
- /** The expression inside any parentheses. */
52
- export const unparenthesized = (node: ts.Expression): ts.Expression =>
53
- ts.isParenthesizedExpression(node) ? unparenthesized(node.expression) : node;
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);
54
159
 
55
160
  // The source text of a numeric literal, negated literals included.
56
161
  export function numericLiteral(node: ts.Expression): string | undefined {
@@ -70,6 +175,29 @@ export function numericLiteral(node: ts.Expression): string | undefined {
70
175
  return undefined;
71
176
  }
72
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
+
73
201
  /** The text of a numeric literal type, such as `4` or `-1`. */
74
202
  const numericLiteralTypeText = (node: ts.TypeNode): string | undefined =>
75
203
  ts.isLiteralTypeNode(node) &&
@@ -93,6 +221,11 @@ export const hasModifier = (
93
221
  ): boolean =>
94
222
  Boolean(node.modifiers?.some((modifier) => modifier.kind === kind));
95
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
+
96
229
  /** `name: value` or shorthand `name` in an object literal; undefined for spreads, methods and computed names. */
97
230
  export function namedProperty(
98
231
  property: ts.ObjectLiteralElementLike,
@@ -114,42 +247,88 @@ export function namedProperty(
114
247
  };
115
248
  }
116
249
 
117
- const telemetryMethods = [
118
- "capture",
119
- "info",
120
- "warn",
121
- "error",
122
- "captureException",
123
- "text",
124
- ] as const;
125
250
  export type TelemetryMethod = (typeof telemetryMethods)[number];
126
251
 
127
- // This is the sole owner of TypeScript annotation substitution and PLC layouts.
128
- // The checker resolves declarations; it never supplies erased numeric widths.
129
- // Service records are the exception: `iec.*` schemas carry their widths as literal types.
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.
130
267
  export class TypeResolver {
131
- readonly types = new Map<string, PlcType>(
268
+ private readonly layouts = new Map<string, PlcType>(
132
269
  primitiveTypes.map((type) => [type.id, type]),
133
270
  );
134
- readonly blockTypes = new Map<ts.Symbol, string>();
135
- readonly standardTypes = new Map<string, string>();
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>();
136
274
  readonly unions = new Set<string>();
137
275
  private readonly active = new Set<string>();
276
+ /** Type literals' records by their fields. */
277
+ private readonly anonymousRecords = new Map<string, string>();
138
278
  constructor(
139
279
  private readonly checker: ts.TypeChecker,
140
280
  private readonly root: string,
141
281
  private readonly sdk: string,
142
282
  private readonly fail: Fail,
143
- /** The service client's struct for a type naming a called procedure's record. */
144
- private readonly serviceRecord?: (type: ts.Type) => ts.Symbol | undefined,
283
+ private readonly serviceRecord: ServiceRecord | null,
145
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. */
146
330
  symbol(node: ts.Node): ts.Symbol {
147
- // An object shorthand has a property symbol and a separate value binding.
148
- // PLC loads and intrinsic provenance must follow the value, including imports.
149
- const symbol =
150
- ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node
151
- ? this.checker.getShorthandAssignmentValueSymbol(node.parent)
152
- : this.checker.getSymbolAtLocation(node);
331
+ const symbol = valueSymbol(this.checker, node);
153
332
  if (!symbol) {
154
333
  this.fail(node, "PLC1002", "This name has no PLC declaration.");
155
334
  }
@@ -178,27 +357,62 @@ export class TypeResolver {
178
357
  return undefined;
179
358
  }
180
359
  const symbol = this.checker.getSymbolAtLocation(node.expression.name);
181
- const declared = symbol?.declarations?.some(
182
- (declaration) =>
183
- declaration.getSourceFile().fileName ===
184
- `${dirname(this.sdk)}/telemetry.d.ts`,
360
+ const declared = symbol?.declarations?.some((declaration) =>
361
+ isTelemetryDeclaration(this.sdk, declaration),
185
362
  );
186
363
  return declared
187
364
  ? telemetryMethods.find((name) => name === symbol?.name)
188
365
  : undefined;
189
366
  }
190
367
 
191
- /** `min`, `max` or `clamp` from the SDK's `@tsplc/compiler/math`. */
192
- mathHelper(node: ts.Node, name: string): MathHelper | undefined {
193
- return resolve(node.getSourceFile().fileName) ===
194
- resolve(dirname(this.sdk), "../stdlib/math.ts") &&
195
- (name === "min" || name === "max" || name === "clamp")
196
- ? name
197
- : undefined;
368
+ id(node: ts.Node, name: string): string {
369
+ return `${modulePath(this.root, node.getSourceFile().fileName)}:${node.getStart()}:${name}`;
198
370
  }
199
371
 
200
- id(node: ts.Node, name: string): string {
201
- return `${relative(this.root, node.getSourceFile().fileName).replaceAll("\\", "/")}:${node.getStart()}:${name}`;
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;
202
416
  }
203
417
 
204
418
  argument(node: ts.TypeNode, environment: TypeEnvironment): TypeArgument {
@@ -217,17 +431,14 @@ export class TypeResolver {
217
431
  ? String(queried.value)
218
432
  : numericLiteralTypeText(node);
219
433
  if (text !== undefined) {
220
- let value: bigint;
221
- try {
222
- value = parseInteger(text);
223
- } catch {
434
+ const value =
435
+ exactInteger(text) ??
224
436
  this.fail(
225
437
  node,
226
438
  "PLC2001",
227
439
  "Layout arguments must be exact integer literals.",
228
440
  );
229
- }
230
- if (value < firstIndex || value > lastIndex) {
441
+ if (value < lowestDint || value > highestDint) {
231
442
  this.fail(
232
443
  node,
233
444
  "PLC2001",
@@ -239,19 +450,23 @@ export class TypeResolver {
239
450
  return { kind: "type", value: this.resolve(node, environment) };
240
451
  }
241
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
+ */
242
457
  bindings(
243
458
  parameters: readonly ts.TypeParameterDeclaration[] | undefined,
244
459
  arguments_: readonly ts.TypeNode[] | undefined,
245
460
  outer: TypeEnvironment,
246
461
  node: ts.Node,
247
- ): Map<ts.Symbol, TypeArgument> {
248
- const result = new Map(outer);
462
+ ): { environment: TypeEnvironment; suffix: string } {
463
+ const environment = new Map(outer);
249
464
  const params = parameters ?? [];
250
465
  const args = arguments_ ?? [];
251
466
  if (args.length > params.length) {
252
467
  this.fail(node, "PLC2001", "Too many concrete type arguments.");
253
468
  }
254
- params.forEach((parameter, index) => {
469
+ const keys = params.map((parameter, index) => {
255
470
  const argument = args[index] ?? parameter.default;
256
471
  if (!argument) {
257
472
  this.fail(
@@ -260,9 +475,11 @@ export class TypeResolver {
260
475
  "Generic PLC declarations require explicit concrete type arguments.",
261
476
  );
262
477
  }
263
- result.set(this.symbol(parameter.name), this.argument(argument, result));
478
+ const value = this.argument(argument, environment);
479
+ environment.set(this.symbol(parameter.name), value);
480
+ return this.key(value);
264
481
  });
265
- return result;
482
+ return { environment, suffix: keys.join(",") };
266
483
  }
267
484
 
268
485
  resolve(
@@ -273,14 +490,14 @@ export class TypeResolver {
273
490
  return { type: "BOOL" };
274
491
  }
275
492
  if (node.kind === ts.SyntaxKind.NumberKeyword) {
276
- return { type: "DINT" };
493
+ return { type: defaultNumericTypes.number };
277
494
  }
278
495
  if (node.kind === ts.SyntaxKind.StringKeyword) {
279
- const id = "STRING<80>";
280
- this.types.set(id, {
496
+ const id = `STRING<${defaultStringLength}>`;
497
+ this.layouts.set(id, {
281
498
  id,
282
499
  kind: "string",
283
- capacity: 80,
500
+ capacity: defaultStringLength,
284
501
  encoding: "utf8",
285
502
  });
286
503
  return { type: id };
@@ -289,23 +506,10 @@ export class TypeResolver {
289
506
  return this.resolve(node.type, environment);
290
507
  }
291
508
  if (ts.isTypeLiteralNode(node)) {
292
- // Environment keys are admitted, declared type parameters with concrete bindings.
293
- const arguments_ = [...environment]
294
- .map(
295
- ([symbol, value]) =>
296
- `${this.id(symbol.declarations![0]!, symbol.name)}=${this.key(value)}`,
297
- )
298
- .sort()
299
- .join(",");
300
- return this.record(
301
- node,
302
- `${this.id(node, "record")}${arguments_ ? `<${arguments_}>` : ""}`,
303
- node.members,
304
- environment,
305
- );
509
+ return this.typeLiteral(node, environment);
306
510
  }
307
511
  if (ts.isUnionTypeNode(node)) {
308
- return this.union(node, this.id(node, "Union"), environment);
512
+ return this.union(node, this.inlineId(node, "Union", ""), environment);
309
513
  }
310
514
  if (ts.isIndexedAccessTypeNode(node)) {
311
515
  const record = this.serviceRecord?.(
@@ -349,10 +553,10 @@ export class TypeResolver {
349
553
  return { type: block };
350
554
  }
351
555
  if (official === "InOut") {
352
- if (node.typeArguments?.length !== 1) {
353
- this.fail(node, "PLC2001", "InOut requires one concrete value type.");
354
- }
355
- const inner = this.resolve(node.typeArguments[0]!, environment);
556
+ const inner = this.resolve(
557
+ this.soleTypeArgument(node, "InOut requires one concrete value type."),
558
+ environment,
559
+ );
356
560
  if (inner.io || !this.isValue(inner)) {
357
561
  this.fail(
358
562
  node,
@@ -362,21 +566,20 @@ export class TypeResolver {
362
566
  }
363
567
  return { type: inner.type, mode: "inOut" };
364
568
  }
365
- if (official && this.types.has(official)) {
569
+ if (official && this.layouts.has(official)) {
366
570
  if (node.typeArguments?.length) {
367
571
  this.fail(node, "PLC2001", "Scalar types take no type arguments.");
368
572
  }
369
573
  return { type: official };
370
574
  }
371
575
  if (official === "Input" || official === "Output") {
372
- if (node.typeArguments?.length !== 1) {
373
- this.fail(
576
+ const inner = this.resolve(
577
+ this.soleTypeArgument(
374
578
  node,
375
- "PLC2001",
376
579
  "I/O types need exactly one PLC type argument.",
377
- );
378
- }
379
- const inner = this.resolve(node.typeArguments[0]!, environment);
580
+ ),
581
+ environment,
582
+ );
380
583
  if (inner.io || inner.mode || this.hasReferences(inner.type)) {
381
584
  this.fail(node, "PLC2001", "I/O type wrappers cannot be nested.");
382
585
  }
@@ -386,8 +589,8 @@ export class TypeResolver {
386
589
  };
387
590
  }
388
591
  if (official === "FixedArray") {
389
- const args = node.typeArguments;
390
- if (!args || args.length < 2 || args.length > 3) {
592
+ const [element, length, lower, ...rest] = node.typeArguments ?? [];
593
+ if (!element || !length || rest.length) {
391
594
  this.fail(
392
595
  node,
393
596
  "PLC2001",
@@ -396,10 +599,10 @@ export class TypeResolver {
396
599
  }
397
600
  return this.fixedArray(
398
601
  node,
399
- this.resolve(args[0]!, environment),
400
- this.argument(args[1]!, environment),
401
- args[2]
402
- ? this.argument(args[2], environment)
602
+ this.resolve(element, environment),
603
+ this.argument(length, environment),
604
+ lower
605
+ ? this.argument(lower, environment)
403
606
  : { kind: "integer", value: 0 },
404
607
  );
405
608
  }
@@ -408,9 +611,9 @@ export class TypeResolver {
408
611
  const [key, value] = node.typeArguments ?? [];
409
612
  const index =
410
613
  key && ts.isTypeReferenceNode(key)
411
- ? this.types.get(this.resolve(key, environment).type)
614
+ ? this.layouts.get(this.resolve(key, environment).type)
412
615
  : undefined;
413
- if (index?.kind !== "enum") {
616
+ if (index?.kind !== "enum" || !value) {
414
617
  this.fail(
415
618
  node,
416
619
  "PLC2001",
@@ -426,7 +629,7 @@ export class TypeResolver {
426
629
  "Record<Enum, T> needs enum member values without gaps.",
427
630
  );
428
631
  }
429
- const element = this.resolve(value!, environment);
632
+ const element = this.resolve(value, environment);
430
633
  if (element.io || !this.isValue(element)) {
431
634
  this.fail(
432
635
  node,
@@ -435,7 +638,7 @@ export class TypeResolver {
435
638
  );
436
639
  }
437
640
  const id = `array<${element.type},${values.length},${lower},${index.id}>`;
438
- this.types.set(id, {
641
+ this.layouts.set(id, {
439
642
  id,
440
643
  kind: "array",
441
644
  element: element.type,
@@ -447,23 +650,26 @@ export class TypeResolver {
447
650
  return { type: id };
448
651
  }
449
652
  if (official === "STRING" || official === "WSTRING") {
450
- if (node.typeArguments?.length !== 1) {
451
- this.fail(
653
+ const capacity = this.argument(
654
+ this.soleTypeArgument(
452
655
  node,
453
- "PLC2001",
454
656
  "Bounded strings require one capacity argument.",
455
- );
456
- }
457
- const capacity = this.argument(node.typeArguments[0]!, environment);
657
+ ),
658
+ environment,
659
+ );
458
660
  if (
459
661
  capacity.kind !== "integer" ||
460
662
  capacity.value < 1 ||
461
- capacity.value > 65535
663
+ capacity.value > maxStringCapacity
462
664
  ) {
463
- this.fail(node, "PLC2001", "String capacity must be 1..65535.");
665
+ this.fail(
666
+ node,
667
+ "PLC2001",
668
+ `String capacity must be 1..${maxStringCapacity}.`,
669
+ );
464
670
  }
465
671
  const id = `${official}<${capacity.value}>`;
466
- this.types.set(id, {
672
+ this.layouts.set(id, {
467
673
  id,
468
674
  kind: "string",
469
675
  capacity: capacity.value,
@@ -474,6 +680,17 @@ export class TypeResolver {
474
680
  return this.declaration(symbol, node.typeArguments, environment, node);
475
681
  }
476
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
+
477
694
  fixedArray(
478
695
  node: ts.Node,
479
696
  element: ResolvedType,
@@ -483,13 +700,14 @@ export class TypeResolver {
483
700
  if (
484
701
  element.io ||
485
702
  !(
486
- this.isValue(element) || this.types.get(element.type)?.kind === "block"
703
+ this.isValue(element) ||
704
+ this.layouts.get(element.type)?.kind === "block"
487
705
  ) ||
488
706
  length.kind !== "integer" ||
489
707
  lower.kind !== "integer" ||
490
708
  length.value < 1 ||
491
709
  length.value > maxScalarElements ||
492
- BigInt(lower.value + length.value - 1) > lastIndex
710
+ BigInt(lower.value + length.value - 1) > highestDint
493
711
  ) {
494
712
  this.fail(
495
713
  node,
@@ -498,7 +716,7 @@ export class TypeResolver {
498
716
  );
499
717
  }
500
718
  const id = `array<${element.type},${length.value},${lower.value}>`;
501
- this.types.set(id, {
719
+ this.layouts.set(id, {
502
720
  id,
503
721
  kind: "array",
504
722
  element: element.type,
@@ -542,15 +760,12 @@ export class TypeResolver {
542
760
  }
543
761
  return this.enumeration(declaration);
544
762
  }
545
- const bindings = this.bindings(
763
+ const { environment: bindings, suffix } = this.bindings(
546
764
  declaration.typeParameters,
547
765
  arguments_,
548
766
  environment,
549
767
  node,
550
768
  );
551
- const suffix = (declaration.typeParameters ?? [])
552
- .map((parameter) => this.key(bindings.get(this.symbol(parameter.name))!))
553
- .join(",");
554
769
  const id = `${this.id(declaration, declaration.name.text)}${suffix ? `<${suffix}>` : ""}`;
555
770
  if (this.active.has(id)) {
556
771
  this.fail(
@@ -559,14 +774,14 @@ export class TypeResolver {
559
774
  "Recursive by-value PLC layouts are unsupported.",
560
775
  );
561
776
  }
562
- if (this.types.has(id)) {
777
+ if (this.layouts.has(id)) {
563
778
  return { type: id };
564
779
  }
565
- if (this.active.size >= 64) {
780
+ if (this.active.size >= maxSubstitutionDepth) {
566
781
  this.fail(
567
782
  node,
568
783
  "PLC2001",
569
- "Type substitution exceeds 64 levels; recursive expansion is unsupported.",
784
+ `Type substitution exceeds ${maxSubstitutionDepth} levels; recursive expansion is unsupported.`,
570
785
  );
571
786
  }
572
787
  this.active.add(id);
@@ -576,8 +791,7 @@ export class TypeResolver {
576
791
  return this.record(
577
792
  declaration,
578
793
  id,
579
- declaration.type.members,
580
- bindings,
794
+ this.fields(declaration.type.members, bindings),
581
795
  );
582
796
  }
583
797
  if (ts.isUnionTypeNode(declaration.type)) {
@@ -595,7 +809,7 @@ export class TypeResolver {
595
809
  bindings,
596
810
  base,
597
811
  );
598
- const layout = this.types.get(baseType.type);
812
+ const layout = this.layouts.get(baseType.type);
599
813
  if (layout?.kind !== "record") {
600
814
  this.fail(base, "PLC2001", "Inherited layout must be a record.");
601
815
  }
@@ -605,9 +819,7 @@ export class TypeResolver {
605
819
  return this.record(
606
820
  declaration,
607
821
  id,
608
- declaration.members,
609
- bindings,
610
- inherited,
822
+ this.fields(declaration.members, bindings, inherited),
611
823
  );
612
824
  } finally {
613
825
  this.active.delete(id);
@@ -653,7 +865,7 @@ export class TypeResolver {
653
865
  !members ||
654
866
  !literal ||
655
867
  !ts.isStringLiteral(literal) ||
656
- !/^[A-Za-z]\w*$/.test(literal.text)
868
+ !generatedNamePattern.test(literal.text)
657
869
  ) {
658
870
  this.fail(
659
871
  variant,
@@ -681,13 +893,13 @@ export class TypeResolver {
681
893
  }
682
894
  }
683
895
  const kindId = `${id}Kind`;
684
- this.types.set(kindId, {
896
+ this.layouts.set(kindId, {
685
897
  id: kindId,
686
898
  kind: "enum",
687
899
  base: "DINT",
688
900
  members: kinds.map((name, value) => ({ name, value: String(value) })),
689
901
  });
690
- this.types.set(id, {
902
+ this.layouts.set(id, {
691
903
  id,
692
904
  kind: "record",
693
905
  fields: [
@@ -700,18 +912,11 @@ export class TypeResolver {
700
912
  return { type: id };
701
913
  }
702
914
 
703
- private record(
704
- node: ts.Node,
705
- id: string,
706
- members: readonly ts.TypeElement[],
707
- environment: TypeEnvironment,
708
- inherited: readonly Field[] = [],
709
- ): ResolvedType {
710
- const fields = this.fields(members, environment, inherited);
915
+ private record(node: ts.Node, id: string, fields: Field[]): ResolvedType {
711
916
  if (!fields.length) {
712
917
  this.fail(node, "PLC2001", "PLC records require at least one field.");
713
918
  }
714
- this.types.set(id, { id, kind: "record", fields });
919
+ this.layouts.set(id, { id, kind: "record", fields });
715
920
  this.checkSize(id, node);
716
921
  return { type: id };
717
922
  }
@@ -759,11 +964,7 @@ export class TypeResolver {
759
964
  name: member.name.text,
760
965
  type: type.type,
761
966
  ...(type.mode && { mode: type.mode }),
762
- readonly: Boolean(
763
- member.modifiers?.some(
764
- (modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword,
765
- ),
766
- ),
967
+ readonly: hasModifier(member, ts.SyntaxKind.ReadonlyKeyword),
767
968
  });
768
969
  names.add(member.name.text);
769
970
  }
@@ -775,7 +976,7 @@ export class TypeResolver {
775
976
  return [];
776
977
  }
777
978
  const resolved = this.resolve(node);
778
- const type = this.types.get(resolved.type);
979
+ const type = this.layouts.get(resolved.type);
779
980
  if (resolved.io || resolved.mode || type?.kind !== "record") {
780
981
  this.fail(
781
982
  node,
@@ -807,7 +1008,7 @@ export class TypeResolver {
807
1008
  return false;
808
1009
  }
809
1010
  seen.add(id);
810
- const type = this.types.get(id);
1011
+ const type = this.layouts.get(id);
811
1012
  if (type?.kind === "record") {
812
1013
  return type.fields.some(
813
1014
  (field) => field.mode || this.hasReferences(field.type, seen),
@@ -818,7 +1019,7 @@ export class TypeResolver {
818
1019
 
819
1020
  enumeration(node: ts.EnumDeclaration): ResolvedType {
820
1021
  const id = this.id(node, node.name.text);
821
- if (this.types.has(id)) {
1022
+ if (this.layouts.has(id)) {
822
1023
  return { type: id };
823
1024
  }
824
1025
  if (!node.members.length) {
@@ -832,8 +1033,8 @@ export class TypeResolver {
832
1033
  if (
833
1034
  typeof value !== "number" ||
834
1035
  !Number.isInteger(value) ||
835
- BigInt(value) < lowestEnumValue ||
836
- BigInt(value) > highestEnumValue
1036
+ BigInt(value) < lowestDint ||
1037
+ BigInt(value) > highestDint
837
1038
  ) {
838
1039
  this.fail(
839
1040
  member,
@@ -848,41 +1049,25 @@ export class TypeResolver {
848
1049
  ) {
849
1050
  this.fail(node, "PLC2001", "PLC enum members require distinct values.");
850
1051
  }
851
- this.types.set(id, { id, kind: "enum", base: "DINT", members });
1052
+ this.layouts.set(id, { id, kind: "enum", base: "DINT", members });
852
1053
  return { type: id };
853
1054
  }
854
1055
 
855
1056
  private checkSize(id: string, node: ts.Node): void {
856
- const count = (typeId: string, depth: number): number => {
857
- if (depth > maxNestingDepth) {
858
- this.fail(
859
- node,
860
- "PLC2001",
861
- `PLC layout nesting exceeds ${maxNestingDepth} levels.`,
862
- );
863
- }
864
- const size = scalars(this.types.get(typeId)!, depth + 1);
865
- if (size > maxScalarElements) {
866
- this.fail(
867
- node,
868
- "PLC2001",
869
- "PLC layout exceeds one million scalar elements.",
870
- );
871
- }
872
- return size;
873
- };
874
- const scalars = (type: PlcType, depth: number): number => {
875
- if (type.kind === "array") {
876
- return type.length * count(type.element, depth);
877
- }
878
- if (type.kind === "record") {
879
- return type.fields.reduce(
880
- (total, field) => total + count(field.type, depth),
881
- 0,
882
- );
883
- }
884
- return 1;
885
- };
886
- count(id, 0);
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
+ }
887
1072
  }
888
1073
  }