@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,18 +1,26 @@
1
- import { primitiveTypes } from "@tsplc/compiler/ir";
2
1
  import ts from "typescript";
3
2
  import { joined, Mapped, mapped, type Part } from "../positions";
4
- import type { DialectText } from "./dialect";
3
+ import { isWrapper } from "../types";
4
+ import { callbackArgument, searchTarget } from "./array-searches";
5
+ import { providedByRuntime } from "./declarations";
5
6
  import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
6
- import { Emitter, type Frame } from "./frame";
7
- import type { Initializers } from "./initializers";
8
- import type { Model, ModelNode } from "./model";
9
- import { referenceIndex, referenceLayout } from "./references";
7
+ import { Emitter, type Frame, looping } from "./frame";
8
+ import { arrayLayout } from "./layouts";
9
+ import type { ModelNode } from "./model";
10
+ import {
11
+ noReference,
12
+ referenceIndex,
13
+ referenceLayout,
14
+ references,
15
+ } from "./references";
10
16
  import {
11
17
  type Counted,
12
18
  constant,
13
19
  type FunctionLike,
14
- repeatable,
20
+ isStoredState,
21
+ known,
15
22
  SpecializeError,
23
+ unwrapped,
16
24
  type Value,
17
25
  } from "./values";
18
26
 
@@ -82,41 +90,28 @@ const adapters = new Set(["map", "filter", "take", "drop", "flatMap"]);
82
90
  * each read only when its index is in range.
83
91
  */
84
92
  export class Iterators {
85
- private readonly model: Model;
86
- private readonly checker: ts.TypeChecker;
87
- private readonly dialect: DialectText;
88
- private readonly initializers: Initializers;
89
93
  private runner: GeneratorRunner | undefined;
90
- /** How many times the body of each loop being written can run, outermost first; undefined for a loop with no counted bound. */
91
- private readonly loops: (number | undefined)[] = [];
92
94
 
93
95
  constructor(
94
- context: SpecializeContext,
95
- private readonly expressions: ExpressionSpecializer,
96
- ) {
97
- this.model = context.model;
98
- this.checker = context.checker;
99
- this.dialect = context.dialect;
100
- this.initializers = context.initializers;
101
- }
96
+ private readonly context: SpecializeContext,
97
+ private readonly expressions: Pick<
98
+ ExpressionSpecializer,
99
+ | "expression"
100
+ | "invoke"
101
+ | "inOrder"
102
+ | "member"
103
+ | "held"
104
+ | "temporaryOf"
105
+ | "localType"
106
+ | "equality"
107
+ | "speculatively"
108
+ >,
109
+ ) {}
102
110
 
103
111
  attach(runner: GeneratorRunner): void {
104
112
  this.runner = runner;
105
113
  }
106
114
 
107
- /**
108
- * Writes the body of a loop that stays a loop in the PLC. A yield in it runs up to `runs` times,
109
- * which sizes a snapshot of the generator; an unrolled loop needs none, as each step is written out.
110
- */
111
- looping<T>(runs: number | undefined, body: () => T): T {
112
- this.loops.push(runs);
113
- try {
114
- return body();
115
- } finally {
116
- this.loops.pop();
117
- }
118
- }
119
-
120
115
  /** A helper called on an iterator: what it is worth, or undefined when the call is no iterator helper. */
