@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
package/src/ir/layouts.ts CHANGED
@@ -1,13 +1,18 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import { elementaryType, integerRange } from "@tsplc/iec";
3
- import { InvalidCore, reject } from "./normalization-error";
2
+ import { reject } from "./normalization-error";
4
3
  import { constantFits } from "./numeric";
4
+ import { lookup } from "./tables";
5
5
  import { type PlcType, primitiveTypes } from "./types";
6
6
 
7
7
  /** The finite storage budget: scalar elements in one layout or allocation, and nesting depth. */
8
8
  export const maxScalarElements = 1_000_000;
9
+ /** `maxScalarElements` as diagnostics spell it. */
10
+ export const maxScalarElementsText = "one million";
9
11
  export const maxNestingDepth = 64;
10
12
 
13
+ /** The largest capacity a bounded string may declare. */
14
+ export const maxStringCapacity = 65535;
15
+
11
16
  // Array bounds and indexes are DINT.
12
17
  const [firstIndex, lastIndex] = integerRange(elementaryType("DINT"));
13
18
 
@@ -32,13 +37,7 @@ const definitionIssue = (
32
37
  return !type.fields.length ||
33
38
  new Set(type.fields.map((field) => field.name)).size !==
34
39
  type.fields.length ||
35
- type.fields.some(
36
- (field) =>
37
- !field.name ||
38
- typeof field.readonly !== "boolean" ||
39
- (field.mode && field.mode !== "inOut") ||
40
- !types.has(field.type),
41
- )
40
+ type.fields.some((field) => !field.name || !types.has(field.type))
42
41
  ? `Invalid closed record layout ${type.id}`
43
42
  : undefined;
44
43
  case "array": {
@@ -87,8 +86,7 @@ const definitionIssue = (
87
86
  case "string":
88
87
  return !Number.isInteger(type.capacity) ||
89
88
  type.capacity < 1 ||
90
- type.capacity > 65535 ||
91
- !["utf8", "utf16"].includes(type.encoding)
89
+ type.capacity > maxStringCapacity
92
90
  ? `Invalid bounded string layout ${type.id}`
93
91
  : undefined;
94
92
  case "block":
@@ -106,41 +104,50 @@ interface Layout {
106
104
  height: number;
107
105
  }
108
106
 
107
+ /** The part of the storage budget a layout exceeds. */
108
+ export type LayoutBudget = "size" | "nesting";
109
+
109
110
  /**
110
- * Validates every layout edge once, before constants or places can traverse them, and measures
111
- * each by-value layout against the storage budget. Returns each type's size in scalar elements.
111
+ * Measures by-value layouts against the storage budget, each once, and hands the first that
112
+ * exceeds it to `exceeded`.
112
113
  */
113
- export const admitLayouts = (
114
+ const layoutMeasure = (
114
115
  types: ReadonlyMap<string, PlcType>,
115
- ): ReadonlyMap<string, number> => {
116
- for (const type of types.values()) {
117
- const issue = definitionIssue(type, types);
118
- if (issue) {
119
- reject(issue);
120
- }
121
- }
116
+ exceeded: (budget: LayoutBudget, message: string) => never,
117
+ ) => {
122
118
  const active = new Set<string>();
123
119
  const layouts = new Map<string, Layout>();
124
120
  const measure = (id: string, depth: number): Layout => {
125
121
  if (active.has(id) || depth > maxNestingDepth) {
126
- reject(`Recursive or excessively nested by-value layout ${id}`);
122
+ exceeded(
123
+ "nesting",
124
+ `Recursive or excessively nested by-value layout ${id}`,
125
+ );
127
126
  }
128
127
  const cached = layouts.get(id);
129
128
  if (cached) {
130
129
  if (depth + cached.height > maxNestingDepth) {
131
- reject(`Layout nesting exceeds ${maxNestingDepth} levels ${id}`);
130
+ exceeded(
131
+ "nesting",
132
+ `Layout nesting exceeds ${maxNestingDepth} levels ${id}`,
133
+ );
132
134
  }
133
135
  return cached;
134
136
  }
135
137
  active.add(id);
136
- // Every edge was validated above.
137
- const layout = composite(types.get(id)!, depth);
138
+ const layout = composite(lookup(types, id, "type"), depth);
138
139
  active.delete(id);
139
140
  if (layout.size > maxScalarElements) {
140
- reject(`Layout exceeds one million scalar elements ${id}`);
141
+ exceeded(
142
+ "size",
143
+ `Layout exceeds ${maxScalarElementsText} scalar elements ${id}`,
144
+ );
141
145
  }
142
146
  if (depth + layout.height > maxNestingDepth) {
143
- reject(`Layout nesting exceeds ${maxNestingDepth} levels ${id}`);
147
+ exceeded(
148
+ "nesting",
149
+ `Layout nesting exceeds ${maxNestingDepth} levels ${id}`,
150
+ );
144
151
  }
145
152
  layouts.set(id, layout);
146
153
  return layout;
@@ -161,21 +168,43 @@ export const admitLayouts = (
161
168
  }
162
169
  return { size: 1, height: 0 };
163
170
  };
164
- for (const id of types.keys()) {
165
- measure(id, 0);
171
+ return (id: string) => measure(id, 0);
172
+ };
173
+
174
+ /**
175
+ * Validates every layout edge once, before constants or places can traverse them, and measures
176
+ * each by-value layout against the storage budget. Returns each type's size in scalar elements.
177
+ */
178
+ export const admitLayouts = (
179
+ types: ReadonlyMap<string, PlcType>,
180
+ ): ReadonlyMap<string, number> => {
181
+ for (const type of types.values()) {
182
+ const issue = definitionIssue(type, types);
183
+ if (issue) {
184
+ reject(issue);
185
+ }
166
186
  }
167
- return new Map([...layouts].map(([id, layout]) => [id, layout.size]));
187
+ const measure = layoutMeasure(types, (_budget, message) => reject(message));
188
+ return new Map([...types.keys()].map((id) => [id, measure(id).size]));
168
189
  };
169
190
 
191
+ class BudgetExceeded {
192
+ constructor(readonly budget: LayoutBudget) {}
193
+ }
194
+
195
+ /** Which part of the storage budget the by-value layout of `id` exceeds, if any. */
170
196
  export const layoutIssue = (
171
197
  types: ReadonlyMap<string, PlcType>,
172
- ): string | undefined => {
198
+ id: string,
199
+ ): LayoutBudget | undefined => {
173
200
  try {
174
- admitLayouts(types);
201
+ layoutMeasure(types, (budget) => {
202
+ throw new BudgetExceeded(budget);
203
+ })(id);
175
204
  return undefined;
176
205
  } catch (cause) {
177
- if (cause instanceof InvalidCore) {
178
- return cause.diagnostic.message;
206
+ if (cause instanceof BudgetExceeded) {
207
+ return cause.budget;
179
208
  }
180
209
  throw cause;
181
210
  }
package/src/ir/link.ts CHANGED
@@ -1,20 +1,21 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import {
3
2
  type CoreFunction,
4
3
  type CoreFunctionBlock,
5
4
  type CoreStatement,
5
+ calledRoutine,
6
6
  directWrites,
7
7
  nestedBodies,
8
+ routineVariables,
8
9
  } from "./core-model";
9
10
  import type { ModuleDeclarations } from "./declarations";
10
11
  import { type PlcModule, telemetryOperands } from "./model";
11
12
  import { reject } from "./normalization-error";
13
+ import { lookup } from "./tables";
12
14
  import { instancedBlock, type PlcType } from "./types";
13
15
 
14
16
  type Edges = ReadonlyMap<string, ReadonlySet<string>>;
15
17
  type Routine = CoreFunction | CoreFunctionBlock;
16
18
 
17
- // Validate the complete authored call graph before pruning unreachable code.
18
19
  // Static instances keep their child layouts even when a child has no scan call.
19
20
  export function linkModule(
20
21
  module: PlcModule,
@@ -30,7 +31,6 @@ export function linkModule(
30
31
  checkRecursion(routines, edges, entries, declarations);
31
32
  checkLoopCounterWrites(module, declarations, routines, edges);
32
33
 
33
- // Only after the complete graph is valid may emission discard unused helpers.
34
34
  const reachable = reachableRoutines(
35
35
  module,
36
36
  declarations,
@@ -130,28 +130,9 @@ const checkLoopCounterWrites = (
130
130
  const variables = new Map(
131
131
  [
132
132
  ...module.variables,
133
- ...[...routines.values()].flatMap((routine) =>
134
- "inputs" in routine
135
- ? [
136
- ...routine.inputs,
137
- ...routine.outputs,
138
- ...routine.state,
139
- ...routine.locals,
140
- ]
141
- : [...routine.parameters, ...routine.locals],
142
- ),
133
+ ...[...routines.values()].flatMap(routineVariables),
143
134
  ].map((variable) => [variable.id, variable]),
144
135
  );
145
- const calledRoutine = (item: CoreStatement): string | undefined => {
146
- if (item.kind === "invoke") {
147
- return item.function;
148
- }
149
- if (item.kind !== "blockUpdate") {
150
- return undefined;
151
- }
152
- const variable = variables.get(item.instance);
153
- return variable && instancedBlock(variable.type, types)?.block;
154
- };
155
136
  const writes = new Map<string, Set<string>>();
156
137
  const routineWrites = (id: string): Set<string> => {
157
138
  const cached = writes.get(id);
@@ -169,8 +150,7 @@ const checkLoopCounterWrites = (
169
150
  }
170
151
  }
171
152
  };
172
- // Calls resolve within the module's routines; routine lowering verified each callee.
173
- inspect(routines.get(id)!.body);
153
+ inspect(lookup(routines, id, "routine").body);
174
154
  for (const child of edges.get(id) ?? []) {
175
155
  for (const root of routineWrites(child)) {
176
156
  result.add(root);
@@ -184,7 +164,7 @@ const checkLoopCounterWrites = (
184
164
  counters: ReadonlySet<string>,
185
165
  ) => {
186
166
  for (const item of body) {
187
- const called = calledRoutine(item);
167
+ const called = calledRoutine(item, (id) => variables.get(id), types);
188
168
  if (
189
169
  called &&
190
170
  [...counters].some((counter) => routineWrites(called).has(counter))
@@ -250,8 +230,6 @@ const reachableRoutines = (
250
230
  return reachable;
251
231
  };
252
232
 
253
- // Admission has already validated every referenced type; these lookups are
254
- // closed over the declaration registry, including dependencies kept by DUTs.
255
233
  const usedTypeIds = (
256
234
  module: PlcModule,
257
235
  types: ReadonlyMap<string, PlcType>,
@@ -264,7 +242,7 @@ const usedTypeIds = (
264
242
  return;
265
243
  }
266
244
  usedTypes.add(id);
267
- const type = types.get(id)!;
245
+ const type = lookup(types, id, "type");
268
246
  if (type.kind === "record") {
269
247
  for (const field of type.fields) {
270
248
  useType(field.type);
@@ -296,24 +274,11 @@ const usedTypeIds = (
296
274
  for (const variable of module.variables) {
297
275
  useType(variable.type);
298
276
  }
299
- for (const fn of linkedFunctions) {
300
- if (fn.result) {
301
- useType(fn.result);
302
- }
303
- for (const variable of [...fn.parameters, ...fn.locals]) {
304
- useType(variable.type);
305
- }
306
- }
307
- for (const block of linkedBlocks) {
308
- if (block.result) {
309
- useType(block.result);
277
+ for (const routine of [...linkedFunctions, ...linkedBlocks]) {
278
+ if (routine.result) {
279
+ useType(routine.result);
310
280
  }
311
- for (const variable of [
312
- ...block.inputs,
313
- ...block.outputs,
314
- ...block.state,
315
- ...block.locals,
316
- ]) {
281
+ for (const variable of routineVariables(routine)) {
317
282
  useType(variable.type);
318
283
  }
319
284
  }
package/src/ir/model.ts CHANGED
@@ -16,6 +16,12 @@ export type Constant =
16
16
  | { kind: "array"; items: readonly Constant[] }
17
17
  | { kind: "record"; fields: Readonly<Record<string, Constant>> };
18
18
 
19
+ /**
20
+ * What a variable keeps when the controller restarts: nothing, a warm restart (`RETAIN`), or also
21
+ * a download and a cold reset (`PERSISTENT RETAIN`).
22
+ */
23
+ export type Retention = "none" | "retain" | "persist";
24
+
19
25
  export interface Variable {
20
26
  id: SymbolId;
21
27
  name: string;
@@ -31,14 +37,26 @@ export interface Variable {
31
37
  | "constant"
32
38
  | "blockOutput";
33
39
  mutable: boolean;
34
- retain: boolean;
40
+ retention: Retention;
35
41
  exported?: true;
36
- exposure?: { name: string; version: string };
37
42
  mode?: "inOut";
38
43
  initial?: Constant;
39
44
  span: SourceSpan;
40
45
  }
41
46
 
47
+ /** Whether a variable is one of the module's logical inputs and outputs, bound to the process image. */
48
+ export const isLogicalIo = (
49
+ variable: Variable,
50
+ ): variable is Variable & { storage: "input" | "output" } =>
51
+ variable.storage === "input" || variable.storage === "output";
52
+
53
+ /** How `T | undefined` is stored: the record `{ has, value }`, named with this prefix and `T`. */
54
+ export const optionalRecord = {
55
+ prefix: "Optional_",
56
+ has: "has",
57
+ value: "value",
58
+ } as const;
59
+
42
60
  export interface Place {
43
61
  root: SymbolId;
44
62
  path: readonly (
@@ -174,14 +192,11 @@ export interface PlcFunction {
174
192
  parameters: readonly Variable[];
175
193
  locals: readonly Variable[];
176
194
  result?: TypeId;
177
- /** A `@tsplc/compiler/math` helper, whose result range follows from its arguments' ranges. */
178
- bounds?: MathHelper;
179
195
  /** The source method this function was specialized from, as `Class.method`, and the TypeScript path of its `this`. */
180
196
  origin?: { name: string; instance?: string };
181
197
  body: readonly Statement[];
182
198
  span: SourceSpan;
183
199
  }
184
- export type MathHelper = "min" | "max" | "clamp";
185
200
 
186
201
  // Native vendor blocks under their TypeScript names. Ports are [name, native name, type];
187
202
  // every output starts at its type's default, matching the vendor library blocks.
@@ -261,6 +276,10 @@ export const standardBlocks = {
261
276
  } as const;
262
277
  export type StandardBlock = keyof typeof standardBlocks;
263
278
 
279
+ /** The methods a service call or `fetch` may use. */
280
+ export const httpMethods = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
281
+ export type HttpMethod = (typeof httpMethods)[number];
282
+
264
283
  export interface FunctionBlock {
265
284
  id: SymbolId;
266
285
  name: string;
@@ -278,7 +297,7 @@ export interface FunctionBlock {
278
297
  | {
279
298
  kind: "http";
280
299
  url: string;
281
- method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
300
+ method: HttpMethod;
282
301
  json: boolean;
283
302
  };
284
303
  /** The async function lowered to this block, and the source each `step` value stands for. */
@@ -1,7 +1,9 @@
1
1
  import { checkStaticAllocation } from "./allocation";
2
2
  import {
3
+ admitCore,
3
4
  type CoreFunction,
4
5
  type CoreFunctionBlock,
6
+ isBlockRoutine,
5
7
  type VerifiedCoreModule,
6
8
  verified,
7
9
  } from "./core-model";
@@ -12,33 +14,6 @@ import type { PlcModule } from "./model";
12
14
  import { InvalidCore } from "./normalization-error";
13
15
  import { RoutineNormalizer } from "./routine";
14
16
 
15
- const verifiedModules = new WeakSet<object>();
16
- export function isVerifiedCore(value: unknown): value is VerifiedCoreModule {
17
- return (
18
- typeof value === "object" && value !== null && verifiedModules.has(value)
19
- );
20
- }
21
-
22
- function freeze(value: unknown): void {
23
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
24
- return;
25
- }
26
- for (const child of Object.values(value)) {
27
- freeze(child);
28
- }
29
- Object.freeze(value);
30
- }
31
- /**
32
- * Admits a module across the trust boundary. Only normalization, and transformations of an
33
- * admitted module that keep what it verified, call this.
34
- */
35
- export function admitCore(core: VerifiedCoreModule): VerifiedCoreModule {
36
- freeze(core);
37
- verifiedModules.add(core);
38
- return core;
39
- }
40
-
41
- // The module crosses the trust boundary only after admission, lowering and linking.
42
17
  export function normalizeModule(module: PlcModule): {
43
18
  core?: VerifiedCoreModule;
44
19
  diagnostics: readonly Diagnostic[];
@@ -56,7 +31,7 @@ export function normalizeModule(module: PlcModule): {
56
31
  declarations,
57
32
  ).normalize();
58
33
  edges.set(source.id, normalized.callees);
59
- if ("inputs" in normalized.routine) {
34
+ if (isBlockRoutine(normalized.routine)) {
60
35
  blocks.push(normalized.routine);
61
36
  } else {
62
37
  functions.push(normalized.routine);
package/src/ir/numeric.ts CHANGED
@@ -1,12 +1,14 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import { roundFloat } from "@tsplc/iec/arithmetic";
3
2
  import type { Constant } from "./model";
4
- import { integerRange, type PlcType } from "./types";
3
+ import { integerRange, integerType, type PlcType } from "./types";
5
4
 
6
- type IntegerType = Extract<PlcType, { kind: "integer" | "bits" }>;
7
5
  type FloatType = Extract<PlcType, { kind: "float" }>;
8
6
 
9
- export type IntegerInterval = readonly [bigint, bigint];
7
+ /**
8
+ * The values from a lowest to a highest, inclusive. `excluded`, when given, is one value strictly
9
+ * between them that the range doesn't hold, as `n !== 0` proves of a signed `n`.
10
+ */
11
+ export type IntegerInterval = readonly [bigint, bigint, excluded?: bigint];
10
12
 
11
13
  export const lowest = (a: bigint, b: bigint): bigint => (a < b ? a : b);
12
14
  export const highest = (a: bigint, b: bigint): bigint => (a > b ? a : b);
@@ -15,18 +17,18 @@ export const highest = (a: bigint, b: bigint): bigint => (a > b ? a : b);
15
17
  export const within = (
16
18
  inner: IntegerInterval,
17
19
  outer: IntegerInterval,
18
- ): boolean => inner[0] >= outer[0] && inner[1] <= outer[1];
20
+ ): boolean =>
21
+ inner[0] >= outer[0] &&
22
+ inner[1] <= outer[1] &&
23
+ (outer[2] === undefined || !admits(inner, outer[2]));
19
24
 
20
25
  /** Whether `interval` admits `value`, such as a divisor that may be zero. */
21
26
  export const admits = (interval: IntegerInterval, value: bigint): boolean =>
22
- interval[0] <= value && value <= interval[1];
27
+ interval[0] <= value && value <= interval[1] && interval[2] !== value;
23
28
 
24
29
  /** Integer constants are canonical decimal text: no leading zeros and no negative zero. */
25
30
  export const canonicalInteger = /^(?:0|-?[1-9][0-9]*)$/;
26
31
 
27
- export const integerType = (type: PlcType): type is IntegerType =>
28
- type.kind === "integer" || type.kind === "bits";
29
-
30
32
  // The significand precision of REAL (IEEE 754 binary32) and LREAL (binary64), which bounds the
31
33
  // integers each format holds exactly.
32
34
  const floatPrecision = { 32: 24, 64: 53 } as const;
@@ -54,8 +56,7 @@ export const exactDecimal = (
54
56
  if (!Number.isSafeInteger(exponent) || Math.abs(exponent) > 400) {
55
57
  return "exponent";
56
58
  }
57
- // The pattern requires the whole digits, so the group always matched.
58
- const digits = BigInt(whole! + fraction) * scale;
59
+ const digits = BigInt(`${whole}${fraction}`) * scale;
59
60
  if (exponent >= 0) {
60
61
  return digits * 10n ** BigInt(exponent);
61
62
  }
@@ -66,12 +67,17 @@ export const exactDecimal = (
66
67
  const integerLiteralIssues: Record<DecimalIssue, string> = {
67
68
  malformed: "Expected an exact integer literal.",
68
69
  exponent: "Integer literal exponent is out of range.",
69
- fraction: "Integer literals cannot have a fractional part.",
70
+ fraction:
71
+ "Integer literals cannot have a fractional part; to hold fractions, annotate the field or variable REAL or LREAL.",
70
72
  };
71
73
 
74
+ /** Whether a numeric literal is written in hexadecimal, octal or binary, which has no fraction or exponent. */
75
+ export const isRadixLiteral = (text: string): boolean =>
76
+ /^-?0[xob]/i.test(text);
77
+
72
78
  export const parseInteger = (text: string): bigint => {
73
79
  const clean = text.replaceAll("_", "").replace(/n$/, "");
74
- if (/^-?0[xob]/i.test(clean)) {
80
+ if (isRadixLiteral(clean)) {
75
81
  return clean.startsWith("-") ? -BigInt(clean.slice(1)) : BigInt(clean);
76
82
  }
77
83
  const value = exactDecimal(clean, 1n);
@@ -81,9 +87,21 @@ export const parseInteger = (text: string): bigint => {
81
87
  return value;
82
88
  };
83
89
 
90
+ /** A float literal's value, rounded to its type's width. */
91
+ export const parseFloatLiteral = (text: string, type: FloatType): number => {
92
+ const clean = text.replaceAll("_", "");
93
+ const value = isRadixLiteral(clean)
94
+ ? Number(parseInteger(clean))
95
+ : Number(clean);
96
+ return roundFloat(value, type);
97
+ };
98
+
99
+ export const literalOutsideType =
100
+ "Literal is outside its PLC type or has the wrong domain.";
101
+
84
102
  export const constantFits = (value: Constant, type: PlcType): boolean => {
85
103
  if (type.kind === "bool") {
86
- return value.kind === "bool" && typeof value.value === "boolean";
104
+ return value.kind === "bool";
87
105
  }
88
106
  if (integerType(type)) {
89
107
  return (
@@ -123,7 +141,17 @@ export const canAssign = (
123
141
  );
124
142
  };
125
143
 
126
- /** Plain integer +, - and * are native IEC arithmetic, which wraps on overflow as hand-written ST does. */
144
+ /**
145
+ * Integer +, - and *: native IEC arithmetic wraps them on overflow as hand-written ST does, and
146
+ * they are the operations that take an explicit wrap or saturate policy.
147
+ */
148
+ export const wrappingOperators: ReadonlySet<string> = new Set([
149
+ "add",
150
+ "subtract",
151
+ "multiply",
152
+ ]);
153
+
154
+ /** Whether an expression is plain integer +, - or *, which wraps natively. */
127
155
  export const wrapsNatively = (expression: {
128
156
  kind: string;
129
157
  operator?: string;
@@ -131,6 +159,5 @@ export const wrapsNatively = (expression: {
131
159
  }): boolean =>
132
160
  expression.kind === "binary" &&
133
161
  !expression.policy &&
134
- (expression.operator === "add" ||
135
- expression.operator === "subtract" ||
136
- expression.operator === "multiply");
162
+ expression.operator !== undefined &&
163
+ wrappingOperators.has(expression.operator);
@@ -5,6 +5,17 @@ import { telemetryOperands } from "./model";
5
5
  export const pathIndexes = (path: CorePath = []): CoreExpression[] =>
6
6
  path.flatMap((segment) => (segment.kind === "index" ? [segment.value] : []));
7
7
 
8
+ /** A path with each index replaced by `map` of it. */
9
+ export const mapPath = (
10
+ path: CorePath,
11
+ map: (index: CoreExpression) => CoreExpression,
12
+ ): CorePath =>
13
+ path.map((segment) =>
14
+ segment.kind === "field"
15
+ ? segment
16
+ : { kind: "index", value: map(segment.value) },
17
+ );
18
+
8
19
  /** The expressions an expression evaluates directly: its operands, or the indexes of the place it loads or borrows. */
9
20
  export const subexpressions = (
10
21
  value: CoreExpression,
@@ -24,6 +35,29 @@ export const subexpressions = (
24
35
  }
25
36
  };
26
37
 
38
+ /** An expression with each of its `subexpressions` replaced by `map` of it. */
39
+ export const mapExpression = (
40
+ value: CoreExpression,
41
+ map: (operand: CoreExpression) => CoreExpression,
42
+ ): CoreExpression => {
43
+ switch (value.kind) {
44
+ case "constant":
45
+ return value;
46
+ case "load":
47
+ return value.path ? { ...value, path: mapPath(value.path, map) } : value;
48
+ case "borrow":
49
+ return {
50
+ ...value,
51
+ place: { ...value.place, path: mapPath(value.place.path, map) },
52
+ };
53
+ case "unary":
54
+ case "convert":
55
+ return { ...value, operand: map(value.operand) };
56
+ case "binary":
57
+ return { ...value, left: map(value.left), right: map(value.right) };
58
+ }
59
+ };
60
+
27
61
  /**
28
62
  * The expressions a statement evaluates itself, a place's indexes before the value stored or
29
63
  * passed there. The statements nested in it are `nestedBodies`.
@@ -56,3 +90,71 @@ export const statementExpressions = (
56
90
  return [];
57
91
  }
58
92
  };
93
+
94
+ /**
95
+ * A statement with each of its `statementExpressions` replaced by `map` of it. A telemetry call's
96
+ * properties are mapped before its exception code: routine sharing numbers constants in the order
97
+ * it maps them, and that order is the merged routine's value parameter order in the emitted ST.
98
+ */
99
+ export const mapStatementExpressions = (
100
+ item: CoreStatement,
101
+ map: (operand: CoreExpression) => CoreExpression,
102
+ ): CoreStatement => {
103
+ switch (item.kind) {
104
+ case "assign":
105
+ return {
106
+ ...item,
107
+ ...(item.path && { path: mapPath(item.path, map) }),
108
+ value: map(item.value),
109
+ };
110
+ case "if":
111
+ return { ...item, condition: map(item.condition) };
112
+ case "switch":
113
+ return { ...item, value: map(item.value) };
114
+ case "for":
115
+ return item.dynamic
116
+ ? {
117
+ ...item,
118
+ dynamic: {
119
+ ...item.dynamic,
120
+ start: map(item.dynamic.start),
121
+ limit: map(item.dynamic.limit),
122
+ },
123
+ }
124
+ : item;
125
+ case "invoke":
126
+ return {
127
+ ...item,
128
+ ...(item.index && { index: map(item.index) }),
129
+ arguments: item.arguments.map(map),
130
+ };
131
+ case "blockUpdate":
132
+ return {
133
+ ...item,
134
+ ...(item.index && { index: map(item.index) }),
135
+ inputs: Object.fromEntries(
136
+ Object.entries(item.inputs).map(([name, input]) => [
137
+ name,
138
+ map(input),
139
+ ]),
140
+ ),
141
+ };
142
+ case "return":
143
+ return item.value ? { ...item, value: map(item.value) } : item;
144
+ case "telemetry":
145
+ return {
146
+ ...item,
147
+ properties: item.properties.map((property) => ({
148
+ ...property,
149
+ value: map(property.value),
150
+ ...(property.length && { length: map(property.length) }),
151
+ })),
152
+ ...(item.record.kind === "exception" && {
153
+ record: { ...item.record, code: map(item.record.code) },
154
+ }),
155
+ };
156
+ case "break":
157
+ case "continue":
158
+ return item;
159
+ }
160
+ };