@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,15 +1,15 @@
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 { calendarZero, domainConstantFits, domainIssue } from "./domains";
1
+ import { isComparison } from "@tsplc/iec/arithmetic";
3
2
  import {
4
- type Constant,
5
- comparisonOperators,
6
- type Expression,
7
- type Place,
8
- type Variable,
9
- } from "./model";
3
+ calendarZero,
4
+ comparedType,
5
+ domainConstantFits,
6
+ domainIssue,
7
+ } from "./domains";
8
+ import type { Constant, Expression, Place, Variable } from "./model";
10
9
  import { constantFits, type IntegerInterval } from "./numeric";
11
10
  import { interval } from "./ranges";
12
11
  import { scalarIssue } from "./scalars";
12
+ import { lookup } from "./tables";
13
13
  import type { PlcType } from "./types";
14
14
 
15
15
  export function aggregate(type: PlcType | undefined): boolean {
@@ -43,7 +43,7 @@ export function valueFits(
43
43
  value.kind === "array" &&
44
44
  value.items.length === type.length &&
45
45
  value.items.every((item) =>
46
- valueFits(item, types.get(type.element)!, types),
46
+ valueFits(item, lookup(types, type.element, "type"), types),
47
47
  )
48
48
  );
49
49
  }
@@ -51,11 +51,15 @@ export function valueFits(
51
51
  return (
52
52
  value.kind === "record" &&
53
53
  Object.keys(value.fields).length === type.fields.length &&
54
- type.fields.every(
55
- (field) =>
56
- Object.hasOwn(value.fields, field.name) &&
57
- valueFits(value.fields[field.name]!, types.get(field.type)!, types),
58
- )
54
+ type.fields.every((field) => {
55
+ const fieldValue = Object.hasOwn(value.fields, field.name)
56
+ ? value.fields[field.name]
57
+ : undefined;
58
+ return (
59
+ fieldValue !== undefined &&
60
+ valueFits(fieldValue, lookup(types, field.type, "type"), types)
61
+ );
62
+ })
59
63
  );
60
64
  }
61
65
  return constantFits(value, type);
@@ -78,12 +82,12 @@ export function defaultValue(
78
82
  return { kind: "string", value: "" };
79
83
  }
80
84
  if (type.kind === "enum") {
81
- return {
82
- kind: "integer",
83
- value:
84
- type.members.find((member) => member.value === "0")?.value ??
85
- type.members[0]!.value,
86
- };
85
+ const member =
86
+ type.members.find((item) => item.value === "0") ?? type.members[0];
87
+ if (!member) {
88
+ throw new Error(`Enum ${type.id} has no members.`);
89
+ }
90
+ return { kind: "integer", value: member.value };
87
91
  }