121
116
  call(node: ts.CallExpression, frame: Frame): Value | undefined {
122
117
  const helper = this.helper(node);
@@ -145,8 +140,85 @@ export class Iterators {
145
140
  : undefined;
146
141
  }
147
142
 
148
- /** A method called on a counted array. */
149
- method(
143
+ /**
144
+ * A method called on a counted array, or a slice of a runtime array; undefined for a receiver that
145
+ * is neither.
146
+ */
147
+ arrayCall(
148
+ name: string,
149
+ value: Value,
150
+ node: ts.CallExpression,
151
+ frame: Frame,
152
+ ): Value | undefined {
153
+ if (value.kind === "counted") {
154
+ return this.method(name, value, node, frame);
155
+ }
156
+ const stored = name === "slice" ? this.storage(value) : undefined;
157
+ return stored && this.method(name, stored, node, frame);
158
+ }
159
+
160
+ /**
161
+ * `some`, `every` and `includes` over elements setup fixed, as one expression: each element's
162
+ * test is written out.
163
+ */
164
+ unrolled(
165
+ name: "some" | "every" | "includes",
166
+ items: readonly Value[],
167
+ node: ts.CallExpression,
168
+ frame: Frame,
169
+ ): Value {
170
+ return this.tested(
171
+ name,
172
+ {
173
+ kind: "counted",
174
+ source: { kind: "items", items },
175
+ start: constant(0),
176
+ end: constant(items.length),
177
+ },
178
+ items,
179
+ node,
180
+ frame,
181
+ );
182
+ }
183
+
184
+ /** A generator call, as a for…of runs it: its body, the object it runs on and its arguments. */
185
+ generator(node: ts.Expression, frame: Frame): GeneratorCall | undefined {
186
+ if (!ts.isCallExpression(node)) {
187
+ return undefined;
188
+ }
189
+ const declaration =
190
+ this.context.checker.getResolvedSignature(node)?.declaration;
191
+ if (
192
+ !declaration ||
193
+ !(
194
+ ts.isFunctionDeclaration(declaration) ||
195
+ ts.isMethodDeclaration(declaration) ||
196
+ ts.isFunctionExpression(declaration)
197
+ ) ||
198
+ !declaration.asteriskToken ||
199
+ !declaration.body
200
+ ) {
201
+ return undefined;
202
+ }
203
+ const callee = node.expression;
204
+ const target = ts.isPropertyAccessExpression(callee)
205
+ ? this.expressions.member(
206
+ this.expressions.expression(callee.expression, frame),
207
+ callee.name.text,
208
+ callee,
209
+ frame,
210
+ )
211
+ : this.expressions.expression(callee, frame);
212
+ const self = target.kind === "function" ? target.self : undefined;
213
+ const args = this.expressions.inOrder(
214
+ node.arguments,
215
+ (argument) => this.expressions.expression(argument, frame),
216
+ frame,
217
+ );
218
+ return { declaration, self, args };
219
+ }
220
+
221
+ private method(
150
222
  name: string,
151
223
  receiver: Counted,
152
224
  node: ts.CallExpression,
@@ -209,46 +281,35 @@ export class Iterators {
209
281
  }
210
282
  }
211
283
 
212
- /** The counted array a method is called on: the receiver when it is one, or a runtime array a slice is taken of. */
213
- receiver(value: Value, method: string): Counted | undefined {
214
- if (value.kind === "counted") {
215
- return value;
216
- }
217
- return method === "slice" ? this.storage(value) : undefined;
218
- }
219
-
220
284
  /**
221
285
  * A runtime array as a counted array of all its elements, for a slice of it: one a routine was
222
286
  * passed, or a runtime record's field, whose layout says how many elements it stores. Undefined
223
287
  * for an array whose elements are each known, which a slice reads one by one.
224
288
  */
225
289
  private storage(value: Value): Counted | undefined {
226
- if (
227
- value.kind !== "code" ||
228
- value.length !== undefined ||
229
- value.layout === undefined
230
- ) {
290
+ if (value.kind !== "code" || value.length !== undefined || !value.layout) {
231
291
  return undefined;
232
292
  }
233
- const stored = storedArray(value.layout);
234
- if (!stored) {
293
+ const { layout } = value;
294
+ const { bound } = layout;
295
+ if (bound === undefined) {
235
296
  return undefined;
236
297
  }
237
- const { bound } = stored;
238
- const declared = value.declared && this.model.elementType(value.declared);
298
+ const declared =
299
+ value.declared && this.context.model.elementType(value.declared);
239
300
  return {
240
301
  kind: "counted",
241
302
  source: {
242
303
  kind: "array",
243
304
  text: value.text,
244
- layout: value.layout,
305
+ layout: layout.text,
245
306
  bound,
246
307
  element: (index) => ({
247
308
  kind: "code",
248
309
  text: mapped`${value.text}[${index}]`,
249
310
  declared,
250
311
  place: value.place,
251
- iec: value.elementIec ?? stored.iec,
312
+ iec: value.elementIec ?? layout.elementIec,
252
313
  copyOf: value.copyOf,
253
314
  }),
254
315
  snapshot: false,
@@ -276,11 +337,8 @@ export class Iterators {
276
337
  */
277
338
  element(counted: Counted, index: Value, at: ts.Node, frame: Frame): Value {
278
339
  const { source } = counted;
279
- if (index.kind !== "const" && index.kind !== "code") {
280
- throw new SpecializeError(at, "Index an array with a number.");
281
- }
282
340
  const offset = known(index);
283
- if (index.kind === "const" && offset === undefined) {
341
+ if (index.kind !== "code" && offset === undefined) {
284
342
  throw new SpecializeError(at, "Index an array with a number.");
285
343
  }
286
344
  if (offset !== undefined && offset < 0) {
@@ -306,7 +364,7 @@ export class Iterators {
306
364
  // A reference has an id for undefined, whatever the element's type says.
307
365
  return {
308
366
  ...item,
309
- index: mapped`(${inside} ? ${item.index} : -1)`,
367
+ index: mapped`(${inside} ? ${item.index} : ${noReference})`,
310
368
  optional: true,
311
369
  };
312
370
  }
@@ -324,17 +382,18 @@ export class Iterators {
324
382
  ) {
325
383
  return item;
326
384
  }
327
- const declared = this.checker.getTypeAtLocation(at);
328
- const optional = this.checker.getNonNullableType(declared) !== declared;
385
+ const { checker, dialect } = this.context;
386
+ const declared = checker.getTypeAtLocation(at);
387
+ const optional = checker.getNonNullableType(declared) !== declared;
329
388
  const empty = optional
330
- ? this.dialect.assignmentText(constant(undefined), declared)
331
- : this.initializers.defaultOf(declared);
389
+ ? dialect.assignmentText(constant(undefined), declared, undefined)
390
+ : this.context.initializers.defaultOf(declared);
332
391
  const result = frame.emitter.temporary();
333
392
  frame.emitter.line(
334
393
  mapped`let ${result}: ${this.expressions.localType(declared)} = ${empty};`,
335
394
  );
336
395
  frame.emitter.line(
337
- mapped`if (${inside}) { ${result} = ${this.dialect.assignmentText(item, declared)}; }`,
396
+ mapped`if (${inside}) { ${result} = ${dialect.assignmentText(item, declared, undefined)}; }`,
338
397
  );
339
398
  return {
340
399
  kind: "code",
@@ -374,7 +433,7 @@ export class Iterators {
374
433
  }
375
434
  const label = frame.emitter.local("tsplcStep");
376
435
  frame.emitter.open(`${label}: {`);
377
- this.looping(source.bound, () =>
436
+ looping(frame, source.bound, () =>
378
437
  visit({
379
438
  value: source.element(counter),
380
439
  index: this.difference(this.number(counter), start),
@@ -409,51 +468,6 @@ export class Iterators {
409
468
  );
410
469
  }
411
470
 
412
- /**
413
- * A counted array passed to a routine: the routine takes its local array and each bound decided
414
- * at run time as parameters of its own, as `lift` makes them.
415
- */
416
- lifted(
417
- counted: Counted,
418
- base: string,
419
- frame: Frame,
420
- parameters: string[],
421
- runtimeArgs: (string | Mapped)[],
422
- lift: (value: Value, name: string) => Value,
423
- ): Value {
424
- const { source } = counted;
425
- const start = lift(counted.start, `${base}_start`);
426
- const end = lift(counted.end, `${base}_end`);
427
- if (source.kind === "items") {
428
- return {
429
- kind: "counted",
430
- source: {
431
- kind: "items",
432
- items: source.items.map((item, index) =>
433
- lift(item, `${base}_${index}`),
434
- ),
435
- },
436
- start,
437
- end,
438
- };
439
- }
440
- const local = frame.emitter.local(base);
441
- parameters.push(`${local}: ${source.layout}`);
442
- runtimeArgs.push(source.text);
443
- return {
444
- kind: "counted",
445
- source: {
446
- ...source,
447
- text: local,
448
- element: (index) => reread(source.element(index), local, index),
449
- // The routine is passed the end as it is now, which a count it never saw can't be compared with.
450
- filled: undefined,
451
- },
452
- start,
453
- end,
454
- };
455
- }
456
-
457
471
  private get generators(): GeneratorRunner {
458
472
  if (!this.runner) {
459
473
  throw new Error("Nothing runs generators yet.");
@@ -472,14 +486,13 @@ export class Iterators {
472
486
  return undefined;
473
487
  }
474
488
  const receiver = node.expression.expression;
475
- const type = this.checker.getTypeAtLocation(receiver);
476
- if (!type.getProperty("next") || !type.getProperty("toArray")) {
477
- return undefined;
478
- }
479
- // The helpers are JavaScript's own, declared by its library; a program's class may share their names.
480
- const declaration = this.checker.getSymbolAtLocation(node.expression.name)
481
- ?.declarations?.[0];
482
- if (!declaration?.getSourceFile().isDeclarationFile) {
489
+ const type = this.context.checker.getTypeAtLocation(receiver);
490
+ // The helpers are JavaScript's own; a program's class may share their names.
491
+ if (
492
+ !type.getProperty("next") ||
493
+ !type.getProperty("toArray") ||
494
+ !providedByRuntime(this.context.checker, node.expression.name)
495
+ ) {
483
496
  return undefined;
484
497
  }
485
498
  return { name: node.expression.name.text, receiver };
@@ -532,17 +545,19 @@ export class Iterators {
532
545
  { sliced }: { sliced: boolean },
533
546
  ): Value | undefined {
534
547
  if (ts.isIdentifier(node)) {
535
- const symbol = this.checker.getSymbolAtLocation(node);
548
+ const symbol = this.context.checker.getSymbolAtLocation(node);
536
549
  return symbol && frame.env.get(symbol);
537
550
  }
538
551
  if (!sliced || !ts.isPropertyAccessExpression(node)) {
539
552
  return undefined;
540
553
  }
541
554
  try {
542
- return this.expressions.expression(node, {
543
- ...frame,
544
- emitter: new Emitter(node),
545
- });
555
+ return this.expressions.speculatively(() =>
556
+ this.expressions.expression(node, {
557
+ ...frame,
558
+ emitter: new Emitter(node),
559
+ }),
560
+ );
546
561
  } catch (cause) {
547
562
  if (cause instanceof SpecializeError) {
548
563
  return undefined;
@@ -554,7 +569,7 @@ export class Iterators {
554
569
  /** A generator call, read through the helpers that give another iterator. */
555
570
  private pipeline(node: ts.Expression, frame: Frame): Traversal {
556
571
  const inner = unwrapped(node);
557
- const generator = this.expressions.generator(inner, frame);
572
+ const generator = this.generator(inner, frame);
558
573
  if (generator) {
559
574
  return this.generated(generator, inner);
560
575
  }
@@ -568,9 +583,17 @@ export class Iterators {
568
583
  const source = this.pipeline(helper.receiver, frame);
569
584
  switch (helper.name) {
570
585
  case "map":
571
- return this.mapped(source, this.callback(inner, frame), inner);
586
+ return this.mapped(
587
+ source,
588
+ callbackArgument(inner, frame, this.expressions),
589
+ inner,
590
+ );
572
591
  case "filter":
573
- return this.filtered(source, this.callback(inner, frame), inner);
592
+ return this.filtered(
593
+ source,
594
+ callbackArgument(inner, frame, this.expressions),
595
+ inner,
596
+ );
574
597
  case "take":
575
598
  return this.taken(source, this.amount(inner, frame));
576
599
  case "drop":
@@ -586,27 +609,14 @@ export class Iterators {
586
609
  private generated(generator: GeneratorCall, at: ts.Node): Traversal {
587
610
  return {
588
611
  run: (frame, visit) => {
589
- const depth = this.loops.length;
612
+ const depth = frame.loops.length;
590
613
  this.generators.run(generator, frame, at, (value, jumps) =>
591
- visit({ ...jumps, value, repeats: this.repeats(depth) }),
614
+ visit({ ...jumps, value, repeats: repeats(frame, depth) }),
592
615
  );
593
616
  },
594
617
  };
595
618
  }
596
619
 
597
- /** How many times code written now can run, for the loops entered since `depth`. */
598
- private repeats(depth: number): number | undefined {
599
- return this.loops
600
- .slice(depth)
601
- .reduce<number | undefined>(
602
- (product, runs) =>
603
- product === undefined || runs === undefined
604
- ? undefined
605
- : product * runs,
606
- 1,
607
- );
608
- }
609
-
610
620
  private mapped(
611
621
  source: Traversal,
612
622
  callback: Value,
@@ -642,7 +652,6 @@ export class Iterators {
642
652
  run: (frame, visit) => {
643
653
  const index = this.indexer(source, callback, 1, frame);
644
654
  source.run(frame, (element) => {
645
- // The test and whatever reads the element next both read it, so it is read once.
646
655
  const value = this.once(element.value, frame);
647
656
  const test = this.expressions.invoke(
648
657
  callback,
@@ -728,7 +737,7 @@ export class Iterators {
728
737
  switch (name) {
729
738
  case "some":
730
739
  case "every": {
731
- const callback = this.callback(node, frame);
740
+ const callback = callbackArgument(node, frame, this.expressions);
732
741
  const index = this.indexer(traversal, callback, 1, frame);
733
742
  return this.decided(
734
743
  traversal,
@@ -745,7 +754,7 @@ export class Iterators {
745
754
  );
746
755
  }
747
756
  case "includes": {
748
- const target = this.target(node, frame);
757
+ const target = searchTarget(node, frame, this.expressions);
749
758
  return this.decided(traversal, node, frame, { some: true }, (element) =>
750
759
  this.expressions.equality(element.value, target, { negate: false }),
751
760
  );
@@ -753,7 +762,7 @@ export class Iterators {
753
762
  case "find":
754
763
  return this.find(traversal, node, frame);
755
764
  case "findIndex": {
756
- const callback = this.callback(node, frame);
765
+ const callback = callbackArgument(node, frame, this.expressions);
757
766
  return this.position(traversal, node, frame, (element) =>
758
767
  this.expressions.invoke(
759
768
  callback,
@@ -764,13 +773,13 @@ export class Iterators {
764
773
  );
765
774
  }
766
775
  case "indexOf": {
767
- const target = this.target(node, frame);
776
+ const target = searchTarget(node, frame, this.expressions);
768
777
  return this.position(traversal, node, frame, (element) =>
769
778
  this.expressions.equality(element.value, target, { negate: false }),
770
779
  );
771
780
  }
772
781
  case "forEach": {
773
- const callback = this.callback(node, frame);
782
+ const callback = callbackArgument(node, frame, this.expressions);
774
783
  const index = this.indexer(traversal, callback, 1, frame);
775
784
  traversal.run(frame, (element) => {
776
785
  const result = this.expressions.invoke(
@@ -825,7 +834,7 @@ export class Iterators {
825
834
  return {
826
835
  kind: "code",
827
836
  text: result,
828
- declared: this.checker.getBooleanType(),
837
+ declared: this.context.checker.getBooleanType(),
829
838
  place: true,
830
839
  };
831
840
  }
@@ -839,9 +848,9 @@ export class Iterators {
839
848
  node: ts.CallExpression,
840
849
  frame: Frame,
841
850
  ): Value {
842
- const callback = this.callback(node, frame);
851
+ const callback = callbackArgument(node, frame, this.expressions);
843
852
  const index = this.indexer(traversal, callback, 1, frame);
844
- const declared = this.checker.getTypeAtLocation(node);
853
+ const declared = this.context.checker.getTypeAtLocation(node);
845
854
  const values = this.trial(traversal, frame).map(({ value }) => value);
846
855
  const referred = references(values);
847
856
  const slot = referred
@@ -904,7 +913,7 @@ export class Iterators {
904
913
  return {
905
914
  kind: "code",
906
915
  text: result,
907
- declared: this.checker.getNumberType(),
916
+ declared: this.context.checker.getNumberType(),
908
917
  place: true,
909
918
  };
910
919
  }
@@ -915,7 +924,7 @@ export class Iterators {
915
924
  node: ts.CallExpression,
916
925
  frame: Frame,
917
926
  ): Value {
918
- const callback = this.callback(node, frame);
927
+ const callback = callbackArgument(node, frame, this.expressions);
919
928
  const [, initialNode] = node.arguments;
920
929
  if (!initialNode) {
921
930
  throw new SpecializeError(
@@ -923,11 +932,11 @@ export class Iterators {
923
932
  "reduce needs an initial value here: whether there is a first element is decided at run time.",
924
933
  );
925
934
  }
926
- const declared = this.checker.getTypeAtLocation(node);
935
+ const declared = this.context.checker.getTypeAtLocation(node);
927
936
  const initial = this.expressions.expression(initialNode, frame, declared);
928
937
  const total = frame.emitter.temporary();
929
938
  frame.emitter.line(
930
- mapped`let ${total}: ${this.expressions.localType(declared)} = ${this.dialect.assignmentText(initial, declared)};`,
939
+ mapped`let ${total}: ${this.expressions.localType(declared)} = ${this.context.dialect.assignmentText(initial, declared, undefined)};`,
931
940
  );
932
941
  const accumulated: Value = {
933
942
  kind: "code",
@@ -944,7 +953,7 @@ export class Iterators {
944
953
  frame,
945
954
  );
946
955
  frame.emitter.line(
947
- mapped`${total} = ${this.dialect.assignmentText(next, declared)};`,
956
+ mapped`${total} = ${this.context.dialect.assignmentText(next, declared, undefined)};`,
948
957
  );
949
958
  });
950
959
  return accumulated;
@@ -972,9 +981,8 @@ export class Iterators {
972
981
  ? Number.POSITIVE_INFINITY
973
982
  : trial.reduce((total, { repeats }) => total + (repeats ?? 0), 0);
974
983
  const bound = Math.min(yielded, traversal.limit ?? yielded);
975
- const size = Math.max(bound, 1);
976
- const element = this.model.elementType(
977
- this.checker.getTypeAtLocation(node),
984
+ const element = this.context.model.elementType(
985
+ this.context.checker.getTypeAtLocation(node),
978
986
  );
979
987
  const values = trial.map(({ value }) => value);
980
988
  const referred = references(values);
@@ -983,26 +991,28 @@ export class Iterators {
983
991
  : this.valueSlot(values, element, node);
984
992
  const array = frame.emitter.temporary();
985
993
  const count = frame.emitter.temporary();
986
- const layout = `FixedArray<${slot.type}, ${size}>`;
987
- frame.emitter.line(`let ${array}: ${layout} = defaultValue<${layout}>();`);
994
+ const layout = arrayLayout(slot.type, bound);
995
+ frame.emitter.line(
996
+ `let ${array}: ${layout.text} = defaultValue<${layout.text}>();`,
997
+ );
988
998
  // Unsigned, so its remainder is proved an index of the array; the count itself never reaches the bound.
989
999
  frame.emitter.line(`let ${count}: UDINT = 0;`);
990
1000
  traversal.run(frame, ({ value }) => {
991
1001
  frame.emitter.line(
992
- mapped`${array}[${count} % ${size}] = ${slot.store(value)};`,
1002
+ mapped`${array}[${count} % ${layout.bound}] = ${slot.store(value)};`,
993
1003
  );
994
1004
  frame.emitter.line(`${count} = ${count} + 1;`);
995
1005
  });
996
1006
  const length = frame.emitter.temporary();
997
1007
  frame.emitter.line(
998
- mapped`const ${length}: number = ${this.dialect.assignmentText({ kind: "code", text: count, iec: "UDINT" }, this.checker.getNumberType())};`,
1008
+ mapped`const ${length}: number = ${this.context.dialect.assignmentText({ kind: "code", text: count, iec: "UDINT" }, this.context.checker.getNumberType(), undefined)};`,
999
1009
  );
1000
1010
  return {
1001
1011
  kind: "counted",
1002
1012
  source: {
1003
1013
  kind: "array",
1004
1014
  text: array,
1005
- layout,
1015
+ layout: layout.text,
1006
1016
  bound,
1007
1017
  snapshot: true,
1008
1018
  filled: this.number(length),
@@ -1013,14 +1023,16 @@ export class Iterators {
1013
1023
  };
1014
1024
  }
1015
1025
 
1016
- /** What a traversal passes on, each with how often, from writing it out without keeping the code. */
1026
+ /** What a traversal passes on, each with how often, from writing it out without keeping anything it wrote. */
1017
1027
  private trial(traversal: Traversal, frame: Frame): Visited[] {
1018
1028
  const visits: Visited[] = [];
1019
- traversal.run(
1020
- { ...frame, emitter: new Emitter(frame.emitter.origin) },
1021
- (element) => {
1022
- visits.push(element);
1023
- },
1029
+ this.expressions.speculatively(() =>
1030
+ traversal.run(
1031
+ { ...frame, emitter: new Emitter(frame.emitter.origin) },
1032
+ (element) => {
1033
+ visits.push(element);
1034
+ },
1035
+ ),
1024
1036
  );
1025
1037
  return visits;
1026
1038
  }
@@ -1032,7 +1044,7 @@ export class Iterators {
1032
1044
  ): Slot {
1033
1045
  return {
1034
1046
  type: referenceLayout,
1035
- empty: () => "-1",
1047
+ empty: () => noReference,
1036
1048
  store: (value) => {
1037
1049
  const index = referenceIndex(value);
1038
1050
  if (index === undefined) {
@@ -1060,7 +1072,11 @@ export class Iterators {
1060
1072
  type: this.expressions.localType(element),
1061
1073
  empty: () => `defaultValue<${this.expressions.localType(element)}>()`,
1062
1074
  store: (value) =>
1063
- this.dialect.assignmentText(copyable(value, node), element),
1075
+ this.context.dialect.assignmentText(
1076
+ copyable(value, node),
1077
+ element,
1078
+ undefined,
1079
+ ),
1064
1080
  read: (place) => ({
1065
1081
  kind: "code",
1066
1082
  text: place,
@@ -1077,13 +1093,18 @@ export class Iterators {
1077
1093
  declared: ts.Type,
1078
1094
  node: ts.CallExpression,
1079
1095
  ): Slot {
1080
- const element = this.checker.getNonNullableType(declared);
1096
+ const element = this.context.checker.getNonNullableType(declared);
1081
1097
  return {
1082
1098
  type: this.expressions.localType(declared),
1083
- empty: () => this.dialect.assignmentText(constant(undefined), declared),
1099
+ empty: () =>
1100
+ this.context.dialect.assignmentText(
1101
+ constant(undefined),
1102
+ declared,
1103
+ undefined,
1104
+ ),
1084
1105
  store: (value) =>
1085
- this.dialect.wrapDefined(
1086
- this.dialect.code(copyable(value, node), element),
1106
+ this.context.dialect.wrapDefined(
1107
+ this.context.dialect.code(copyable(value, node), element),
1087
1108
  declared,
1088
1109
  ),
1089
1110
  read: (place) => ({
@@ -1171,7 +1192,7 @@ export class Iterators {
1171
1192
  return {
1172
1193
  kind: "code",
1173
1194
  text: mapped`(${joined(terms, some ? " || " : " && ")})`,
1174
- declared: this.checker.getBooleanType(),
1195
+ declared: this.context.checker.getBooleanType(),
1175
1196
  };
1176
1197
  }
1177
1198
 
@@ -1198,11 +1219,11 @@ export class Iterators {
1198
1219
  frame: Frame,
1199
1220
  ): (item: Value, index: Value) => Value {
1200
1221
  if (name === "includes") {
1201
- const target = this.target(node, frame);
1222
+ const target = searchTarget(node, frame, this.expressions);
1202
1223
  return (item) =>
1203
1224
  this.expressions.equality(item, target, { negate: false });
1204
1225
  }
1205
- const callback = this.callback(node, frame);
1226
+ const callback = callbackArgument(node, frame, this.expressions);
1206
1227
  return (item, index) =>
1207
1228
  this.expressions.invoke(callback, [item, index], node, frame);
1208
1229
  }
@@ -1281,7 +1302,7 @@ export class Iterators {
1281
1302
  }
1282
1303
  const local = frame.emitter.temporary();
1283
1304
  frame.emitter.line(
1284
- mapped`const ${local}: number = ${this.dialect.assignmentText(value, this.checker.getNumberType())};`,
1305
+ mapped`const ${local}: number = ${this.context.dialect.assignmentText(value, this.context.checker.getNumberType(), undefined)};`,
1285
1306
  );
1286
1307
  return this.number(local);
1287
1308
  }
@@ -1326,25 +1347,6 @@ export class Iterators {
1326
1347
  };
1327
1348
  }
1328
1349
 
1329
- private callback(node: ts.CallExpression, frame: Frame): Value {
1330
- const [argument] = node.arguments;
1331
- if (!argument) {
1332
- throw new SpecializeError(node, "Pass a callback.");
1333
- }
1334
- return this.expressions.expression(argument, frame);
1335
- }
1336
-
1337
- private target(node: ts.CallExpression, frame: Frame): Value {
1338
- const [argument] = node.arguments;
1339
- if (!argument) {
1340
- throw new SpecializeError(node, "Pass the value to look for.");
1341
- }
1342
- return this.expressions.held(
1343
- this.expressions.expression(argument, frame),
1344
- frame,
1345
- );
1346
- }
1347
-
1348
1350
  /** `take` and `drop`'s count: known now, or held in a const before the generator runs. */
1349
1351
  private amount(node: ts.CallExpression, frame: Frame): Value {
1350
1352
  const [argument] = node.arguments;
@@ -1368,29 +1370,26 @@ export class Iterators {
1368
1370
 
1369
1371
  /** A number computed at run time in a const of its own, so the bounds that use it read it rather than repeat it. */
1370
1372
  private kept(value: Value, frame: Frame): Value {
1371
- if (value.kind !== "code" || repeatable(value.text)) {
1372
- return value;
1373
- }
1374
- const local = frame.emitter.temporary();
1375
- frame.emitter.line(mapped`const ${local}: number = ${value.text};`);
1376
- return this.number(local);
1373
+ return value.kind === "code"
1374
+ ? this.expressions.temporaryOf(value, frame)
1375
+ : value;
1377
1376
  }
1378
1377
 
1379
1378
  private condition(value: Value, at: ts.CallExpression): string | Mapped {
1380
- return this.dialect.condition(value, at.arguments[0] ?? at);
1379
+ return this.context.dialect.condition(value, at.arguments[0] ?? at);
1381
1380
  }
1382
1381
 
1383
1382
  private number(text: string | Mapped): Value {
1384
1383
  return {
1385
1384
  kind: "code",
1386
1385
  text,
1387
- declared: this.checker.getNumberType(),
1386
+ declared: this.context.checker.getNumberType(),
1388
1387
  place: true,
1389
1388
  };
1390
1389
  }
1391
1390
 
1392
1391
  private text(value: Value): string | Mapped {
1393
- return this.dialect.code(value, undefined);
1392
+ return this.context.dialect.code(value, undefined);
1394
1393
  }
1395
1394
 
1396
1395
  private sum(left: Value, right: Value): Value {
@@ -1449,132 +1448,17 @@ export class Iterators {
1449
1448
  }
1450
1449
  }
1451
1450
 
1452
- /**
1453
- * How many times a counted loop's body can run: from its start, the bound its counter is compared
1454
- * with and its step, when setup fixed them all. Undefined for a header that doesn't say.
1455
- */
1456
- export const iterationCount = (
1457
- start: Value,
1458
- comparison: ts.SyntaxKind,
1459
- limit: Value,
1460
- incrementor: ts.Expression,
1461
- ): number | undefined => {
1462
- const first = known(start);
1463
- const last = known(limit);
1464
- const step = stepOf(incrementor);
1465
- if (first === undefined || last === undefined || step === undefined) {
1466
- return undefined;
1467
- }
1468
- const span = step > 0 ? last - first : first - last;
1469
- const size = Math.abs(step);
1470
- const rising = step > 0;
1471
- switch (comparison) {
1472
- case rising ? ts.SyntaxKind.LessThanToken : ts.SyntaxKind.GreaterThanToken:
1473
- return Math.max(0, Math.ceil(span / size));
1474
- case rising
1475
- ? ts.SyntaxKind.LessThanEqualsToken
1476
- : ts.SyntaxKind.GreaterThanEqualsToken:
1477
- return Math.max(0, Math.floor(span / size) + 1);
1478
- default:
1479
- return undefined;
1480
- }
1481
- };
1482
-
1483
- const iecNames = new Set(primitiveTypes.map((type) => type.id));
1484
-
1485
- /**
1486
- * What a stored array's layout says of it, as `FixedArray<BYTE, 32>` does: how many elements it
1487
- * has, and the IEC width of each when the layout names one. An array a routine was passed has
1488
- * only its layout to say so.
1489
- */
1490
- const storedArray = (
1491
- layout: string,
1492
- ): { bound: number; iec: string | undefined } | undefined => {
1493
- const [, element, size] = /^FixedArray<(.*), (\d+)>$/.exec(layout) ?? [];
1494
- if (element === undefined || size === undefined) {
1495
- return undefined;
1496
- }
1497
- return {
1498
- bound: Number(size),
1499
- iec: iecNames.has(element) ? element : undefined,
1500
- };
1501
- };
1502
-
1503
- /** What tells two counted arguments apart to the routine specialized for them. */
1504
- export const countedKey = (
1505
- counted: Counted,
1506
- valueKey: (value: Value) => string,
1507
- ): string => {
1508
- const { source } = counted;
1509
- const bounds = `${valueKey(counted.start)}..${valueKey(counted.end)}`;
1510
- return source.kind === "items"
1511
- ? `counted[${source.items.map(valueKey).join(",")}]${bounds}`
1512
- : `counted:${source.layout}:${valueKey(source.element("0"))}:${bounds}`;
1513
- };
1514
-
1515
- /** An element as a routine reads it from the array it was passed: the same slot of its own parameter. */
1516
- const reread = (
1517
- sample: Value,
1518
- array: string,
1519
- index: string | Mapped,
1520
- ): Value => {
1521
- const place = mapped`${array}[${index}]`;
1522
- if (sample.kind === "choice") {
1523
- return { ...sample, index: place };
1524
- }
1525
- return sample.kind === "code" ? { ...sample, text: place } : sample;
1526
- };
1527
-
1528
- /** A counted loop's step, as `i++`, `i--`, `i += 2` or `i -= 2` writes it. */
1529
- const stepOf = (incrementor: ts.Expression): number | undefined => {
1530
- if (
1531
- ts.isPrefixUnaryExpression(incrementor) ||
1532
- ts.isPostfixUnaryExpression(incrementor)
1533
- ) {
1534
- return incrementor.operator === ts.SyntaxKind.PlusPlusToken ? 1 : -1;
1535
- }
1536
- if (
1537
- !ts.isBinaryExpression(incrementor) ||
1538
- !ts.isNumericLiteral(incrementor.right)
1539
- ) {
1540
- return undefined;
1541
- }
1542
- const size = Number(incrementor.right.text);
1543
- switch (incrementor.operatorToken.kind) {
1544
- case ts.SyntaxKind.PlusEqualsToken:
1545
- return size > 0 ? size : undefined;
1546
- case ts.SyntaxKind.MinusEqualsToken:
1547
- return size > 0 ? -size : undefined;
1548
- default:
1549
- return undefined;
1550
- }
1551
- };
1552
-
1553
- /**
1554
- * The objects references among the values can be, and whether one can be undefined; undefined
1555
- * when none of the values is an object setup built.
1556
- */
1557
- const references = (
1558
- values: readonly Value[],
1559
- ): { options: readonly ModelNode[]; optional: boolean } | undefined => {
1560
- const options = values.flatMap((value) => {
1561
- if (value.kind === "choice") {
1562
- return value.options;
1563
- }
1564
- return value.kind === "static" ? [value.node] : [];
1565
- });
1566
- if (!options.length) {
1567
- return undefined;
1568
- }
1569
- return {
1570
- // In the order setup built them, so the code over them is the same every build.
1571
- options: [...new Set(options)].sort((left, right) => left.id - right.id),
1572
- optional: values.some(
1573
- (value) =>
1574
- value.kind === "const" || (value.kind === "choice" && value.optional),
1575
- ),
1576
- };
1577
- };
1451
+ /** How many times code written now can run, for the loops entered since `depth`. */
1452
+ const repeats = (frame: Frame, depth: number): number | undefined =>
1453
+ frame.loops
1454
+ .slice(depth)
1455
+ .reduce<number | undefined>(
1456
+ (product, runs) =>
1457
+ product === undefined || runs === undefined
1458
+ ? undefined
1459
+ : product * runs,
1460
+ 1,
1461
+ );
1578
1462
 
1579
1463
  /** A value a local can keep a copy of. */
1580
1464
  const copyable = (value: Value, at: ts.Node): Value => {
@@ -1595,17 +1479,7 @@ const copyable = (value: Value, at: ts.Node): Value => {
1595
1479
  const copiedFrom = (
1596
1480
  values: readonly Value[],
1597
1481
  method: string,
1598
- ): string | undefined =>
1599
- values.some(
1600
- (value) =>
1601
- value.kind === "code" &&
1602
- (value.copyOf !== undefined ||
1603
- (value.place === true &&
1604
- value.declared !== undefined &&
1605
- Boolean(value.declared.flags & ts.TypeFlags.Object))),
1606
- )
1607
- ? method
1608
- : undefined;
1482
+ ): string | undefined => (values.some(isStoredState) ? method : undefined);
1609
1483
 
1610
1484
  /** The smaller of two limits, either of which may be unknown. */
1611
1485
  const fewest = (
@@ -1618,11 +1492,6 @@ const fewest = (
1618
1492
  return Math.min(left, right);
1619
1493
  };
1620
1494
 
1621
- const known = (value: Value): number | undefined =>
1622
- value.kind === "const" && typeof value.value === "number"
1623
- ? value.value
1624
- : undefined;
1625
-
1626
1495
  /** Whether two numbers are the same one: equal constants, or the same local. */
1627
1496
  const sameNumber = (left: Value, right: Value): boolean => {
1628
1497
  if (left.kind === "code" && right.kind === "code") {
@@ -1632,11 +1501,17 @@ const sameNumber = (left: Value, right: Value): boolean => {
1632
1501
  return fixed !== undefined && fixed === known(right);
1633
1502
  };
1634
1503
 
1635
- /** A test's result when it is known now: a value setup fixed, or an object, which is always truthy. */
1504
+ /**
1505
+ * A test's result when it is known now: a value setup fixed, or an object, which is always truthy.
1506
+ * A reference that may hold none is decided at run time.
1507
+ */
1636
1508
  const truth = (value: Value): boolean | undefined => {
1637
1509
  if (value.kind === "const") {
1638
1510
  return Boolean(value.value);
1639
1511
  }
1512
+ if (value.kind === "choice") {
1513
+ return value.optional ? undefined : true;
1514
+ }
1640
1515
  return value.kind === "code" ? undefined : true;
1641
1516
  };
1642
1517
 
@@ -1661,17 +1536,6 @@ const takes = (callback: Value, parameter: number): boolean =>
1661
1536
  (declared.dotDotDotToken !== undefined && position < parameter),
1662
1537
  );
1663
1538
 
1664
- const unwrapped = (node: ts.Expression): ts.Expression =>
1665
- ts.isParenthesizedExpression(node) ||
1666
- ts.isNonNullExpression(node) ||
1667
- ts.isAsExpression(node) ||
1668
- ts.isSatisfiesExpression(node)
1669
- ? unwrapped(node.expression)
1670
- : node;
1671
-
1672
- /** What reads an expression, outside the parentheses around it. */
1539
+ /** What reads an expression, outside the wrappers around it. */
1673
1540
  const outside = (node: ts.Node): ts.Node =>
1674
- ts.isParenthesizedExpression(node.parent) ||
1675
- ts.isNonNullExpression(node.parent)
1676
- ? outside(node.parent)
1677
- : node.parent;
1541
+ isWrapper(node.parent) ? outside(node.parent) : node.parent;