embedded-react 0.19.0 → 0.21.0

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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -0,0 +1,582 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*
17
+ * Loops: `for` and `for…of` in handlers, effects, timers and the helpers they call. The VM only has a counted loop,
18
+ * so each loop needs a most number of visits the compiler can work out: a `for` counts from a constant or a list's
19
+ * length to another, and a `for…of` visits a list's rows, at most its cap. A test before each visit ends the loop
20
+ * where JS's would.
21
+ */
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Imports
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ import { aotError } from './diagnostics.mjs';
26
+ import { listValueOf, lowerExpr, staticInt } from './expressions.mjs';
27
+ import { statementsOf } from './helper-values.mjs';
28
+ import { BOOL, INT } from './ir/types.mjs';
29
+ import { rowItemOf } from './list-order.mjs';
30
+ /*----------------------------------------------------------------------------------------------------------------------
31
+ - Constants
32
+ ---------------------------------------------------------------------------------------------------------------------*/
33
+ /** The most visits of one loop: LOOPSET's count is 16 bits. */
34
+ const MAX_VISITS = 0xffff;
35
+ /** The range of a 32-bit whole number, which a `for` loop's counter holds. */
36
+ const INT_MIN = -(2 ** 31);
37
+ const INT_MAX = 2 ** 31 - 1;
38
+ /** The most list lengths worked through to find a loop's most visits. */
39
+ const MAX_LENGTH_CASES = 100_000;
40
+ const FLIPPED = {
41
+ '<': '>',
42
+ '<=': '>=',
43
+ '>': '<',
44
+ '>=': '<=',
45
+ };
46
+ const BOUND_HINT = "count from a constant or a list's length to another, by a constant step: for (let i = 0; i < 8; i++) or " +
47
+ 'for (let i = 0; i < items.length; i++). To go over a list, write for (const item of items).';
48
+ /*----------------------------------------------------------------------------------------------------------------------
49
+ - Variables
50
+ ---------------------------------------------------------------------------------------------------------------------*/
51
+ /** Numbers the locals each loop's visits are read through. */
52
+ let loopVisits = 0;
53
+ /*----------------------------------------------------------------------------------------------------------------------
54
+ - Implementation
55
+ ---------------------------------------------------------------------------------------------------------------------*/
56
+ /**
57
+ * An error located at a node.
58
+ *
59
+ * @param node The node.
60
+ * @param message The message.
61
+ * @param hint The hint.
62
+ *
63
+ * @returns The error.
64
+ */
65
+ function errorAt(node, message, hint) {
66
+ const error = aotError(message, hint);
67
+ if (node.loc)
68
+ error.aotLoc = node.loc.start;
69
+ return error;
70
+ }
71
+ /**
72
+ * Whether an expression reads a name.
73
+ *
74
+ * @param node The expression.
75
+ * @param name The name.
76
+ *
77
+ * @returns Whether it does.
78
+ */
79
+ function readsName(node, name) {
80
+ if (!node || typeof node !== 'object')
81
+ return false;
82
+ if (Array.isArray(node))
83
+ return node.some(child => readsName(child, name));
84
+ const astNode = node;
85
+ if (astNode.type === 'Identifier')
86
+ return astNode.name === name;
87
+ return Object.entries(astNode).some(([key, child]) => key !== 'loc' &&
88
+ !(key === 'property' &&
89
+ astNode.type === 'MemberExpression' &&
90
+ !astNode.computed) &&
91
+ readsName(child, name));
92
+ }
93
+ /**
94
+ * The local a loop's visit number is read through. Each has a name of its own, which no JS name can clash with.
95
+ *
96
+ * @returns The local.
97
+ */
98
+ const visitLocal = () => ({
99
+ slotKind: 'int',
100
+ name: `#visit${loopVisits++}`,
101
+ });
102
+ /**
103
+ * A whole number worked out from constants and the lengths of lists, which the compiler can bound.
104
+ *
105
+ * @param node The expression.
106
+ * @param environment The expression environment.
107
+ *
108
+ * @returns How to work it out for given lengths, or null when it reads anything else.
109
+ */
110
+ function boundedOf(node, environment) {
111
+ const constant = staticInt(node, environment);
112
+ if (constant !== null)
113
+ return { reads: [], at: () => constant };
114
+ // An outer loop's counter, which goes through the values it was found to take.
115
+ if (node.type === 'Identifier') {
116
+ const local = environment.locals.get(node.name);
117
+ return local?.range
118
+ ? { reads: [local], at: values => values.get(local) }
119
+ : null;
120
+ }
121
+ if (node.type === 'MemberExpression' &&
122
+ !node.computed &&
123
+ node.property.type === 'Identifier' &&
124
+ node.property.name === 'length') {
125
+ const list = listValueOf(node.object, environment);
126
+ return list ? { reads: [list], at: values => values.get(list) } : null;
127
+ }
128
+ if (node.type === 'UnaryExpression' && node.operator === '-') {
129
+ const operand = boundedOf(node.argument, environment);
130
+ return operand && { reads: operand.reads, at: values => -operand.at(values) };
131
+ }
132
+ if (node.type === 'BinaryExpression' &&
133
+ (node.operator === '+' || node.operator === '-' || node.operator === '*')) {
134
+ const left = boundedOf(node.left, environment);
135
+ const right = boundedOf(node.right, environment);
136
+ if (!left || !right)
137
+ return null;
138
+ const { operator } = node;
139
+ return {
140
+ reads: [...left.reads, ...right.reads],
141
+ at: values => {
142
+ const [first, second] = [left.at(values), right.at(values)];
143
+ return operator === '+'
144
+ ? first + second
145
+ : operator === '-'
146
+ ? first - second
147
+ : first * second;
148
+ },
149
+ };
150
+ }
151
+ // Math.min / Math.max of bounded values.
152
+ if (node.type === 'CallExpression' &&
153
+ node.callee.type === 'MemberExpression' &&
154
+ node.callee.object.type === 'Identifier' &&
155
+ node.callee.object.name === 'Math' &&
156
+ node.callee.property.type === 'Identifier' &&
157
+ (node.callee.property.name === 'min' ||
158
+ node.callee.property.name === 'max') &&
159
+ node.arguments.length > 0) {
160
+ const parts = node.arguments.map(argument => argument.type === 'SpreadElement' ||
161
+ argument.type === 'ArgumentPlaceholder'
162
+ ? null
163
+ : boundedOf(argument, environment));
164
+ if (parts.some(part => !part))
165
+ return null;
166
+ const pick = node.callee.property.name === 'min' ? Math.min : Math.max;
167
+ return {
168
+ reads: parts.flatMap(part => part.reads),
169
+ at: values => pick(...parts.map(part => part.at(values))),
170
+ };
171
+ }
172
+ return null;
173
+ }
174
+ /**
175
+ * How many times a counter goes from `start` by `step` while `start test end` holds.
176
+ *
177
+ * @returns The count, or Infinity when the counter never gets there.
178
+ */
179
+ function visitsOf(start, test, end, step) {
180
+ const holds = (value) => test === '<'
181
+ ? value < end
182
+ : test === '<='
183
+ ? value <= end
184
+ : test === '>'
185
+ ? value > end
186
+ : value >= end;
187
+ if (!holds(start))
188
+ return 0;
189
+ const goesUp = test === '<' || test === '<=';
190
+ if (goesUp !== step > 0)
191
+ return Infinity;
192
+ const distance = Math.abs(end - start);
193
+ const size = Math.abs(step);
194
+ return test === '<' || test === '>'
195
+ ? Math.ceil(distance / size)
196
+ : Math.floor(distance / size) + 1;
197
+ }
198
+ /**
199
+ * The values a bound's variable can have: a list holds from none to its cap (a constant array exactly its
200
+ * length), and an outer counter goes through the values it was found to take.
201
+ *
202
+ * @param variable The variable.
203
+ *
204
+ * @returns Its lowest and highest value.
205
+ */
206
+ const rangeOf = (variable) => 'kind' in variable
207
+ ? [variable.constant ? variable.capacity : 0, variable.capacity]
208
+ : variable.range;
209
+ /**
210
+ * The most times a loop can run, and the values its counter takes, over every value its bounds can read.
211
+ *
212
+ * @param reads What its start and end read.
213
+ * @param start Its start.
214
+ * @param test How its test compares the counter with the end.
215
+ * @param end Its end.
216
+ * @param step What each visit adds.
217
+ * @param node The loop, for errors.
218
+ *
219
+ * @returns The count, and the counter's lowest and highest value, or null when it never runs.
220
+ */
221
+ function mostVisits(reads, start, test, end, step, node) {
222
+ const distinct = [...new Set(reads)];
223
+ const ranges = distinct.map(rangeOf);
224
+ const cases = ranges.reduce((count, [low, high]) => count * (high - low + 1), 1);
225
+ if (cases > MAX_LENGTH_CASES) {
226
+ throw errorAt(node, "AOT: a for loop's bound reads too many values to count its visits", BOUND_HINT);
227
+ }
228
+ let most = 0;
229
+ let range = null;
230
+ const values = new Map();
231
+ const visit = (at) => {
232
+ if (at === distinct.length) {
233
+ const first = start.at(values);
234
+ const visits = visitsOf(first, test, end.at(values), step);
235
+ most = Math.max(most, visits);
236
+ if (visits > 0 && visits !== Infinity) {
237
+ const last = first + (visits - 1) * step;
238
+ const [low, high] = range ?? [first, first];
239
+ range = [Math.min(low, first, last), Math.max(high, first, last)];
240
+ }
241
+ return;
242
+ }
243
+ const [low, high] = ranges[at];
244
+ for (let value = low; value <= high; value++) {
245
+ values.set(distinct[at], value);
246
+ visit(at + 1);
247
+ }
248
+ };
249
+ visit(0);
250
+ return { visits: most, range };
251
+ }
252
+ /**
253
+ * A `for` loop's step: `i++`, `i--`, `i += k`, `i -= k`, `i = i + k` or `i = i - k`, with k a constant.
254
+ *
255
+ * @param update The loop's update.
256
+ * @param name The counter's name.
257
+ * @param environment The expression environment.
258
+ *
259
+ * @returns How much each visit adds, or null when it is no such step.
260
+ */
261
+ function stepOf(update, name, environment) {
262
+ if (!update)
263
+ return null;
264
+ const isCounter = (node) => node.type === 'Identifier' && node.name === name;
265
+ if (update.type === 'UpdateExpression' && isCounter(update.argument)) {
266
+ return update.operator === '++' ? 1 : -1;
267
+ }
268
+ if (update.type !== 'AssignmentExpression' || !isCounter(update.left)) {
269
+ return null;
270
+ }
271
+ const sign = (operator) => operator === '+' ? 1 : operator === '-' ? -1 : null;
272
+ if (update.operator === '+=' || update.operator === '-=') {
273
+ const amount = staticInt(update.right, environment);
274
+ return amount === null ? null : sign(update.operator[0]) * amount;
275
+ }
276
+ if (update.operator === '=' &&
277
+ update.right.type === 'BinaryExpression' &&
278
+ isCounter(update.right.left) &&
279
+ sign(update.right.operator) !== null) {
280
+ const amount = staticInt(update.right.right, environment);
281
+ return amount === null ? null : sign(update.right.operator) * amount;
282
+ }
283
+ return null;
284
+ }
285
+ /**
286
+ * Lowers a loop's body with the lists it visits or is bounded by on the context's stack, which a setter of one
287
+ * of them inside it is checked against.
288
+ *
289
+ * @param body The body.
290
+ * @param lists The lists.
291
+ * @param environment The body's environment.
292
+ * @param state The component's state table.
293
+ * @param context The statement compiler's context.
294
+ * @param lowerStatements lowerStmts.
295
+ *
296
+ * @returns The lowered body.
297
+ */
298
+ function lowerLoopBody(body, lists, environment, state, context, lowerStatements) {
299
+ const loops = (context.loops ??= []);
300
+ // A filtered or sorted list holds rows of its source, so setting the source changes it too.
301
+ loops.push(lists.flatMap(list => list.derived?.source ? [list, list.derived.source] : [list]));
302
+ try {
303
+ return lowerStatements(body, environment, state, context);
304
+ }
305
+ finally {
306
+ loops.pop();
307
+ }
308
+ }
309
+ /**
310
+ * Lowers `for (let i = start; i < end; i++) …`: the counter is a local the body reads but can't set. Start and end
311
+ * are constants or lists' lengths, so the compiler can work out how many times it runs at most; one that reads a
312
+ * length is tested before each visit, as JS tests it.
313
+ *
314
+ * @param statement The loop.
315
+ * @param environment The expression environment.
316
+ * @param state The component's state table.
317
+ * @param context The statement compiler's context.
318
+ * @param lowerStatements lowerStmts.
319
+ *
320
+ * @returns The statements.
321
+ */
322
+ export function lowerFor(statement, environment, state, context, lowerStatements) {
323
+ const { init, test, update } = statement;
324
+ const declarator = init?.type === 'VariableDeclaration' &&
325
+ init.kind === 'let' &&
326
+ init.declarations.length === 1
327
+ ? init.declarations[0]
328
+ : null;
329
+ if (!declarator || declarator.id.type !== 'Identifier' || !declarator.init) {
330
+ throw errorAt(statement, 'AOT: a for loop must declare its counter with let', BOUND_HINT);
331
+ }
332
+ const name = declarator.id.name;
333
+ // `i < end`, or `end > i`.
334
+ if (test?.type !== 'BinaryExpression' ||
335
+ !(test.operator in FLIPPED) ||
336
+ test.left.type === 'PrivateName') {
337
+ throw errorAt(test ?? statement, `AOT: a for loop's test must compare ${name} with its end: ${name} < end`, BOUND_HINT);
338
+ }
339
+ const isCounter = (node) => node.type === 'Identifier' && node.name === name;
340
+ const counterOnLeft = isCounter(test.left);
341
+ if (!counterOnLeft && !isCounter(test.right)) {
342
+ throw errorAt(test, `AOT: a for loop's test must compare ${name} with its end: ${name} < end`, BOUND_HINT);
343
+ }
344
+ const operator = counterOnLeft
345
+ ? test.operator
346
+ : FLIPPED[test.operator];
347
+ const endNode = (counterOnLeft ? test.right : test.left);
348
+ const step = stepOf(update, name, environment);
349
+ if (!step) {
350
+ throw errorAt(update ?? statement, `AOT: a for loop must step ${name} by a constant: ${name}++, ${name}-- or ${name} += 2`, BOUND_HINT);
351
+ }
352
+ // In JS both read the loop's own counter, not an outer one of the same name.
353
+ for (const bound of [declarator.init, endNode]) {
354
+ if (readsName(bound, name)) {
355
+ throw errorAt(bound, `AOT: a for loop's start and end can't read its counter ${name}`, BOUND_HINT);
356
+ }
357
+ }
358
+ const start = boundedOf(declarator.init, environment);
359
+ const end = boundedOf(endNode, environment);
360
+ if (!start || !end) {
361
+ throw errorAt(start ? endNode : declarator.init, "AOT: a for loop's start and end must be constants or lists' lengths", BOUND_HINT);
362
+ }
363
+ const reads = [...start.reads, ...end.reads];
364
+ const { visits: bound, range } = mostVisits(reads, start, operator, end, step, statement);
365
+ if (bound === Infinity) {
366
+ throw errorAt(statement, `AOT: this for loop never ends: ${name} moves away from its end`, BOUND_HINT);
367
+ }
368
+ if (bound > MAX_VISITS) {
369
+ throw errorAt(statement, `AOT: a for loop runs at most ${MAX_VISITS} times, and this one can run ${bound}`, 'split the work into smaller loops, or over several events.');
370
+ }
371
+ // The counter is an int, and so is the value the last step leaves it at.
372
+ if (range &&
373
+ (Math.min(range[0], range[0] + step) < INT_MIN ||
374
+ Math.max(range[1], range[1] + step) > INT_MAX)) {
375
+ throw errorAt(statement, `AOT: a for loop's counter must stay a 32-bit whole number, and ${name} can reach past one`, BOUND_HINT);
376
+ }
377
+ // The counter is a local of its own, which the body reads and only the step sets.
378
+ const counter = {
379
+ slotKind: 'int',
380
+ name: `local_${name}@${statement.start ?? 0}`,
381
+ counter: true,
382
+ ...(range ? { range } : {}),
383
+ };
384
+ const startValue = lowerExpr(declarator.init, environment);
385
+ const bodyEnvironment = {
386
+ ...environment,
387
+ locals: new Map(environment.locals).set(name, counter),
388
+ };
389
+ const counterRead = { kind: 'local', local: counter, type: INT };
390
+ const lists = reads.filter((read) => 'kind' in read);
391
+ const body = lowerLoopBody(statementsOf(statement.body), lists, bodyEnvironment, state, context, lowerStatements);
392
+ return [
393
+ {
394
+ kind: 'declareLocal',
395
+ name: counter.name,
396
+ initializer: startValue,
397
+ isHoisted: false,
398
+ },
399
+ {
400
+ kind: 'loop',
401
+ bound,
402
+ visit: null,
403
+ // A loop whose bounds read only constants runs exactly its bound.
404
+ test: reads.length
405
+ ? {
406
+ kind: 'compare',
407
+ operator,
408
+ left: counterRead,
409
+ right: lowerExpr(endNode, environment),
410
+ type: BOOL,
411
+ }
412
+ : null,
413
+ body,
414
+ step: [
415
+ {
416
+ kind: 'assignLocal',
417
+ name: counter.name,
418
+ value: {
419
+ kind: 'helper',
420
+ helper: 'add',
421
+ bits: 32,
422
+ callArguments: [
423
+ counterRead,
424
+ { kind: 'number', value: step, type: INT },
425
+ ],
426
+ type: INT,
427
+ },
428
+ },
429
+ ],
430
+ },
431
+ ];
432
+ }
433
+ /**
434
+ * The names a `for…of` binds for each row: `item`, `{a, b}`, or `[i, item]` over `list.entries()`.
435
+ *
436
+ * @param statement The loop.
437
+ *
438
+ * @returns The list's expression, the item's pattern, and the index's name for entries().
439
+ */
440
+ function forOfParts(statement) {
441
+ const { left, right } = statement;
442
+ if (left.type !== 'VariableDeclaration' ||
443
+ (left.kind !== 'const' && left.kind !== 'let') ||
444
+ left.declarations.length !== 1 ||
445
+ left.declarations[0].init) {
446
+ throw errorAt(statement, 'AOT: a for…of must declare its item with const or let: for (const item of items)');
447
+ }
448
+ const { kind } = left;
449
+ const pattern = left.declarations[0].id;
450
+ // `for (const [i, item] of items.entries())`.
451
+ const isEntries = right.type === 'CallExpression' &&
452
+ right.callee.type === 'MemberExpression' &&
453
+ !right.callee.computed &&
454
+ right.callee.property.type === 'Identifier' &&
455
+ right.callee.property.name === 'entries' &&
456
+ right.arguments.length === 0;
457
+ if (isEntries) {
458
+ const [index, item] = pattern.type === 'ArrayPattern' ? pattern.elements : [];
459
+ if (pattern.type !== 'ArrayPattern' ||
460
+ pattern.elements.length !== 2 ||
461
+ index?.type !== 'Identifier' ||
462
+ !item ||
463
+ item.type === 'RestElement') {
464
+ throw errorAt(pattern, 'AOT: a for…of over entries() must name the index and the item: for (const [i, item] of items.entries())');
465
+ }
466
+ return {
467
+ iterable: right.callee.object,
468
+ item: item,
469
+ indexName: index.name,
470
+ kind,
471
+ };
472
+ }
473
+ return { iterable: right, item: pattern, indexName: null, kind };
474
+ }
475
+ /**
476
+ * Binds a for…of's item pattern: a name for the row, or `{a, b: c}`, each field a local the body starts with,
477
+ * declared as the loop declares its item.
478
+ *
479
+ * @param pattern The pattern.
480
+ * @param item The row's item.
481
+ * @param locals The body's locals, which the item's name is added to.
482
+ * @param kind How the loop declares its item.
483
+ *
484
+ * @returns The declarations the body starts with.
485
+ */
486
+ function bindItem(pattern, item, locals, kind) {
487
+ if (pattern.type === 'Identifier') {
488
+ locals.set(pattern.name, { ...item, name: pattern.name });
489
+ return [];
490
+ }
491
+ if (pattern.type !== 'ObjectPattern') {
492
+ throw errorAt(pattern, 'AOT: a for…of item must be a name or {field, …}', 'name the item, then read its fields: for (const item of items) … item.title.');
493
+ }
494
+ // The row is bound under a name no JS name can clash with, and each field read from it.
495
+ const hidden = {
496
+ type: 'Identifier',
497
+ name: `item@${pattern.start ?? 0}`,
498
+ };
499
+ locals.set(hidden.name, { ...item, name: hidden.name });
500
+ const declarators = pattern.properties.map((property) => {
501
+ if (property.type !== 'ObjectProperty' ||
502
+ property.computed ||
503
+ property.key.type !== 'Identifier' ||
504
+ property.value.type !== 'Identifier') {
505
+ throw errorAt(property, 'AOT: a for…of item can only take plain fields apart: {title, done}', 'read a nested or defaulted field in the body: const x = item.pos.x.');
506
+ }
507
+ return {
508
+ type: 'VariableDeclarator',
509
+ id: property.value,
510
+ // Its own position names its local apart from any other.
511
+ start: property.start,
512
+ init: {
513
+ type: 'MemberExpression',
514
+ object: hidden,
515
+ property: property.key,
516
+ computed: false,
517
+ loc: property.loc,
518
+ },
519
+ loc: property.loc,
520
+ };
521
+ });
522
+ return declarators.length
523
+ ? [
524
+ {
525
+ type: 'VariableDeclaration',
526
+ kind,
527
+ declarations: declarators,
528
+ loc: pattern.loc,
529
+ },
530
+ ]
531
+ : [];
532
+ }
533
+ /**
534
+ * Lowers `for (const item of list) …`: the body runs for each row of a list state, a constant array, a list worked
535
+ * out in render or a handler's split, at most the list's cap times, and stops at its count.
536
+ *
537
+ * @param statement The loop.
538
+ * @param environment The expression environment.
539
+ * @param state The component's state table.
540
+ * @param context The statement compiler's context.
541
+ * @param lowerStatements lowerStmts.
542
+ *
543
+ * @returns The statements.
544
+ */
545
+ export function lowerForOf(statement, environment, state, context, lowerStatements) {
546
+ if (statement.await) {
547
+ throw errorAt(statement, 'AOT: for await is not supported');
548
+ }
549
+ const { iterable, item: pattern, indexName, kind } = forOfParts(statement);
550
+ const list = listValueOf(iterable, environment);
551
+ if (!list) {
552
+ throw errorAt(iterable, 'AOT: a for…of must go over a list', 'loop over a list state, a constant array, a filtered or sorted list, or a split: for (const item of items).');
553
+ }
554
+ const visit = visitLocal();
555
+ const row = { kind: 'local', local: visit, type: INT };
556
+ const item = rowItemOf(list, { name: 'item', index: row });
557
+ const locals = new Map(environment.locals);
558
+ const declarations = bindItem(pattern, item, locals, kind);
559
+ if (indexName) {
560
+ locals.set(indexName, { ...visit, counter: true });
561
+ }
562
+ const body = lowerLoopBody([...declarations, ...statementsOf(statement.body)], [list], { ...environment, locals }, state, context, lowerStatements);
563
+ return [
564
+ {
565
+ kind: 'loop',
566
+ bound: list.capacity,
567
+ visit,
568
+ // A constant array is always full.
569
+ test: list.constant
570
+ ? null
571
+ : {
572
+ kind: 'compare',
573
+ operator: '<',
574
+ left: row,
575
+ right: { kind: 'listLength', list, type: INT },
576
+ type: BOOL,
577
+ },
578
+ body,
579
+ step: [],
580
+ },
581
+ ];
582
+ }