88
92
  if (type.kind === "array") {
89
93
  return {
@@ -119,7 +123,7 @@ export function placeType(
119
123
  place: Place,
120
124
  types: ReadonlyMap<string, PlcType>,
121
125
  variables: ReadonlyMap<string, Variable>,
122
- ranges: ReadonlyMap<string, IntegerInterval> = new Map(),
126
+ ranges: ReadonlyMap<string, IntegerInterval>,
123
127
  writable = false,
124
128
  ): { type?: string; issue?: string } {
125
129
  const root = variables.get(place.root);
@@ -134,56 +138,69 @@ export function placeType(
134
138
  (root.storage === "parameter" && root.mode !== "inOut") ||
135
139
  (!place.path.length && !root.mutable))
136
140
  ) {
137
- return { issue: "This storage is read-only." };
141
+ return {
142
+ issue:
143
+ "This storage is read-only here: copy it into a let and change the copy.",
144
+ };
138
145
  }
139
- let id = root.type;
140
- for (const segment of place.path) {
141
- const type = types.get(id);
142
- if (segment.kind === "field") {
143
- if (type?.kind === "block" && segment.name === "out" && type.output) {
144
- if (writable) {
145
- return { issue: "Function block output views are read-only." };
146
- }
147
- id = type.output;
148
- continue;
149
- }
150
- if (type?.kind !== "record") {
151
- return { issue: "Field access requires a record." };
152
- }
153
- const field = type.fields.find((field) => field.name === segment.name);
154
- if (!field) {
155
- return { issue: "Unknown record field." };
156
- }
157
- if (writable && field.readonly) {
158
- return { issue: "This field is read-only." };
159
- }
160
- id = field.type;
161
- } else {
162
- if (type?.kind !== "array") {
163
- return { issue: "Index access requires a fixed array." };
164
- }
165
- // Enum values are closed, and the layout check below proves its members are the bounds.
166
- // An integer, such as a for…of counter, still needs its bounds proof.
167
- if (type.index && segment.value.type === type.index) {
168
- id = type.element;
169
- continue;
170
- }
171
- const indexType = types.get(segment.value.type);
172
- const bounds = interval(segment.value, types, variables, ranges);
173
- if (
174
- indexType?.kind !== "integer" ||
175
- !bounds ||
176
- bounds[0] < BigInt(type.lowerBound) ||
177
- bounds[1] >= BigInt(type.lowerBound + type.length)
178
- ) {
179
- return {
180
- issue: "Array index must be proved within the declared bounds.",
181
- };
182
- }
183
- id = type.element;
146
+ return place.path.reduce<Walk>(
147
+ (walk, segment) =>
148
+ "issue" in walk
149
+ ? walk
150
+ : segmentType(walk.type, segment, types, variables, ranges, writable),
151
+ { type: root.type },
152
+ );
153
+ }
154
+
155
+ type Walk = { type: string } | { issue: string };
156
+
157
+ /** The type a path segment selects from `id`, or why it cannot. */
158
+ function segmentType(
159
+ id: string,
160
+ segment: Place["path"][number],
161
+ types: ReadonlyMap<string, PlcType>,
162
+ variables: ReadonlyMap<string, Variable>,
163
+ ranges: ReadonlyMap<string, IntegerInterval>,
164
+ writable: boolean,
165
+ ): Walk {
166
+ const type = types.get(id);
167
+ if (segment.kind === "field") {
168
+ if (type?.kind === "block" && segment.name === "out" && type.output) {
169
+ return writable
170
+ ? { issue: "Function block output views are read-only." }
171
+ : { type: type.output };
172
+ }
173
+ if (type?.kind !== "record") {
174
+ return { issue: "Field access requires a record." };
175
+ }
176
+ const field = type.fields.find((field) => field.name === segment.name);
177
+ if (!field) {
178
+ return { issue: "Unknown record field." };
184
179
  }
180
+ if (writable && field.readonly) {
181
+ return { issue: "This field is read-only." };
182
+ }
183
+ return { type: field.type };
184
+ }
185
+ if (type?.kind !== "array") {
186
+ return { issue: "Index access requires a fixed array." };
187
+ }
188
+ // Enum values are closed, and admission proves an enum-keyed array's members are its bounds.
189
+ // An integer, such as a for…of counter, still needs its bounds proof.
190
+ if (type.index && segment.value.type === type.index) {
191
+ return { type: type.element };
192
+ }
193
+ const indexType = types.get(segment.value.type);
194
+ const bounds = interval(segment.value, types, variables, ranges);
195
+ if (
196
+ indexType?.kind !== "integer" ||
197
+ !bounds ||
198
+ bounds[0] < BigInt(type.lowerBound) ||
199
+ bounds[1] >= BigInt(type.lowerBound + type.length)
200
+ ) {
201
+ return { issue: "Array index must be proved within the declared bounds." };
185
202
  }
186
- return { type: id };
203
+ return { type: type.element };
187
204
  }
188
205
  export function aggregateIssue(
189
206
  value: Expression,
@@ -238,13 +255,11 @@ export function aggregateIssue(
238
255
  ) {
239
256
  return undefined;
240
257
  }
241
- if (value.kind === "binary" && comparisonOperators.has(value.operator)) {
242
- const left = types.get(value.left.type);
243
- return value.type === "BOOL" &&
244
- left &&
245
- ["enum", "string"].includes(left.kind) &&
246
- value.left.type === value.right.type &&
247
- (left.kind !== "enum" || ["equal", "notEqual"].includes(value.operator))
258
+ if (value.kind === "binary" && isComparison(value.operator)) {
259
+ const compared = comparedType(value, types, ["enum", "string"]);
260
+ return compared &&
261
+ (compared.kind !== "enum" ||
262
+ ["equal", "notEqual"].includes(value.operator))
248
263
  ? undefined
249
264
  : "Comparison requires compatible scalar domains; object identity is unsupported.";
250
265
  }
@@ -1,31 +1,43 @@
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 type { ModuleDeclarations } from "./declarations";
3
- import { maxNestingDepth, maxScalarElements } from "./layouts";
2
+ import {
3
+ maxNestingDepth,
4
+ maxScalarElements,
5
+ maxScalarElementsText,
6
+ } from "./layouts";
4
7
  import type { PlcModule } from "./model";
5
8
  import { reject } from "./normalization-error";
9
+ import { lookup } from "./tables";
6
10
  import { instancedBlock } from "./types";
7
11
 
12
+ interface Allocation {
13
+ size: number;
14
+ height: number;
15
+ }
16
+
8
17
  export function checkStaticAllocation(
9
18
  module: PlcModule,
10
19
  declarations: ModuleDeclarations,
11
20
  ): void {
12
21
  const { types, blocks, layoutSizes } = declarations;
13
22
 
14
- // Declaration admission closes these registries over every referenced type
15
- // and block before allocation starts; a missing entry cannot be authored here.
16
23
  // Static allocation is a separate graph from scan calls: even an unused child
17
24
  // consumes memory, and a recursive child cannot be allocated by value.
18
- const payload = (id: string): number => layoutSizes.get(id)!;
25
+ const payload = (id: string): number => lookup(layoutSizes, id, "layout");
19
26
 
20
- const instanceSize = (id: string): number => {
21
- const type = types.get(id)!;
27
+ const instance = (id: string): Allocation => {
28
+ const instanced = instancedBlock(id, types);
29
+ if (!instanced) {
30
+ throw new Error(`Type ${id} instantiates no block.`);
31
+ }
32
+ const block = allocation(instanced.block);
33
+ const type = lookup(types, id, "type");
22
34
  return type.kind === "array"
23
- ? type.length * instanceSize(type.element)
24
- : allocation(type.kind === "block" ? type.block : "").size;
35
+ ? { size: type.length * block.size, height: block.height }
36
+ : block;
25
37
  };
26
- const allocations = new Map<string, { size: number; height: number }>();
38
+ const allocations = new Map<string, Allocation>();
27
39
  const allocating = new Set<string>();
28
- const allocation = (id: string): { size: number; height: number } => {
40
+ const allocation = (id: string): Allocation => {
29
41
  if (allocating.size >= maxNestingDepth) {
30
42
  reject(
31
43
  `Static block allocation nesting exceeds ${maxNestingDepth} levels.`,
@@ -40,13 +52,10 @@ export function checkStaticAllocation(
40
52
  return cached;
41
53
  }
42
54
  allocating.add(id);
43
- const block = blocks.get(id)!;
55
+ const block = lookup(blocks, id, "block");
44
56
  const children = block.state
45
57
  .filter((item) => item.storage === "instance")
46
- .map((item) => ({
47
- height: allocation(instancedBlock(item.type, types)!.block).height,
48
- size: instanceSize(item.type),
49
- }));
58
+ .map((item) => instance(item.type));
50
59
  const own = [
51
60
  ...block.inputs,
52
61
  ...block.outputs,
@@ -75,11 +84,13 @@ export function checkStaticAllocation(
75
84
  return (
76
85
  sum +
77
86
  (instancedBlock(variable.type, types)
78
- ? instanceSize(variable.type)
87
+ ? instance(variable.type).size
79
88
  : payload(variable.type))
80
89
  );
81
90
  }, 0);
82
91
  if (staticPayload > maxScalarElements) {
83
- reject("Static module storage exceeds one million scalar elements.");
92
+ reject(
93
+ `Static module storage exceeds ${maxScalarElementsText} scalar elements.`,
94
+ );
84
95
  }
85
96
  }
@@ -1,3 +1,4 @@
1
+ import type { jobStateFields } from "@tsplc/debug/manifest";
1
2
  import type { BinaryOperator, UnaryOperator } from "@tsplc/iec/arithmetic";
2
3
  import {
3
4
  type CoreExpression,
@@ -5,11 +6,16 @@ import {
5
6
  type CoreFunctionBlock,
6
7
  type CorePath,
7
8
  type CoreStatement,
9
+ constantIndex,
10
+ isBlockRoutine,
11
+ isTemporary,
8
12
  nestedBodies,
13
+ wholeAssign,
9
14
  } from "./core-model";
10
15
  import type { SourceSpan } from "./diagnostics";
11
16
  import type { Constant, Variable } from "./model";
12
- import { isTemporary } from "./routine";
17
+ import { loweredLogical, loweredSelect } from "./short-circuit";
18
+ import { lookup } from "./tables";
13
19
 
14
20
  type Routine = CoreFunction | CoreFunctionBlock;
15
21
  type Assign = Extract<CoreStatement, { kind: "assign" }>;
@@ -193,40 +199,28 @@ const merged = (...all: readonly Exits[]): Exits => ({
193
199
  continues: all.flatMap((exits) => exits.continues),
194
200
  });
195
201
 
196
- const wholeAssign = (
197
- item: CoreStatement | undefined,
198
- root: string,
199
- ): item is Assign =>
200
- item?.kind === "assign" && item.root === root && !item.path?.length;
201
-
202
- const loadedRoot = (value: CoreExpression): string | undefined =>
203
- value.kind === "load" && !value.path?.length ? value.root : undefined;
204
-
205
- const constantIndex = (value: CoreExpression): number | undefined =>
206
- value.kind === "constant" && value.value.kind === "integer"
207
- ? Number(value.value.value)
208
- : undefined;
202
+ /** A field of a job's state, which the frontend's generated job block declares. */
203
+ const jobField = (
204
+ job: CoreFunctionBlock,
205
+ name: keyof typeof jobStateFields,
206
+ ): string | undefined => job.state.find((field) => field.name === name)?.id;
209
207
 
210
208
  /** A constant's field or element, when it has one. */
211
209
  const constantPart = (
212
210
  value: Constant,
213
211
  segment: ReconstructedSegment,
214
- lower: number,
215
212
  ): Constant | undefined => {
216
213
  if (segment.kind === "field") {
217
214
  return value.kind === "record" ? value.fields[segment.name] : undefined;
218
215
  }
219
- const index =
220
- segment.value.kind === "constant" && segment.value.value.kind === "integer"
221
- ? Number(segment.value.value.value)
222
- : undefined;
216
+ const index = constantIndex(segment.value);
223
217
  return value.kind === "array" && index !== undefined
224
- ? value.items[index - lower]
218
+ ? value.items[index]
225
219
  : undefined;
226
220
  };
227
221
 
228
222
  /** The names along a path of fields and constant indexes, or nothing when an index is dynamic. */
229
- const staticNames = (
223
+ export const staticNames = (
230
224
  path: readonly ReconstructedSegment[],
231
225
  ): string[] | undefined => {
232
226
  const names: string[] = [];
@@ -283,11 +277,7 @@ export const projectReconstruction = (
283
277
  }
284
278
  case "array": {
285
279
  const index =
286
- segment.kind === "index" &&
287
- segment.value.kind === "constant" &&
288
- segment.value.value.kind === "integer"
289
- ? Number(segment.value.value.value)
290
- : undefined;
280
+ segment.kind === "index" ? constantIndex(segment.value) : undefined;
291
281
  const item =
292
282
  index === undefined ? undefined : node.items[index - node.lower];
293
283
  return item
@@ -295,7 +285,7 @@ export const projectReconstruction = (
295
285
  : opaque("an element at a dynamic index", type, node.span);
296
286
  }
297
287
  case "constant": {
298
- const part = constantPart(node.value, segment, 0);
288
+ const part = constantPart(node.value, segment);
299
289
  return part
300
290
  ? projectReconstruction(
301
291
  { kind: "constant", value: part, type, span: node.span },
@@ -337,15 +327,15 @@ export function pathConditions(
337
327
  .map((local) => [local.id, local]),
338
328
  );
339
329
  const parameters = new Map(
340
- "parameters" in routine
341
- ? routine.parameters.map((parameter, index) => [parameter.id, index])
342
- : [],
330
+ isBlockRoutine(routine)
331
+ ? []
332
+ : routine.parameters.map((parameter, index) => [parameter.id, index]),
343
333
  );
344
334
  const typeOf = (root: string): string | undefined =>
345
335
  locals.get(root)?.type ??
346
- ("parameters" in routine
347
- ? routine.parameters.find((parameter) => parameter.id === root)?.type
348
- : undefined) ??
336
+ (isBlockRoutine(routine)
337
+ ? undefined
338
+ : routine.parameters.find((parameter) => parameter.id === root)?.type) ??
349
339
  variables.get(root)?.type;
350
340
 
351
341
  const positions = new Map<CoreStatement, number>();
@@ -376,49 +366,22 @@ export function pathConditions(
376
366
  }
377
367
  };
378
368
  number(routine.body);
379
- const position = (item: CoreStatement): number => positions.get(item) ?? 0;
380
- // `a && b` lowers to `t := a; if t { …; t := b }`, `||` the same under `if NOT t`, and
381
- // `c ? x : y` to `if c { …; t := x } else { …; t := y }`.
369
+ const position = (item: CoreStatement): number =>
370
+ lookup(positions, item, "statement");
371
+ // A temporary that only a lowered `&&`, `||` or `?:` defines stands for it.
372
+ const lowered = (root: string) =>
373
+ temporaries.has(root) && definitions.get(root)?.length === 2;
382
374
  for (const items of sequences) {
383
375
  items.forEach((item, index) => {
384
- const next = items[index + 1];
385
- if (
386
- item.kind === "assign" &&
387
- !item.path?.length &&
388
- temporaries.has(item.root) &&
389
- next?.kind === "if" &&
390
- !next.else.length
391
- ) {
392
- const negated =
393
- next.condition.kind === "unary" && next.condition.operator === "not";
394
- const tested = loadedRoot(
395
- next.condition.kind === "unary" && next.condition.operator === "not"
396
- ? next.condition.operand
397
- : next.condition,
398
- );
399
- const right = next.then.at(-1);
400
- if (
401
- tested === item.root &&
402
- wholeAssign(right, item.root) &&
403
- definitions.get(item.root)?.length === 2
404
- ) {
405
- const operator = negated ? "or" : "and";
406
- logicals.set(item.root, { operator, left: item, right });
407
- synthetic.set(next, { operator, left: item });
408
- }
376
+ const logical = loweredLogical(item, items[index + 1]);
377
+ if (logical && lowered(logical.left.root)) {
378
+ const { operator, left, right, test } = logical;
379
+ logicals.set(left.root, { operator, left, right });
380
+ synthetic.set(test, { operator, left });
409
381
  }
410
- if (item.kind === "if") {
411
- const then = item.then.at(-1);
412
- const otherwise = item.else.at(-1);
413
- if (
414
- then?.kind === "assign" &&
415
- temporaries.has(then.root) &&
416
- wholeAssign(then, then.root) &&
417
- wholeAssign(otherwise, then.root) &&
418
- definitions.get(then.root)?.length === 2
419
- ) {
420
- selects.set(then.root, { test: item, then, else: otherwise });
421
- }
382
+ const select = loweredSelect(item);
383
+ if (select && lowered(select.root)) {
384
+ selects.set(select.root, select);
422
385
  }
423
386
  });
424
387
  }
@@ -686,11 +649,8 @@ export function pathConditions(
686
649
  };
687
650
 
688
651
  const job =
689
- "inputs" in routine && routine.job
690
- ? {
691
- busy: routine.state.find((field) => field.name === "busy")?.id,
692
- step: routine.state.find((field) => field.name === "step")?.id,
693
- }
652
+ isBlockRoutine(routine) && routine.job
653
+ ? { busy: jobField(routine, "busy"), step: jobField(routine, "step") }
694
654
  : undefined;
695
655
  const isField = (node: Reconstruction, field: string | undefined): boolean =>
696
656
  field !== undefined &&
@@ -3,14 +3,13 @@ import type { SourceSpan } from "./diagnostics";
3
3
  import type {
4
4
  Constant,
5
5
  FunctionBlock,
6
- MethodOwner,
7
6
  PlcFunction,
8
7
  PlcModule,
9
8
  PlcProgram,
10
9
  TelemetryCall,
11
10
  Variable,
12
11
  } from "./model";
13
- import type { PlcType } from "./types";
12
+ import { instancedBlock, type PlcType } from "./types";
14
13
 
15
14
  // Core expressions contain no source-level calls. Their effects have already
16
15
  // become ordered statements, and every place has passed storage/bounds checks.
@@ -102,6 +101,12 @@ export type CoreStatement = { readonly span: SourceSpan } & (
102
101
  | { readonly kind: "break" | "continue" }
103
102
  | ({ readonly kind: "telemetry" } & TelemetryCall<CoreExpression>)
104
103
  );
104
+ /** Whether a statement assigns the whole of `root`. */
105
+ export const wholeAssign = (
106
+ item: CoreStatement | undefined,
107
+ root: string,
108
+ ): item is Extract<CoreStatement, { kind: "assign" }> =>
109
+ item?.kind === "assign" && item.root === root && !item.path?.length;
105
110
  /** The statement lists nested directly inside a statement. */
106
111
  export const nestedBodies = (
107
112
  item: CoreStatement,
@@ -117,6 +122,30 @@ export const nestedBodies = (
117
122
  }
118
123
  return [];
119
124
  };
125
+ /** A statement with each list `nestedBodies` returns replaced by `map` of it. */
126
+ export const mapBodies = (
127
+ item: CoreStatement,
128
+ map: (body: readonly CoreStatement[]) => readonly CoreStatement[],
129
+ ): CoreStatement => {
130
+ switch (item.kind) {
131
+ case "if":
132
+ // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
133
+ return { ...item, then: map(item.then), else: map(item.else) };
134
+ case "switch":
135
+ return {
136
+ ...item,
137
+ cases: item.cases.map((branch) => ({
138
+ ...branch,
139
+ body: map(branch.body),
140
+ })),
141
+ fallback: map(item.fallback),
142
+ };
143
+ case "for":
144
+ return { ...item, body: map(item.body) };
145
+ default:
146
+ return item;
147
+ }
148
+ };
120
149
  /**
121
150
  * The storage roots a statement writes itself, in statement order: an assignment's target, a
122
151
  * loop's counter, a call's destination and every place it borrows. Nested bodies and the
@@ -144,16 +173,24 @@ export const directWrites = (item: CoreStatement): readonly string[] => {
144
173
  }
145
174
  return [];
146
175
  };
147
- export interface CoreFunction {
148
- readonly owner?: MethodOwner;
149
- readonly origin?: PlcFunction["origin"];
150
- readonly id: string;
151
- readonly name: string;
152
- readonly parameters: readonly Variable[];
153
- readonly result?: string;
154
- readonly locals: readonly Variable[];
176
+ /** The routine a statement runs: an invoke's function, or the block its instance's type instantiates. */
177
+ export const calledRoutine = (
178
+ item: CoreStatement,
179
+ variableOf: (id: string) => Variable | undefined,
180
+ types: ReadonlyMap<string, PlcType>,
181
+ ): string | undefined => {
182
+ if (item.kind === "invoke") {
183
+ return item.function;
184
+ }
185
+ if (item.kind !== "blockUpdate") {
186
+ return undefined;
187
+ }
188
+ const variable = variableOf(item.instance);
189
+ return variable && instancedBlock(variable.type, types)?.block;
190
+ };
191
+ export interface CoreFunction
192
+ extends Readonly<Omit<PlcFunction, "body" | "bounds">> {
155
193
  readonly body: readonly CoreStatement[];
156
- readonly span: SourceSpan;
157
194
  }
158
195
  export interface CoreFunctionBlock
159
196
  extends Readonly<Omit<FunctionBlock, "body">> {
@@ -170,3 +207,83 @@ export interface VerifiedCoreModule {
170
207
  readonly blocks: readonly CoreFunctionBlock[];
171
208
  readonly programs: readonly PlcProgram[];
172
209
  }
210
+
211
+ const verifiedModules = new WeakSet<object>();
212
+ export function isVerifiedCore(value: unknown): value is VerifiedCoreModule {
213
+ return (
214
+ typeof value === "object" && value !== null && verifiedModules.has(value)
215
+ );
216
+ }
217
+
218
+ /** Freezes a value and everything it holds. */
219
+ export function freeze(value: unknown): void {
220
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
221
+ return;
222
+ }
223
+ for (const child of Object.values(value)) {
224
+ freeze(child);
225
+ }
226
+ Object.freeze(value);
227
+ }
228
+
229
+ /**
230
+ * Admits a module across the trust boundary. Only normalization, and transformations of an
231
+ * admitted module that keep what it verified, call this.
232
+ */
233
+ export function admitCore(core: VerifiedCoreModule): VerifiedCoreModule {
234
+ freeze(core);
235
+ verifiedModules.add(core);
236
+ return core;
237
+ }
238
+
239
+ /** Whether a routine is a function block rather than a function. */
240
+ export function isBlockRoutine(
241
+ routine: CoreFunction | CoreFunctionBlock,
242
+ ): routine is CoreFunctionBlock;
243
+ export function isBlockRoutine(
244
+ routine: PlcFunction | FunctionBlock,
245
+ ): routine is FunctionBlock;
246
+ export function isBlockRoutine(
247
+ routine: CoreFunction | CoreFunctionBlock | PlcFunction | FunctionBlock,
248
+ ): boolean {
249
+ return "inputs" in routine;
250
+ }
251
+
252
+ /** The fields of a block's instance, in the order its type declares them: inputs, outputs, then state. */
253
+ export const instanceFields = (
254
+ block: CoreFunctionBlock,
255
+ ): readonly Variable[] => [...block.inputs, ...block.outputs, ...block.state];
256
+
257
+ /** Every variable a routine declares: a function's parameters and locals, a block's ports, state and locals. */
258
+ export const routineVariables = (
259
+ routine: CoreFunction | CoreFunctionBlock,
260
+ ): readonly Variable[] =>
261
+ isBlockRoutine(routine)
262
+ ? [...instanceFields(routine), ...routine.locals]
263
+ : [...routine.parameters, ...routine.locals];
264
+
265
+ const temporaryPrefix = (routine: string) => `${routine}:temporary:`;
266
+ export const temporaryId = (routine: string, index: number) =>
267
+ `${temporaryPrefix(routine)}${index}`;
268
+
269
+ /** Whether a local is a temporary the normalizer made for `routine`, rather than one its source declares. */
270
+ export function isTemporary(routine: string, variable: Variable): boolean {
271
+ const prefix = temporaryPrefix(routine);
272
+ return (
273
+ variable.storage === "local" &&
274
+ variable.id.startsWith(prefix) &&
275
+ /^\d+$/.test(variable.id.slice(prefix.length))
276
+ );
277
+ }
278
+
279
+ /**
280
+ * An index's value when it is an integer constant. Structural, because conditions' reconstructions
281
+ * carry indexes too, and they are not core expressions.
282
+ */
283
+ export const constantIndex = (expression: {
284
+ readonly kind: string;
285
+ readonly value?: Constant;
286
+ }): number | undefined =>
287
+ expression.kind === "constant" && expression.value?.kind === "integer"
288
+ ? Number(expression.value.value)
289
+ : undefined;