embedded-react 0.20.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 (74) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +1 -0
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +16 -46
  5. package/aot/compiler/animations.mjs +299 -57
  6. package/aot/compiler/boot.mjs +27 -2
  7. package/aot/compiler/check.mjs +61 -9
  8. package/aot/compiler/collect.mjs +516 -136
  9. package/aot/compiler/contexts.mjs +391 -0
  10. package/aot/compiler/control-flow.mjs +276 -117
  11. package/aot/compiler/custom-hooks.mjs +686 -0
  12. package/aot/compiler/elements/button.mjs +182 -0
  13. package/aot/compiler/elements/image-background.mjs +76 -0
  14. package/aot/compiler/elements/image.mjs +2 -1
  15. package/aot/compiler/elements/props.mjs +38 -3
  16. package/aot/compiler/elements/rewrite.mjs +118 -0
  17. package/aot/compiler/elements/section-list.mjs +370 -0
  18. package/aot/compiler/expressions.mjs +1351 -97
  19. package/aot/compiler/handlers.mjs +1761 -365
  20. package/aot/compiler/helper-values.mjs +312 -0
  21. package/aot/compiler/ir/nodes.mjs +40 -1
  22. package/aot/compiler/ir/reads.mjs +206 -5
  23. package/aot/compiler/ir/text.mjs +5 -1
  24. package/aot/compiler/ir/types.mjs +12 -0
  25. package/aot/compiler/kept-states.mjs +177 -0
  26. package/aot/compiler/list-items.mjs +226 -0
  27. package/aot/compiler/list-order.mjs +586 -0
  28. package/aot/compiler/list-split.mjs +259 -0
  29. package/aot/compiler/loops.mjs +582 -0
  30. package/aot/compiler/lower.mjs +191 -53
  31. package/aot/compiler/native-files.mjs +439 -0
  32. package/aot/compiler/native-header.mjs +335 -0
  33. package/aot/compiler/native-modules.mjs +1173 -0
  34. package/aot/compiler/nodes.mjs +28 -22
  35. package/aot/compiler/options.mjs +3 -2
  36. package/aot/compiler/out.mjs +14 -1
  37. package/aot/compiler/package/animations.mjs +133 -23
  38. package/aot/compiler/package/assemble.mjs +2 -4
  39. package/aot/compiler/package/bytecode.mjs +37 -8
  40. package/aot/compiler/package/checks.mjs +4 -0
  41. package/aot/compiler/package/codegen.mjs +870 -31
  42. package/aot/compiler/package/enums.mjs +10 -0
  43. package/aot/compiler/package/format.mjs +12 -1
  44. package/aot/compiler/package/lower.mjs +658 -161
  45. package/aot/compiler/package/string-caps.mjs +515 -0
  46. package/aot/compiler/package/tables.mjs +24 -0
  47. package/aot/compiler/package/writer.mjs +22 -0
  48. package/aot/compiler/parse.mjs +3 -1
  49. package/aot/compiler/record-shapes.mjs +246 -0
  50. package/aot/compiler/records.mjs +654 -0
  51. package/aot/compiler/reducers.mjs +272 -0
  52. package/aot/compiler/static-eval.mjs +315 -7
  53. package/aot/compiler/style-text.mjs +18 -3
  54. package/aot/compiler/svg.mjs +7 -4
  55. package/aot/compiler/switch-cases.mjs +198 -0
  56. package/aot/compiler/tagged-records.mjs +450 -0
  57. package/aot/compiler/typing.mjs +307 -0
  58. package/aot/compiler/updaters.mjs +320 -0
  59. package/aot/compiler/window-dimensions.mjs +94 -0
  60. package/aot/compiler/worked-values.mjs +319 -0
  61. package/aot/demo-file.mjs +30 -0
  62. package/aot/style-map.mjs +50 -2
  63. package/build.mjs +9 -1
  64. package/cli.mjs +44 -1
  65. package/hotreload/pack-split.mjs +29 -40
  66. package/pack-container.mjs +9 -1
  67. package/package.json +1 -1
  68. package/sim/embedded-react.wasm +0 -0
  69. package/sim-server.mjs +22 -22
  70. package/src/embedded-react/Dimensions.js +37 -0
  71. package/src/embedded-react/SectionList.js +1 -3
  72. package/src/embedded-react/index.d.ts +83 -3
  73. package/src/embedded-react/index.js +2 -0
  74. package/src/embedded-react/nativeModule.js +462 -0
@@ -17,19 +17,56 @@
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
19
  import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.js';
20
- import { aotError, constantText, withLoc } from './diagnostics.mjs';
21
- import { evalStatic } from './static-eval.mjs';
22
- import { mix64Error, staticInt, isTime64, constDivisor, lowerSourcedWide, lowerSource, slotValueOf, lowerExpr, lowerExprWide, lowerText, } from './expressions.mjs';
20
+ import { aotError, constantText, ENGINE_STRING_MAX, withLoc, } from './diagnostics.mjs';
21
+ import { evalStatic, foldScope, RuntimeLeaf } from './static-eval.mjs';
22
+ import { fieldsUnder } from './list-items.mjs';
23
+ import { lowerNativeCall, nativeCalleeOf, nativeEventOf, nativeRecordCallOf, recordTreeOf, valueCount, } from './native-modules.mjs';
24
+ import { itemCallback, listChainOf, orderStatements } from './list-order.mjs';
25
+ import { handlerSplitList, lowerSplitInto } from './list-split.mjs';
26
+ import { boundObjectOf, expandObjectDeclarator, lowerRecordSet, objectTreeOf, } from './records.mjs';
27
+ import { narrowOn, narrowed } from './tagged-records.mjs';
28
+ import { exits, helperEnvironment, statementsOf } from './helper-values.mjs';
29
+ import { lowerFor, lowerForOf } from './loops.mjs';
30
+ import { switchAsIf } from './switch-cases.mjs';
31
+ import { isReturnSet, updaterStatements } from './updaters.mjs';
32
+ import { actionChoice, actionEnvironment, prunedStatements, } from './reducers.mjs';
33
+ import { whenTyped } from './check.mjs';
34
+ import { copyLocal, holdLater, localShape, setLater, shapeOf, typedLater, } from './typing.mjs';
35
+ import { bareLocalOf, binarySource, stateRead, is64BitLocal, is64BitSlot, mix64Error, staticInt, isTime64, constDivisor, lowerSource, typeSource, slotValueOf, lowerExpr, lowerExprWide, lowerText, lowerLogText, buildsText, } from './expressions.mjs';
23
36
  import { isFn } from './collect.mjs';
37
+ import { keepingStates, readingLatest } from './kept-states.mjs';
24
38
  import { isAnimatedCall, resolveAnim, animValues, lowerAnimateStart, stopWaitOwner, } from './animations.mjs';
25
39
  import { svgNum, CAP_MAP, JOIN_MAP, arcTape, circleTape, rectTape, lineTape, checkedTapeNumber, checkVectorPaints, vectorPaintOf, DEFAULT_MITER_LIMIT, } from './svg.mjs';
26
40
  import { armedFlag } from './ir/functions.mjs';
27
- import { FLOAT, INT, isConvertible64, isIntSlot, isTime, refType, slotOf, stateType, } from './ir/types.mjs';
41
+ import { INT, isConvertible64, isIntSlot, isTime, refType, STRING, } from './ir/types.mjs';
28
42
  /*----------------------------------------------------------------------------------------------------------------------
29
43
  - Constants
30
44
  ---------------------------------------------------------------------------------------------------------------------*/
45
+ /** The slot a native event's value of each type is read as: an Int64 converts like any number. */
46
+ const VALUE_SLOTS = {
47
+ int: { slotKind: 'int' },
48
+ float: { slotKind: 'float' },
49
+ bool: { slotKind: 'int', isBoolean: true },
50
+ int64: { slotKind: 'i64', isLiteral: true },
51
+ string: { slotKind: 'string' },
52
+ };
31
53
  /** The constant 0, which a remainder by 0 or ±1 stores. */
32
54
  const ZERO = { kind: 'number', value: 0, type: INT };
55
+ /** Keys an AST node keeps besides what it says: where it is, and its comments. */
56
+ const POSITION_KEYS = new Set([
57
+ 'loc',
58
+ 'start',
59
+ 'end',
60
+ 'range',
61
+ 'extra',
62
+ 'leadingComments',
63
+ 'trailingComments',
64
+ 'innerComments',
65
+ ]);
66
+ /** Update locals made so far, which numbers the next one's name. */
67
+ let updateRows = 0;
68
+ /** Counts the native calls whose record is kept, to name its locals as no JS binding can be named. */
69
+ let keptRecords = 0;
33
70
  /** Each updateVector shape key and the numbers its array takes, for errors. */
34
71
  const UPDATE_VECTOR_ARGUMENTS = {
35
72
  arc: '[cx, cy, r, startAngle, endAngle]',
@@ -40,82 +77,670 @@ const UPDATE_VECTOR_ARGUMENTS = {
40
77
  /*----------------------------------------------------------------------------------------------------------------------
41
78
  - Implementation
42
79
  ---------------------------------------------------------------------------------------------------------------------*/
80
+ /**
81
+ * Whether a value is left out of an item: null or undefined.
82
+ *
83
+ * @param node The value.
84
+ *
85
+ * @returns Whether it is.
86
+ */
87
+ const leavesOut = (node) => node.type === 'NullLiteral' ||
88
+ (node.type === 'Identifier' && node.name === 'undefined');
89
+ /**
90
+ * Whether two expressions are written the same, wherever they are.
91
+ *
92
+ * @param first One.
93
+ * @param second The other.
94
+ *
95
+ * @returns Whether they are.
96
+ */
97
+ function sameNode(first, second) {
98
+ if (first === second)
99
+ return true;
100
+ if (!first ||
101
+ !second ||
102
+ typeof first !== 'object' ||
103
+ typeof second !== 'object' ||
104
+ Array.isArray(first) !== Array.isArray(second)) {
105
+ return false;
106
+ }
107
+ const keysOf = (value) => Object.keys(value).filter(key => !POSITION_KEYS.has(key));
108
+ const firstKeys = keysOf(first);
109
+ return (firstKeys.length === keysOf(second).length &&
110
+ firstKeys.every(key => sameNode(first[key], second[key])));
111
+ }
112
+ /**
113
+ * Whether an expression reads any of some names.
114
+ *
115
+ * @param node The expression.
116
+ * @param names The names.
117
+ *
118
+ * @returns Whether it does.
119
+ */
120
+ function mentions(node, names) {
121
+ if (!node || typeof node !== 'object')
122
+ return false;
123
+ if (Array.isArray(node))
124
+ return node.some(child => mentions(child, names));
125
+ const astNode = node;
126
+ if (astNode.type === 'Identifier')
127
+ return names.has(astNode.name);
128
+ return Object.entries(astNode).some(([key, child]) => !POSITION_KEYS.has(key) &&
129
+ !(key === 'property' &&
130
+ (astNode.type === 'MemberExpression' ||
131
+ astNode.type === 'OptionalMemberExpression') &&
132
+ !astNode.computed) &&
133
+ !(key === 'key' &&
134
+ astNode.type === 'ObjectProperty' &&
135
+ !astNode.computed) &&
136
+ mentions(child, names));
137
+ }
138
+ /**
139
+ * The value an item's field is set to, checked against the field.
140
+ *
141
+ * @param field The field.
142
+ * @param valueNode Its value.
143
+ * @param listState The list.
144
+ * @param environment The expression environment.
145
+ *
146
+ * @returns The value.
147
+ */
148
+ function itemValue(field, valueNode, listState, environment) {
149
+ if (field.kind === 'string') {
150
+ const text = lowerText(valueNode, environment);
151
+ checkConstantFits(text, `field "${field.key}" of list state "${listState.name}"`);
152
+ return { field, text };
153
+ }
154
+ const value = lowerExpr(valueNode, environment);
155
+ if ((field.kind === 'bool') !== (shapeOf(value) === 'bool')) {
156
+ throw aotError(`AOT: field "${field.key || 'value'}" of list state "${listState.name}" holds ${field.kind === 'bool' ? 'a boolean' : 'a number'}`, 'give it a value of the same kind as the initial ones.');
157
+ }
158
+ return {
159
+ field,
160
+ value: field.kind === 'bool'
161
+ ? value
162
+ : storeValue(value, () => field.kind),
163
+ };
164
+ }
165
+ /**
166
+ * The fields an appended item sets, by key: an object literal's, nested ones flattened into dotted keys, or a plain
167
+ * value's one field. A field set to null or undefined is left out.
168
+ *
169
+ * @param item The appended item.
170
+ * @param struct The list's fields.
171
+ * @param listName The list, for errors.
172
+ *
173
+ * @returns Each field's value.
174
+ */
175
+ function appendedFields(item, struct, listName) {
176
+ const given = new Map();
177
+ if (struct.plain) {
178
+ if (item.type === 'ObjectExpression') {
179
+ throw aotError(`AOT: list state "${listName}" holds plain values, not objects`, 'append a value of the same kind as the initial ones.');
180
+ }
181
+ if (!leavesOut(item)) {
182
+ given.set('', item);
183
+ }
184
+ return given;
185
+ }
186
+ const visit = (object, path) => {
187
+ for (const property of object.properties) {
188
+ if (property.type !== 'ObjectProperty' || property.computed) {
189
+ throw aotError('AOT: an appended item must be an object literal of plain fields', 'write each field out: {title: t, n: 1}. Spreads, methods and computed keys are not lowered.');
190
+ }
191
+ const fieldPath = [...path, propertyKey(property)];
192
+ if (property.value.type === 'ObjectExpression') {
193
+ visit(property.value, fieldPath);
194
+ continue;
195
+ }
196
+ // A field set to null or undefined, or an object of fields set to one, is left out.
197
+ const name = fieldPath.join('.');
198
+ const isField = struct.fields.some(field => field.key === name);
199
+ if (!isField &&
200
+ !(leavesOut(property.value) && fieldsUnder(struct, fieldPath).length)) {
201
+ throw noField(listName, name);
202
+ }
203
+ if (!leavesOut(property.value)) {
204
+ given.set(name, property.value);
205
+ }
206
+ }
207
+ };
208
+ if (item.type !== 'ObjectExpression') {
209
+ throw new Error('AOT: appended list items must be object literals');
210
+ }
211
+ visit(item, []);
212
+ return given;
213
+ }
214
+ /**
215
+ * An object property's key.
216
+ *
217
+ * @param property The property.
218
+ *
219
+ * @returns The key.
220
+ */
221
+ const propertyKey = (property) => property.key.name ??
222
+ String(property.key.value);
223
+ /**
224
+ * The error for a field a list's items don't have.
225
+ *
226
+ * @param listName The list.
227
+ * @param name The field.
228
+ *
229
+ * @returns The error.
230
+ */
231
+ const noField = (listName, name) => aotError(`AOT: list state "${listName}" has no field "${name}"`, "a list's fields are those of its initial items. Give one of them the field, and leave it out of the " +
232
+ 'others to make it optional.');
233
+ /**
234
+ * A list row index: a whole number.
235
+ *
236
+ * @param node The index.
237
+ * @param listName The list, for errors.
238
+ * @param environment The expression environment.
239
+ *
240
+ * @returns The index.
241
+ */
242
+ function rowIndexOf(node, listName, environment) {
243
+ const index = lowerExpr(node, environment);
244
+ whenTyped(() => {
245
+ if (index.type.kind !== 'int') {
246
+ throw aotError(`AOT: an index into "${listName}" must be a whole number`, 'an index is an int: Math.floor(x) or a whole-number state.');
247
+ }
248
+ });
249
+ return index;
250
+ }
251
+ /**
252
+ * The index `items.filter((_, i) => i !== n)` removes: n.
253
+ *
254
+ * @param callback The filter's function.
255
+ *
256
+ * @returns n, or null when the filter is no such test.
257
+ */
258
+ function filteredIndex(callback) {
259
+ const { itemName, indexName, body } = callback;
260
+ const isIndex = (node) => node.type === 'Identifier' && node.name === indexName;
261
+ const other = indexName &&
262
+ body.type === 'BinaryExpression' &&
263
+ (body.operator === '!==' || body.operator === '!=')
264
+ ? isIndex(body.left)
265
+ ? body.right
266
+ : isIndex(body.right)
267
+ ? body.left
268
+ : null
269
+ : null;
270
+ const names = new Set([itemName, indexName].filter(Boolean));
271
+ return other && !mentions(other, names) ? other : null;
272
+ }
273
+ /**
274
+ * Whether an expression is the object at a path in an item: `base.pos.x` for ['pos', 'x'].
275
+ *
276
+ * @param node The expression.
277
+ * @param path The path.
278
+ * @param isItem Whether an expression is the item.
279
+ *
280
+ * @returns Whether it is.
281
+ */
282
+ function isPathOf(node, path, isItem) {
283
+ let current = node;
284
+ for (let index = path.length - 1; index >= 0; index--) {
285
+ if (current.type !== 'MemberExpression' ||
286
+ current.computed ||
287
+ current.property.name !== path[index]) {
288
+ return false;
289
+ }
290
+ current = current.object;
291
+ }
292
+ return isItem(current);
293
+ }
294
+ /**
295
+ * The statements an update runs on a row: `if`s for a ternary's tests, and a `setRow` for each item it builds.
296
+ * A branch that gives back the item itself changes nothing.
297
+ *
298
+ * @param node What the update gives the row.
299
+ * @param update The update.
300
+ *
301
+ * @returns The statements.
302
+ */
303
+ function updateBody(node, update) {
304
+ if (update.isRow(node, [])) {
305
+ return [];
306
+ }
307
+ if (node.type === 'ConditionalExpression') {
308
+ const consequent = updateBody(node.consequent, update);
309
+ const alternate = updateBody(node.alternate, update);
310
+ if (!consequent.length && !alternate.length) {
311
+ return [];
312
+ }
313
+ return [
314
+ {
315
+ kind: 'if',
316
+ test: lowerExprWide(node.test, update.environment),
317
+ consequent,
318
+ alternate: alternate.length ? alternate : null,
319
+ },
320
+ ];
321
+ }
322
+ return [setRow(node, update)];
323
+ }
324
+ /**
325
+ * Sets a row to an item: a spread of the row's own item keeps the fields it doesn't set; without one, every field
326
+ * it leaves out is undefined from then on.
327
+ *
328
+ * @param node The item.
329
+ * @param update The update.
330
+ *
331
+ * @returns The statement.
332
+ */
333
+ function setRow(node, update) {
334
+ const { list, listName, environment } = update;
335
+ const { struct } = list;
336
+ const given = new Map();
337
+ const cleared = new Set();
338
+ // A key written twice takes its last value, as in JS.
339
+ const give = (field, value) => {
340
+ cleared.delete(field);
341
+ given.set(field, value);
342
+ };
343
+ const clear = (field) => {
344
+ given.delete(field);
345
+ cleared.add(field);
346
+ };
347
+ if (struct.plain) {
348
+ if (node.type === 'ObjectExpression') {
349
+ throw aotError(`AOT: list state "${listName}" holds plain values, not objects`, 'give a value of the same kind as the initial ones.');
350
+ }
351
+ if (leavesOut(node)) {
352
+ clear(struct.fields[0]);
353
+ }
354
+ else {
355
+ give(struct.fields[0], node);
356
+ }
357
+ }
358
+ else {
359
+ if (node.type !== 'ObjectExpression') {
360
+ throw aotError(`AOT: an item of "${listName}" must be replaced with an object literal`, 'spread the item and set the fields that change: {...item, done: true}.');
361
+ }
362
+ const visit = (object, path) => {
363
+ const seen = new Set();
364
+ let keeps = false;
365
+ object.properties.forEach((property, position) => {
366
+ if (property.type === 'SpreadElement') {
367
+ if (position !== 0 || !update.isRow(property.argument, path)) {
368
+ throw aotError('AOT: an updated item can spread only the item it replaces, first', path.length
369
+ ? `spread the same object: {...item, ${path[0]}: {...item.${path.join('.')}, x: 1}}.`
370
+ : 'spread the item, then set the fields that change: {...item, done: true}.');
371
+ }
372
+ keeps = true;
373
+ return;
374
+ }
375
+ if (property.type !== 'ObjectProperty' || property.computed) {
376
+ throw aotError('AOT: an updated item must be an object literal of plain fields', 'write each field out: {...item, title: t, n: 1}. Methods and computed keys are not lowered.');
377
+ }
378
+ const fieldPath = [...path, propertyKey(property)];
379
+ const fields = fieldsUnder(struct, fieldPath);
380
+ if (!fields.length) {
381
+ throw noField(listName, fieldPath.join('.'));
382
+ }
383
+ // A key written again replaces all an earlier value set under it.
384
+ fields.forEach(field => {
385
+ seen.add(field);
386
+ given.delete(field);
387
+ cleared.delete(field);
388
+ });
389
+ const { value } = property;
390
+ if (value.type === 'ObjectExpression') {
391
+ visit(value, fieldPath);
392
+ }
393
+ else if (leavesOut(value)) {
394
+ fields.forEach(field => clear(field));
395
+ }
396
+ else if (fields.length === 1 &&
397
+ fields[0].key === fieldPath.join('.')) {
398
+ give(fields[0], value);
399
+ }
400
+ else if (!update.isRow(value, fieldPath)) {
401
+ throw aotError(`AOT: field "${fieldPath.join('.')}" of list state "${listName}" holds an object`, `set its fields with an object literal: {...item, ${fieldPath[0]}: {...item.${fieldPath.join('.')}, x: 1}}.`);
402
+ }
403
+ });
404
+ if (!keeps) {
405
+ for (const field of fieldsUnder(struct, path)) {
406
+ if (!seen.has(field)) {
407
+ clear(field);
408
+ }
409
+ }
410
+ }
411
+ };
412
+ visit(node, []);
413
+ }
414
+ const values = [];
415
+ for (const field of struct.fields) {
416
+ const valueNode = given.get(field);
417
+ if (cleared.has(field)) {
418
+ field.optional = true;
419
+ }
420
+ else if (valueNode) {
421
+ values.push(itemValue(field, valueNode, list, environment));
422
+ }
423
+ }
424
+ return { kind: 'setRow', list, values, cleared: [...cleared] };
425
+ }
426
+ /**
427
+ * The local an update's row index is read through. Each has a name of its own, which no JS name can clash with.
428
+ *
429
+ * @returns The local.
430
+ */
431
+ function updateRowLocal() {
432
+ return { slotKind: 'int', name: `#row${updateRows++}` };
433
+ }
434
+ /**
435
+ * Whether an expression reads a row of a list by index: `items[k]`, under the list's name or the name a setter's
436
+ * updater gives it.
437
+ *
438
+ * @param node The expression.
439
+ * @param listState The list.
440
+ * @param listName What the setter's argument calls it.
441
+ * @param environment The expression environment.
442
+ *
443
+ * @returns Whether it does.
444
+ */
445
+ function readsRowsOf(node, listState, listName, environment) {
446
+ if (!node || typeof node !== 'object')
447
+ return false;
448
+ if (Array.isArray(node)) {
449
+ return node.some(child => readsRowsOf(child, listState, listName, environment));
450
+ }
451
+ const astNode = node;
452
+ if ((astNode.type === 'MemberExpression' ||
453
+ astNode.type === 'OptionalMemberExpression') &&
454
+ astNode.computed &&
455
+ astNode.object.type === 'Identifier' &&
456
+ (astNode.object.name === listName ||
457
+ environment.state.get(astNode.object.name) === listState)) {
458
+ return true;
459
+ }
460
+ return Object.entries(astNode).some(([key, child]) => !POSITION_KEYS.has(key) &&
461
+ readsRowsOf(child, listState, listName, environment));
462
+ }
463
+ /**
464
+ * Lowers `items.map(…)` as a list's next value: each row is visited, and set to what the function gives it.
465
+ *
466
+ * @param listState The list.
467
+ * @param listName What the setter's argument calls it.
468
+ * @param argument The map's function.
469
+ * @param environment The expression environment.
470
+ *
471
+ * @returns The statements.
472
+ */
473
+ function lowerItemsMap(listState, listName, argument, environment) {
474
+ const { itemName, indexName, body } = itemCallback(argument, `${listName}.map`);
475
+ // The rows are set in place, one after another, so a read of another row could see its new value.
476
+ if (readsRowsOf(body, listState, listName, environment)) {
477
+ throw aotError(`AOT: ${listName}.map's function can't read other items of ${listName}`, 'its items are set in place, so a read of another one could see its new value. Read it into a const ' +
478
+ `before the setter: const first = ${listName}[0].n.`);
479
+ }
480
+ const row = updateRowLocal();
481
+ const locals = new Map(environment.locals);
482
+ if (itemName) {
483
+ locals.set(itemName, {
484
+ name: itemName,
485
+ struct: listState.struct,
486
+ list: listState,
487
+ index: { kind: 'local', local: row, type: INT },
488
+ });
489
+ }
490
+ if (indexName) {
491
+ locals.set(indexName, row);
492
+ }
493
+ const statements = updateBody(body, {
494
+ list: listState,
495
+ listName,
496
+ environment: { ...environment, locals },
497
+ isRow: (node, path) => isPathOf(node, path, item => item.type === 'Identifier' && item.name === itemName),
498
+ });
499
+ return statements.length
500
+ ? [
501
+ {
502
+ kind: 'updateItems',
503
+ list: listState,
504
+ row,
505
+ index: null,
506
+ body: statements,
507
+ },
508
+ ]
509
+ : [];
510
+ }
511
+ /**
512
+ * Lowers `items.with(n, item)` as a list's next value: row n is set to the item. A negative n counts back from the
513
+ * end, and a row past either end stops the app, as JS throws there.
514
+ *
515
+ * @param listState The list.
516
+ * @param listName What the setter's argument calls it.
517
+ * @param argumentNodes The call's arguments.
518
+ * @param environment The expression environment.
519
+ *
520
+ * @returns The statements.
521
+ */
522
+ function lowerItemsWith(listState, listName, argumentNodes, environment) {
523
+ const [indexNode, itemNode] = argumentNodes;
524
+ if (argumentNodes.length !== 2 ||
525
+ indexNode.type === 'SpreadElement' ||
526
+ itemNode.type === 'SpreadElement') {
527
+ throw aotError(`AOT: ${listName}.with takes an index and an item`, `e.g. ${listName}.with(n, {...${listName}[n], done: true}).`);
528
+ }
529
+ const index = rowIndexOf(indexNode, listName, environment);
530
+ const constantIndex = staticInt(indexNode, environment);
531
+ // The replaced item: items[n], or a row's own item when n is that row's index. For a negative n, with() counts
532
+ // back but items[n] is undefined, so what the update keeps from it isn't the row's.
533
+ let keepsIndexed = false;
534
+ const isItem = (node) => {
535
+ if (node.type === 'MemberExpression' &&
536
+ node.computed &&
537
+ node.object.type === 'Identifier' &&
538
+ node.object.name === listName) {
539
+ const same = sameNode(node.property, indexNode);
540
+ keepsIndexed ||= same;
541
+ return same;
542
+ }
543
+ const local = node.type === 'Identifier'
544
+ ? environment.locals.get(node.name)
545
+ : undefined;
546
+ return (local?.list === listState &&
547
+ local.row !== undefined &&
548
+ local.row === constantIndex);
549
+ };
550
+ const row = updateRowLocal();
551
+ const statements = updateBody(itemNode, {
552
+ list: listState,
553
+ listName,
554
+ environment,
555
+ isRow: (node, path) => isPathOf(node, path, isItem),
556
+ });
557
+ if (keepsIndexed && constantIndex !== null && constantIndex < 0) {
558
+ throw aotError(`AOT: ${listName}.with(${constantIndex}, …) keeps fields of ${listName}[${constantIndex}], which is undefined`, `with() counts a negative index back from the end, but ${listName}[${constantIndex}] doesn't. ` +
559
+ `Use the index it counts back to, e.g. ${listName}.length - 1.`);
560
+ }
561
+ // Even an update that changes nothing reads the row, so an index past the end faults.
562
+ return [
563
+ {
564
+ kind: 'updateItems',
565
+ list: listState,
566
+ row,
567
+ index,
568
+ body: statements,
569
+ negativeKeeps: keepsIndexed && constantIndex === null,
570
+ },
571
+ ];
572
+ }
573
+ /**
574
+ * The arguments of a call to a method of the list: `items.slice(…)`, or null when it is no such call.
575
+ *
576
+ * @param node The expression.
577
+ * @param listName The list's name.
578
+ * @param method The method.
579
+ *
580
+ * @returns The arguments.
581
+ */
582
+ function listCall(node, listName, method) {
583
+ return node?.type === 'CallExpression' &&
584
+ node.callee.type === 'MemberExpression' &&
585
+ !node.callee.computed &&
586
+ node.callee.object.type === 'Identifier' &&
587
+ node.callee.object.name === listName &&
588
+ node.callee.property.name === method
589
+ ? node.arguments
590
+ : null;
591
+ }
592
+ /**
593
+ * The index `[...items.slice(0, n), ...items.slice(n + 1)]` removes, or null when the list literal is not that.
594
+ *
595
+ * @param nextList The list literal.
596
+ * @param listName The list's name.
597
+ * @param environment The expression environment.
598
+ *
599
+ * @returns n.
600
+ */
601
+ function slicedOutIndex(nextList, listName, environment) {
602
+ const [first, second] = nextList.elements;
603
+ if (nextList.elements.length !== 2 ||
604
+ first?.type !== 'SpreadElement' ||
605
+ second?.type !== 'SpreadElement') {
606
+ return null;
607
+ }
608
+ const before = listCall(first.argument, listName, 'slice');
609
+ const after = listCall(second.argument, listName, 'slice');
610
+ if (before?.length !== 2 || after?.length !== 1) {
611
+ return null;
612
+ }
613
+ const [start, end] = before;
614
+ const [next] = after;
615
+ const constantEnd = staticInt(end, environment);
616
+ const constantNext = staticInt(next, environment);
617
+ const followsOn = (next.type === 'BinaryExpression' &&
618
+ next.operator === '+' &&
619
+ sameNode(next.left, end) &&
620
+ staticInt(next.right, environment) === 1) ||
621
+ (constantEnd !== null && constantNext === constantEnd + 1);
622
+ if (staticInt(start, environment) !== 0 ||
623
+ !followsOn ||
624
+ (constantEnd !== null && constantEnd < 0)) {
625
+ throw aotError(`AOT: only [...${listName}.slice(0, n), ...${listName}.slice(n + 1)] is supported to splice a list`, 'it removes item n, which must not be negative.');
626
+ }
627
+ return end;
628
+ }
43
629
  /**
44
630
  * Lowers a list-state setter call (`setItems(...)`) to bounded list operations.
45
631
  *
46
632
  * @param listState The list state.
47
633
  * @param nextList The setter's argument: the list's next value.
48
634
  * @param environment The expression environment.
635
+ * @param listName What the argument calls the list: its name, or an updater's parameter.
49
636
  *
50
637
  * @returns The statements.
51
638
  */
52
- function lowerListOp(listState, nextList, environment) {
639
+ function lowerListOp(listState, nextList, environment, listName = listState.name) {
53
640
  const { capacity: capacity, struct } = listState;
54
- // setItems([...items, a, b]) — append; setItems([]) — clear.
641
+ // setWords(text.split(',')) — the pieces replace the rows.
642
+ const split = lowerSplitInto(listState, nextList, environment, listName);
643
+ if (split)
644
+ return split;
645
+ // setItems([...items, a, b]) — append; setItems([]) — clear; [...items.slice(0, n), ...items.slice(n + 1)] — remove.
55
646
  if (nextList.type === 'ArrayExpression') {
56
647
  if (nextList.elements.length === 0) {
57
648
  return [{ kind: 'clearList', list: listState }];
58
649
  }
650
+ const slicedOut = slicedOutIndex(nextList, listName, environment);
651
+ if (slicedOut) {
652
+ return [
653
+ {
654
+ kind: 'removeItem',
655
+ list: listState,
656
+ index: rowIndexOf(slicedOut, listName, environment),
657
+ negative: 'sliced',
658
+ },
659
+ ];
660
+ }
59
661
  const [firstElement, ...appendedItems] = nextList.elements;
60
662
  if (firstElement?.type !== 'SpreadElement' ||
61
- firstElement.argument.name !== listState.name) {
62
- throw new Error(`AOT: a list literal must spread the current list first: [...${listState.name}, item]`);
663
+ firstElement.argument.name !== listName) {
664
+ throw new Error(`AOT: a list literal must spread the current list first: [...${listName}, item]`);
63
665
  }
64
- // Each appended object literal fills every field of the next free slot; a full list drops it. A field it
65
- // leaves out is reset to 0 or "", as an initial item's is, so the slot keeps nothing from a cleared item.
666
+ // Each appended item fills the next free row; a full list drops it. A field it leaves out is 0 or "", and
667
+ // optional from then on, so a read of it sees undefined.
66
668
  const statements = [];
67
669
  for (const item of appendedItems) {
68
670
  if (!item) {
69
671
  throw aotError('AOT: a list literal has an empty slot');
70
672
  }
71
- if (item.type !== 'ObjectExpression') {
72
- throw new Error('AOT: appended list items must be object literals');
673
+ if (item.type === 'SpreadElement') {
674
+ throw aotError(`AOT: a list literal can spread only the current list, first: [...${listName}, item]`);
73
675
  }
74
- const props = new Map(item.properties.map((prop) => [
75
- prop.key.name ??
76
- prop.key.value,
77
- prop.value,
78
- ]));
676
+ const given = appendedFields(item, struct, listName);
79
677
  const values = [];
80
678
  for (const field of struct.fields) {
81
- const valueNode = props.get(field.key);
82
- if (!valueNode) {
83
- values.push(field.kind === 'string'
84
- ? { field, text: { parts: [] } }
85
- : {
86
- field,
87
- value: {
88
- kind: 'number',
89
- value: 0,
90
- type: field.kind === 'float' ? FLOAT : INT,
91
- },
92
- });
93
- }
94
- else if (field.kind === 'string') {
95
- const text = lowerText(valueNode, environment);
96
- checkConstantFits(text, `field "${field.key}" of list state "${listState.name}"`, environment);
97
- values.push({ field, text });
679
+ const valueNode = given.get(field.key);
680
+ if (valueNode) {
681
+ values.push(itemValue(field, valueNode, listState, environment));
98
682
  }
99
683
  else {
100
- values.push({
101
- field,
102
- value: storeValue(lowerExpr(valueNode, environment), field.kind),
103
- });
684
+ field.optional = true;
104
685
  }
105
686
  }
106
687
  statements.push({ kind: 'appendItem', list: listState, values });
107
688
  }
108
689
  return statements;
109
690
  }
691
+ // filter((_, i) => i !== n) removes item n; other filters and sorts change the rows in place.
692
+ const chain = listChainOf(nextList);
693
+ if (chain?.base.type === 'Identifier' && chain.base.name === listName) {
694
+ const [step] = chain.steps;
695
+ const index = chain.steps.length === 1 && step.kind === 'filter'
696
+ ? filteredIndex(itemCallback(step.callback, step.what))
697
+ : null;
698
+ if (index) {
699
+ return [
700
+ {
701
+ kind: 'removeItem',
702
+ list: listState,
703
+ index: rowIndexOf(index, listName, environment),
704
+ negative: 'none',
705
+ },
706
+ ];
707
+ }
708
+ return lowerListOrder(listState, listName, chain, environment);
709
+ }
710
+ // toSpliced(n, 1) removes item n, counting a negative n back from the end.
711
+ const splicedArguments = listCall(nextList, listName, 'toSpliced');
712
+ if (splicedArguments) {
713
+ const [start, count] = splicedArguments;
714
+ if (splicedArguments.length !== 2 ||
715
+ start.type === 'SpreadElement' ||
716
+ staticInt(count, environment) !== 1) {
717
+ throw aotError(`AOT: only ${listName}.toSpliced(n, 1) is supported on a list`, 'it removes item n.');
718
+ }
719
+ return [
720
+ {
721
+ kind: 'removeItem',
722
+ list: listState,
723
+ index: rowIndexOf(start, listName, environment),
724
+ negative: 'spliced',
725
+ },
726
+ ];
727
+ }
728
+ // map(item => …) and with(n, item) set items in place.
729
+ const mapArguments = listCall(nextList, listName, 'map');
730
+ if (mapArguments) {
731
+ return lowerItemsMap(listState, listName, mapArguments[0], environment);
732
+ }
733
+ const withArguments = listCall(nextList, listName, 'with');
734
+ if (withArguments) {
735
+ return lowerItemsWith(listState, listName, withArguments, environment);
736
+ }
110
737
  // slice(0, end) keeps the first items by JS rules: a negative end counts back, a large or missing one keeps all.
111
- if (nextList.type === 'CallExpression' &&
112
- nextList.callee.type === 'MemberExpression' &&
113
- nextList.callee.object.name === listState.name &&
114
- nextList.callee.property.name === 'slice') {
115
- const [start, end] = nextList.arguments;
738
+ const sliceArguments = listCall(nextList, listName, 'slice');
739
+ if (sliceArguments) {
740
+ const [start, end] = sliceArguments;
116
741
  if (start && staticInt(start, environment) !== 0) {
117
- throw aotError(`AOT: only ${listState.name}.slice(0, end) is supported on a list`, `a list is a fixed pool and a count, so a slice can only drop items from the end — ` +
118
- `e.g. ${listState.name}.slice(0, -1) drops the last one.`);
742
+ throw aotError(`AOT: only ${listName}.slice(0, end) is supported on a list`, `a list is a fixed pool and a count, so a slice can only drop items from the end — ` +
743
+ `e.g. ${listName}.slice(0, -1) drops the last one.`);
119
744
  }
120
745
  if (!end)
121
746
  return [];
@@ -146,43 +771,67 @@ function lowerListOp(listState, nextList, environment) {
146
771
  },
147
772
  ];
148
773
  }
149
- throw new Error(`AOT: unsupported list operation on "${listState.name}" (use [...${listState.name}, ` +
150
- `item], ${listState.name}.slice(0, n), or [])`);
774
+ throw aotError(`AOT: unsupported list operation on "${listName}"`, `use [...${listName}, item], ${listName}.slice(0, n), [], ${listName}.filter(item => …), ` +
775
+ `${listName}.toSorted((a, b) => …), ${listName}.toSpliced(n, 1), ${listName}.map(item => …) or ` +
776
+ `${listName}.with(n, item).`);
151
777
  }
152
778
  /**
153
- * Returns a statement node's body list: a BlockStatement's contents, or the lone statement wrapped.
779
+ * Lowers filters and sorts as a list's next value: each changes the rows in place, a filter dropping the rows it
780
+ * doesn't keep and a sort moving them, equal ones kept in order.
154
781
  *
155
- * @param node An `if` branch.
782
+ * @param listState The list.
783
+ * @param listName What the setter's argument calls it.
784
+ * @param chain The filters and sorts.
785
+ * @param environment The expression environment.
156
786
  *
157
- * @returns Its statements.
787
+ * @returns The statements.
158
788
  */
159
- function blockList(node) {
160
- return node.type === 'BlockStatement' ? node.body : [node];
789
+ function lowerListOrder(listState, listName, chain, environment) {
790
+ // The rows move as the steps run, so a read of another row could see a different one.
791
+ for (const step of chain.steps) {
792
+ if (readsRowsOf(step.callback, listState, listName, environment)) {
793
+ throw aotError(`AOT: ${step.what}'s function can't read other items of ${listName}`, 'its items move as it runs, so a read of another one could see a different item. Read it into a ' +
794
+ `const before the setter: const first = ${listName}[0].n.`);
795
+ }
796
+ }
797
+ return orderStatements(listState, chain.steps.map(step => ({ ...step, environment })), {
798
+ itemAt: position => ({
799
+ name: `${listName}[]`,
800
+ struct: listState.struct,
801
+ list: listState,
802
+ index: { kind: 'local', local: position, type: INT },
803
+ }),
804
+ listName,
805
+ source: listState,
806
+ });
161
807
  }
162
808
  /**
163
- * Checks a value written to a numeric state or ref slot, whose kind came from its initial value. Every value
164
- * written to an int slot is recorded in environment.stores, from which the typing pass infers the slots that hold a
165
- * 64-bit timestamp, and compileWidened compiles again with those slots widened to 64 bits. A timestamp cannot
166
- * go into a float or boolean slot (a 64-bit constant can go into a float one), and a widened slot takes no
167
- * floats.
168
- *
169
- * @param lowered The value: its source, and its type.
170
- * @param slotType The slot's kind.
171
- * @param isBoolean The slot holds a boolean.
172
- * @param widened What the slot holds, if it was widened to 64 bits.
173
- * @param slotName The slot's name, for environment.stores.
174
- * @param slotDescription The slot, for the message.
809
+ * Records a value written to a whole-number state, ref or `let` slot, whose kind came from its initial value:
810
+ * from every such value the typing pass infers the slots that hold 64 bits.
811
+ *
812
+ * @param value The value's source.
813
+ * @param slotName The slot's name.
814
+ * @param target The state or ref, or the `let` local.
175
815
  * @param environment The expression environment.
176
816
  */
177
- function storeCheck(lowered, slotType, isBoolean, widened, slotName, slotDescription, environment) {
178
- const value = lowered.expression;
179
- if ((slotType === 'int' && !isBoolean) || widened === 'number') {
180
- environment.stores.push({
181
- slot: slotName,
182
- value: lowered.source,
183
- math64: Boolean(environment.math64),
184
- });
185
- }
817
+ function recordStore(value, slotName, target, environment) {
818
+ environment.stores.push({
819
+ slot: slotName,
820
+ value,
821
+ math64: environment.math64,
822
+ ...('kind' in target ? { target } : { local: target }),
823
+ });
824
+ }
825
+ /**
826
+ * Checks a value written to a numeric slot, once both are typed. A timestamp cannot go into a float or boolean
827
+ * slot (a 64-bit constant can go into a float one), and a 64-bit slot takes no floats.
828
+ *
829
+ * @param value The typed value.
830
+ * @param slot The slot.
831
+ * @param slotDescription The slot, for the message.
832
+ */
833
+ function checkStored(value, slot, slotDescription) {
834
+ const { slotType, isBoolean } = slot;
186
835
  if (value.type.kind === 'int64' && slotType !== 'i64') {
187
836
  if (slotType === 'int' && !isBoolean)
188
837
  return;
@@ -195,25 +844,46 @@ function storeCheck(lowered, slotType, isBoolean, widened, slotName, slotDescrip
195
844
  }
196
845
  }
197
846
  /**
198
- * `value` for an int destination. A float goes through a checked conversion: a plain one is undefined for
199
- * NaN or a value past the int range.
847
+ * The environment a value stored in a slot is lowered in: a 64-bit slot takes int `+ - *` worked out in 64
848
+ * bits.
200
849
  *
201
- * @param value The lowered value.
850
+ * @param environment The expression environment.
851
+ * @param is64Bit Whether the slot holds 64 bits, asked once its width is known.
852
+ *
853
+ * @returns The value's environment.
854
+ */
855
+ function storeEnvironment(environment, is64Bit) {
856
+ const outer = environment.math64;
857
+ return { ...environment, math64: () => is64Bit() || Boolean(outer?.()) };
858
+ }
859
+ /**
860
+ * A typed value for an int destination. A float goes through a checked conversion: a plain one is undefined
861
+ * for NaN or a value past the int range.
862
+ *
863
+ * @param value The typed value.
202
864
  *
203
865
  * @returns The value as an int.
204
866
  */
205
- const asInt = (value) => value.type.kind === 'float'
867
+ const typedAsInt = (value) => value.type.kind === 'float'
206
868
  ? { kind: 'toInt', operand: value, type: INT }
207
869
  : value;
208
870
  /**
209
- * `value` for a slot of `slotType`: an int slot takes a float the way asInt does.
871
+ * `value` for an int destination (see typedAsInt).
210
872
  *
211
873
  * @param value The lowered value.
212
- * @param slotType The slot's kind.
874
+ *
875
+ * @returns The value as an int.
876
+ */
877
+ const asInt = (value) => typedLater('number', () => typedAsInt(value), [value]);
878
+ /**
879
+ * `value` for a slot: an int slot takes a float the way asInt does.
880
+ *
881
+ * @param value The lowered value.
882
+ * @param slotType The slot's kind, asked once it is known.
213
883
  *
214
884
  * @returns The value the slot stores.
215
885
  */
216
- const storeValue = (value, slotType) => slotType === 'int' ? asInt(value) : value;
886
+ const storeValue = (value, slotType) => typedLater(shapeOf(value), () => (slotType() === 'int' ? typedAsInt(value) : value), [value]);
217
887
  /**
218
888
  * A read of a ref's current value.
219
889
  *
@@ -227,21 +897,20 @@ const refRead = (ref) => ({
227
897
  type: refType(ref),
228
898
  });
229
899
  /**
230
- * Refuses a constant string too long for the buffer it is written into, which would cut it short. A string
900
+ * Refuses a constant string too long for the buffer a write is built in, which would cut it short. A string
231
901
  * built at run time is checked when it is written instead.
232
902
  *
233
903
  * @param text The text written.
234
904
  * @param what What it is written into, for the error.
235
- * @param environment The expression environment.
236
905
  */
237
- function checkConstantFits(text, what, environment) {
906
+ function checkConstantFits(text, what) {
238
907
  const constant = constantText(text);
239
908
  if (constant === null) {
240
909
  return;
241
910
  }
242
911
  const bytes = Buffer.byteLength(constant, 'utf8');
243
- if (bytes >= environment.caps.listStrCap) {
244
- throw aotError(`AOT: ${what} is set to a ${bytes}-byte string, but a string holds ${environment.caps.listStrCap - 1} bytes`, 'raise ER_AOT_LIST_STR_CAP (the listStrCap option), or shorten the string.');
912
+ if (bytes > ENGINE_STRING_MAX.ER_TEXT_MAX) {
913
+ throw aotError(`AOT: ${what} is set to a ${bytes}-byte string, but a write holds ${ENGINE_STRING_MAX.ER_TEXT_MAX} bytes (ER_TEXT_MAX)`, 'shorten the string: a write is built in a buffer that ER_TEXT_MAX in er_scene.h sizes.');
245
914
  }
246
915
  }
247
916
  /**
@@ -256,26 +925,126 @@ function checkConstantFits(text, what, environment) {
256
925
  */
257
926
  function lowerScalarSet(scalarState, valueNode, environment) {
258
927
  if (scalarState.slotKind !== 'string') {
259
- // A 64-bit slot takes int `+ - *` worked out in 64 bits.
260
- const lowered = lowerSource(valueNode, scalarState.slotKind === 'i64'
261
- ? { ...environment, math64: true }
262
- : environment);
928
+ const lowered = lowerSource(valueNode, storeEnvironment(environment, () => is64BitSlot(scalarState)));
263
929
  const value = lowered.expression;
264
- storeCheck(lowered, scalarState.slotKind, scalarState.isBoolean, scalarState.widened, scalarState.slotName, `state "${scalarState.name}"`, environment);
930
+ if ((scalarState.slotKind === 'int' && !scalarState.isBoolean) ||
931
+ scalarState.widened === 'number') {
932
+ recordStore(lowered.source, scalarState.slotName, scalarState, environment);
933
+ }
934
+ whenTyped(() => checkStored(value, { slotType: scalarState.slotKind, isBoolean: scalarState.isBoolean }, `state "${scalarState.name}"`));
265
935
  return {
266
936
  kind: 'setState',
267
937
  state: scalarState,
268
- value: storeValue(value, scalarState.slotKind),
938
+ value: storeValue(value, () => scalarState.slotKind),
269
939
  };
270
940
  }
271
941
  const text = lowerText(valueNode, environment);
272
- checkConstantFits(text, `state "${scalarState.name}"`, environment);
942
+ checkConstantFits(text, `state "${scalarState.name}"`);
273
943
  return {
274
944
  kind: 'setStateText',
275
945
  state: scalarState,
276
946
  text,
277
947
  };
278
948
  }
949
+ /** How an object setter's writes are lowered. */
950
+ const RECORD_LOWERING = {
951
+ field: lowerScalarSet,
952
+ test: (node, environment) => lowerExprWide(node, environment),
953
+ };
954
+ /**
955
+ * Works out a write to a value ref, `ref.current = …` or a compound assignment, once the ref and the value are
956
+ * typed. It does not trigger a re-render.
957
+ *
958
+ * @param expression The assignment.
959
+ * @param ref The ref.
960
+ * @param loweredValue The right side: its source, and the typed value.
961
+ * @param environment The expression environment.
962
+ *
963
+ * @returns The write's operator and value.
964
+ */
965
+ function typedRefWrite(expression, ref, loweredValue, environment) {
966
+ const valueExpression = loweredValue.expression;
967
+ const refHoldsTime = isTime(refType(ref));
968
+ if (expression.operator === '/=' &&
969
+ (refHoldsTime || isTime64(valueExpression))) {
970
+ throw aotError('AOT: `/=` on a 64-bit time value is not supported', 'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.');
971
+ }
972
+ // A 64-bit `%=` keeps its constant divisor.
973
+ const wideModuloDivisor = expression.operator === '%=' && (refHoldsTime || isTime64(valueExpression))
974
+ ? constDivisor(expression.right, environment)
975
+ : null;
976
+ checkStored(valueExpression, { slotType: ref.slotKind, isBoolean: false }, `ref "${expression.left.object.name}"`);
977
+ const stored = (value) => ref.slotKind === 'int' ? typedAsInt(value) : value;
978
+ // Whole-ref `+= -= *=`, float `/=` and float `%=` are the binary op, to share its checked and float math.
979
+ const isWholeRef = ref.slotKind === 'int' || ref.slotKind === 'i64';
980
+ const binaryOperation = { '+=': '+', '-=': '-', '*=': '*' }[expression.operator];
981
+ const isFloatModulo = expression.operator === '%=' &&
982
+ (ref.slotKind === 'float' || valueExpression.type.kind === 'float');
983
+ if ((isWholeRef &&
984
+ (binaryOperation ||
985
+ (expression.operator === '/=' &&
986
+ valueExpression.type.kind === 'float'))) ||
987
+ isFloatModulo) {
988
+ const resultExpression = typeSource(binarySource({
989
+ type: 'BinaryExpression',
990
+ operator: binaryOperation ?? expression.operator.slice(0, -1),
991
+ left: expression.left,
992
+ right: expression.right,
993
+ loc: expression.loc,
994
+ }, { kind: 'ref', ref, location: expression.left.loc?.start }, loweredValue.source, environment), ref.slotKind === 'i64' || Boolean(environment.math64?.()));
995
+ return { operator: '=', value: stored(resultExpression) };
996
+ }
997
+ // Whole-number `/=` and `%=` use the checked helpers for JS's answer, in 64 bits on a 64-bit ref that holds no
998
+ // time; a constant divisor other than 0 or -1 needs no check.
999
+ const isWholeValue = isIntSlot(valueExpression.type) ||
1000
+ (valueExpression.type.kind === 'int64' && !isTime64(valueExpression));
1001
+ const refBits = ref.slotKind === 'i64' ? 64 : 32;
1002
+ if (((ref.slotKind === 'int' && isIntSlot(valueExpression.type)) ||
1003
+ (ref.slotKind === 'i64' && !refHoldsTime && isWholeValue)) &&
1004
+ (expression.operator === '/=' || expression.operator === '%=')) {
1005
+ const staticDivisor = staticInt(expression.right, environment);
1006
+ if (expression.operator === '/=' &&
1007
+ (staticDivisor === null || staticDivisor === 0 || staticDivisor === -1)) {
1008
+ return {
1009
+ operator: '=',
1010
+ value: {
1011
+ kind: 'helper',
1012
+ helper: 'div',
1013
+ bits: refBits,
1014
+ callArguments: [refRead(ref), valueExpression],
1015
+ type: refType(ref),
1016
+ },
1017
+ };
1018
+ }
1019
+ if (expression.operator === '%=' &&
1020
+ (staticDivisor === 0 || staticDivisor === -1)) {
1021
+ return { operator: '=', value: ZERO };
1022
+ }
1023
+ if (expression.operator === '%=' && staticDivisor === null) {
1024
+ return {
1025
+ operator: '=',
1026
+ value: {
1027
+ kind: 'helper',
1028
+ helper: 'mod',
1029
+ bits: refBits,
1030
+ callArguments: [refRead(ref), valueExpression],
1031
+ type: refType(ref),
1032
+ },
1033
+ };
1034
+ }
1035
+ }
1036
+ // A 64-bit `%=` by 0 or ±1 stores 0: no remainder, JS's NaN as 0, and no overflow on INT64_MIN % -1.
1037
+ if (wideModuloDivisor === 0 ||
1038
+ wideModuloDivisor === 1 ||
1039
+ wideModuloDivisor === -1) {
1040
+ return { operator: '=', value: ZERO };
1041
+ }
1042
+ // Everything else is a plain assignment or compound assignment.
1043
+ return {
1044
+ operator: expression.operator,
1045
+ value: expression.operator === '=' ? stored(valueExpression) : valueExpression,
1046
+ };
1047
+ }
279
1048
  /**
280
1049
  * Resolves `node` to its ref when it is `<ref>.current` member access on a known value ref.
281
1050
  *
@@ -428,54 +1197,311 @@ function lowerUpdateVector(expression, environment, context) {
428
1197
  update.tape.push({ kind: 'op', operation: 'ER_VECTOR_OP_SHAPE' }, checkedTapeNumber(update.paints.length), ...shape.entries);
429
1198
  update.paints.push(shape.paint);
430
1199
  }
431
- // Declare the op-tape and its paint table.
432
- checkVectorPaints(update.paints);
433
- output.vectors.push({ kind: 'updateVector', update });
434
- // Hint the dirty sub-rect when the call gives one.
435
- if (dirtyArgument) {
436
- if (dirtyArgument.type !== 'ArrayExpression' ||
437
- dirtyArgument.elements.length < 4) {
438
- throw new Error('AOT: updateVector dirtyRect must be a [x, y, w, h] array literal');
439
- }
440
- update.dirty = dirtyArgument.elements.slice(0, 4).map((edgeNode, edge) => {
441
- if (!edgeNode) {
442
- throw aotError(`AOT: updateVector dirtyRect has an empty slot at position ${edge}`);
443
- }
444
- return lowerExpr(edgeNode, environment);
445
- });
1200
+ // Declare the op-tape and its paint table.
1201
+ checkVectorPaints(update.paints);
1202
+ output.vectors.push({ kind: 'updateVector', update });
1203
+ // Hint the dirty sub-rect when the call gives one.
1204
+ if (dirtyArgument) {
1205
+ if (dirtyArgument.type !== 'ArrayExpression' ||
1206
+ dirtyArgument.elements.length < 4) {
1207
+ throw new Error('AOT: updateVector dirtyRect must be a [x, y, w, h] array literal');
1208
+ }
1209
+ update.dirty = dirtyArgument.elements.slice(0, 4).map((edgeNode, edge) => {
1210
+ if (!edgeNode) {
1211
+ throw aotError(`AOT: updateVector dirtyRect has an empty slot at position ${edge}`);
1212
+ }
1213
+ return lowerExpr(edgeNode, environment);
1214
+ });
1215
+ }
1216
+ return update;
1217
+ }
1218
+ /**
1219
+ * Lowers setInterval/setTimeout(cb, ms) to a timer, and registers cb as a timer function of its own.
1220
+ *
1221
+ * @param expression The setInterval / setTimeout call.
1222
+ * @param environment The expression environment.
1223
+ * @param state The component's state table.
1224
+ * @param context The statement compiler's context.
1225
+ *
1226
+ * @returns The timer.
1227
+ */
1228
+ function lowerTimer(expression, environment, state, context) {
1229
+ const callback = expression.arguments[0];
1230
+ if (!isFn(callback)) {
1231
+ throw aotError('AOT: a setInterval/setTimeout callback must be an inline function', 'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).');
1232
+ }
1233
+ // Any delay is accepted here; the printer converts a timestamp or float one the way Flow A's setTimeout does.
1234
+ const delay = expression.arguments[1]
1235
+ ? lowerExprWide(expression.arguments[1], environment)
1236
+ : null;
1237
+ const isRepeating = expression.callee.name === 'setInterval';
1238
+ // Reserve the timer's slot before compiling its body, which may add timers of its own.
1239
+ const slot = context.output.timerFunctions.length;
1240
+ const timerFunctionName = `timer_${slot}`;
1241
+ context.output.timerFunctions.push({ name: timerFunctionName, callback: null });
1242
+ context.output.timerFunctions[slot].callback = lowerHandler(callback, environment, state, context.output);
1243
+ return { delay, isRepeating, functionName: timerFunctionName };
1244
+ }
1245
+ /**
1246
+ * Checks a setter called inside a loop. One for a list the loop visits is refused, as the loop would see the rows
1247
+ * it changes, where React's loops over the list as it was. So is a setter given a value that reads its own state:
1248
+ * React's reads the value from before the loop each time, so only the last call counts, where Flow B's would see
1249
+ * each call's.
1250
+ *
1251
+ * @param setter The setter's name.
1252
+ * @param target What it sets.
1253
+ * @param argument What it is given.
1254
+ * @param environment The expression environment.
1255
+ * @param loops The lists each loop around it visits or is bounded by.
1256
+ */
1257
+ function checkLoopSetter(setter, target, argument, environment, loops) {
1258
+ if (target.kind === 'list' && loops.some(lists => lists.includes(target))) {
1259
+ throw aotError(`AOT: ${setter} can't change ${target.name} inside a loop over it`, 'the loop would see the rows it changes, where React loops over the list as it was. Work out what to ' +
1260
+ 'change in the loop, into a let, and set the list after it.');
1261
+ }
1262
+ if (!argument || isFn(argument))
1263
+ return;
1264
+ const names = new Set([target.name]);
1265
+ for (const [name, record] of environment.state) {
1266
+ if (record === target)
1267
+ names.add(name);
1268
+ }
1269
+ if (mentions(argument, names)) {
1270
+ throw aotError(`AOT: ${setter}(…) inside a loop must take an updater to read ${target.name}`, `React reads ${target.name} from before the loop each time, so only the last call would count. Write ` +
1271
+ `${setter}(previous => …), or work the value out in a let and set it after the loop.`);
1272
+ }
1273
+ }
1274
+ /**
1275
+ * Lowers `x = …`, `x += …` or `x++` on a `let` local. A whole-number `let` given a fraction or a timestamp is
1276
+ * widened to hold it, once every store is lowered; a boolean or a string one holds only those.
1277
+ *
1278
+ * @param expression The assignment or update.
1279
+ * @param target The local's name.
1280
+ * @param local The local.
1281
+ * @param environment The expression environment.
1282
+ *
1283
+ * @returns The statement.
1284
+ */
1285
+ function lowerLocalAssign(expression, target, local, environment) {
1286
+ const { name } = target;
1287
+ if (!local.assignable) {
1288
+ if (local.list) {
1289
+ throw aotError(`AOT: "${name}" is a list's item, which can't be set`, `copy what you need into a let: let value = ${name}.value;`);
1290
+ }
1291
+ throw aotError(local.counter
1292
+ ? `AOT: "${name}" is a loop's counter, which only the loop sets`
1293
+ : `AOT: "${name}" can't be assigned: only a \`let\` can`, local.counter
1294
+ ? `copy it into a let of its own first: let at = ${name};`
1295
+ : `declare it with let to change it: let ${name} = …;`);
1296
+ }
1297
+ // What it is set to, as one expression: `x += e` is `x + e`, and `x++` is `x + 1`.
1298
+ const { loc } = expression;
1299
+ let valueNode;
1300
+ if (expression.type === 'UpdateExpression') {
1301
+ valueNode = {
1302
+ type: 'BinaryExpression',
1303
+ operator: expression.operator === '++' ? '+' : '-',
1304
+ left: target,
1305
+ right: { type: 'NumericLiteral', value: 1 },
1306
+ loc,
1307
+ };
1308
+ }
1309
+ else if (expression.operator === '=') {
1310
+ valueNode = expression.right;
1311
+ }
1312
+ else {
1313
+ const operator = expression.operator.slice(0, -1);
1314
+ valueNode =
1315
+ operator === '&&' || operator === '||' || operator === '??'
1316
+ ? {
1317
+ type: 'LogicalExpression',
1318
+ operator,
1319
+ left: target,
1320
+ right: expression.right,
1321
+ loc,
1322
+ }
1323
+ : {
1324
+ type: 'BinaryExpression',
1325
+ operator: operator,
1326
+ left: target,
1327
+ right: expression.right,
1328
+ loc,
1329
+ };
1330
+ }
1331
+ const holds = (what) => aotError(`AOT: "${name}" holds ${what}, so it can only be set to ${what === 'a string' ? 'strings' : what === 'a boolean' ? 'booleans' : 'numbers'}`, `a let keeps the kind of value it starts with; declare another let for a value of another kind.`);
1332
+ const localName = local.name;
1333
+ // A string is built in the local's buffer, which may be read to build it.
1334
+ if (localShape(local) === 'string') {
1335
+ if (buildsText(valueNode, environment)) {
1336
+ return {
1337
+ kind: 'assignLocal',
1338
+ name: localName,
1339
+ value: { kind: 'string', value: '', type: STRING },
1340
+ text: lowerText(valueNode, environment),
1341
+ };
1342
+ }
1343
+ const value = lowerExpr(valueNode, environment);
1344
+ if (shapeOf(value) !== 'string')
1345
+ throw holds('a string');
1346
+ whenTyped(() => {
1347
+ if (value.kind === 'string') {
1348
+ checkConstantFits({ parts: [{ kind: 'literal', text: value.value }] }, `local "${name}"`);
1349
+ }
1350
+ });
1351
+ return { kind: 'assignLocal', name: localName, value };
1352
+ }
1353
+ const holdsBoolean = localShape(local) === 'bool';
1354
+ const lowered = lowerSource(valueNode, storeEnvironment(environment, () => is64BitLocal(local)));
1355
+ const shape = shapeOf(lowered.expression);
1356
+ if (holdsBoolean ? shape !== 'bool' : shape === 'bool') {
1357
+ throw holds(holdsBoolean ? 'a boolean' : 'a number');
1358
+ }
1359
+ if (shape === 'string')
1360
+ throw holds('a number');
1361
+ if (!holdsBoolean) {
1362
+ recordStore(lowered.source, local.assignable, local, environment);
1363
+ }
1364
+ whenTyped(() => checkStored(lowered.expression, { slotType: local.slotKind, isBoolean: holdsBoolean }, `local "${name}"`));
1365
+ return {
1366
+ kind: 'assignLocal',
1367
+ name: localName,
1368
+ value: storeValue(lowered.expression, () => local.slotKind),
1369
+ };
1370
+ }
1371
+ /**
1372
+ * The environment an updater's body reads: its parameter names the state's current value. A list's is the list,
1373
+ * an object's its fields, and a scalar's a read of its slot.
1374
+ *
1375
+ * @param target The state set.
1376
+ * @param updater The updater.
1377
+ * @param environment The handler's environment.
1378
+ *
1379
+ * @returns The body's environment.
1380
+ */
1381
+ function updaterEnvironment(target, updater, environment) {
1382
+ const previousName = updater.params[0]?.name;
1383
+ if (!previousName)
1384
+ return environment;
1385
+ // The parameter hides any local or state of its name.
1386
+ const locals = new Map(environment.locals);
1387
+ locals.delete(previousName);
1388
+ const state = new Map(environment.state);
1389
+ state.delete(previousName);
1390
+ if (target.kind === 'list') {
1391
+ return {
1392
+ ...environment,
1393
+ locals,
1394
+ state: state.set(previousName, target),
1395
+ };
1396
+ }
1397
+ if (target.kind === 'record') {
1398
+ return {
1399
+ ...environment,
1400
+ locals,
1401
+ state,
1402
+ constants: { ...environment.constants, [previousName]: target.value },
1403
+ };
1404
+ }
1405
+ const previous = stateRead(target, true);
1406
+ locals.set(previousName, holdLater({
1407
+ source: {
1408
+ kind: 'state',
1409
+ state: target,
1410
+ latest: true,
1411
+ location: undefined,
1412
+ },
1413
+ expression: previous,
1414
+ }, shapeOf(previous), () => ({
1415
+ slotKind: target.slotKind,
1416
+ isBoolean: target.isBoolean,
1417
+ ...(target.widened === 'number' ? { isLiteral: true } : {}),
1418
+ })));
1419
+ return { ...environment, locals, state };
1420
+ }
1421
+ /**
1422
+ * Lowers a setter given an updater with a block body: the body runs in place, and each `return next` sets the
1423
+ * state through an updater of its own, then leaves the body.
1424
+ *
1425
+ * @param setter The setter's name.
1426
+ * @param target The state set.
1427
+ * @param updater The updater.
1428
+ * @param environment The handler's environment.
1429
+ * @param state The component's state table.
1430
+ * @param context The statement compiler's context.
1431
+ * @param what What the updater is, for errors.
1432
+ *
1433
+ * @returns The statements.
1434
+ */
1435
+ function inlineUpdater(setter, target, updater, environment, state, context, what) {
1436
+ const statements = updaterStatements(setter, updater, target.kind === 'list', what);
1437
+ const { helperList, usedReturn } = context;
1438
+ context.helperList = statements;
1439
+ context.usedReturn = false;
1440
+ try {
1441
+ const lowered = lowerStmts(statements, updaterEnvironment(target, updater, environment), state, context);
1442
+ return context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered;
1443
+ }
1444
+ finally {
1445
+ context.helperList = helperList;
1446
+ context.usedReturn = usedReturn;
446
1447
  }
447
- return update;
448
1448
  }
449
1449
  /**
450
- * Lowers setInterval/setTimeout(cb, ms) to a timer, and registers cb as a timer function of its own.
1450
+ * Lowers a dispatch: the reducer runs in place as an updater, its state parameter reading the state and its action
1451
+ * parameter bound to what is dispatched. Branches the action's constant fields rule out are dropped first.
451
1452
  *
452
- * @param expression The setInterval / setTimeout call.
453
- * @param environment The expression environment.
1453
+ * @param dispatch The dispatch's name.
1454
+ * @param target The state it sets.
1455
+ * @param reducer The state's reducer.
1456
+ * @param action What is dispatched.
1457
+ * @param environment The handler's environment.
454
1458
  * @param state The component's state table.
455
1459
  * @param context The statement compiler's context.
456
1460
  *
457
- * @returns The timer.
1461
+ * @returns The statements.
458
1462
  */
459
- function lowerTimer(expression, environment, state, context) {
460
- const callback = expression.arguments[0];
461
- if (!isFn(callback)) {
462
- throw aotError('AOT: a setInterval/setTimeout callback must be an inline function', 'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).');
1463
+ function inlineReducer(dispatch, target, { name, functionNode }, action, environment, state, context) {
1464
+ const [stateParameter, actionParameter] = functionNode.params;
1465
+ if (!action || action.type === 'SpreadElement') {
1466
+ throw aotError(`AOT: ${dispatch} must be given an action`, `pass the action itself: ${dispatch}({type: 'increment'}).`);
463
1467
  }
464
- // Any delay is accepted here; the printer converts a timestamp or float one the way Flow A's setTimeout does.
465
- const delay = expression.arguments[1]
466
- ? lowerExprWide(expression.arguments[1], environment)
467
- : null;
468
- const isRepeating = expression.callee.name === 'setInterval';
469
- // Reserve the timer's slot before compiling its body, which may add timers of its own.
470
- const slot = context.output.timerFunctions.length;
471
- const timerFunctionName = `timer_${slot}`;
472
- context.output.timerFunctions.push({ name: timerFunctionName, callback: null });
473
- context.output.timerFunctions[slot].callback = lowerHandler(callback, environment, state, context.output);
474
- return { delay, isRepeating, functionName: timerFunctionName };
1468
+ // An action that picks between two at run time dispatches each in a branch of its own.
1469
+ const choice = actionChoice(action, foldScope(environment, environment.constants ?? {}));
1470
+ if (choice) {
1471
+ const dispatchOf = (picked) => inlineReducer(dispatch, target, { name, functionNode }, picked, environment, state, context);
1472
+ return [
1473
+ {
1474
+ kind: 'if',
1475
+ test: lowerExprWide(choice.test, environment),
1476
+ consequent: dispatchOf(choice.whenTrue),
1477
+ alternate: dispatchOf(choice.whenFalse),
1478
+ },
1479
+ ];
1480
+ }
1481
+ const bodyEnvironment = actionEnvironment(actionParameter?.name, action, environment);
1482
+ const statements = functionNode.body.type === 'BlockStatement'
1483
+ ? functionNode.body.body
1484
+ : [{ type: 'ReturnStatement', argument: functionNode.body }];
1485
+ const unpruned = {
1486
+ type: 'ArrowFunctionExpression',
1487
+ params: stateParameter ? [stateParameter] : [],
1488
+ body: { type: 'BlockStatement', body: statements, directives: [] },
1489
+ loc: functionNode.loc,
1490
+ };
1491
+ const readEnvironment = updaterEnvironment(target, unpruned, bodyEnvironment);
1492
+ const updater = {
1493
+ ...unpruned,
1494
+ body: {
1495
+ ...unpruned.body,
1496
+ body: prunedStatements(statements, foldScope(readEnvironment, readEnvironment.constants ?? {})),
1497
+ },
1498
+ };
1499
+ return inlineUpdater(dispatch, target, updater, bodyEnvironment, state, context, `reducer "${name}"`);
475
1500
  }
476
1501
  /**
477
- * Inlines a handler-statement call to a helper / useCallback: binds the call's args to the helper's params
478
- * as locals, then lowers the helper body here in the current env/state/ctx. Guards against recursion.
1502
+ * Inlines a handler-statement call to a helper / useCallback: binds the call's args to the helper's params, then
1503
+ * lowers the helper body here in the current env/state/ctx. A `return` in it leaves the helper, which becomes a
1504
+ * block.
479
1505
  *
480
1506
  * @param helperName The helper's name.
481
1507
  * @param helper The helper.
@@ -487,48 +1513,50 @@ function lowerTimer(expression, environment, state, context) {
487
1513
  * @returns The helper's body as statements.
488
1514
  */
489
1515
  function inlineHelperCall(helperName, helper, callArguments, environment, state, context) {
490
- // A helper already being inlined further up this call chain is recursive.
491
- context.inlining = context.inlining ?? new Set();
492
- if (context.inlining.has(helperName)) {
493
- throw aotError(`AOT: helper "${helperName}" is recursive — can't be inlined into a handler`, 'handlers are flattened to straight-line code, so a helper that calls itself (directly ' +
494
- 'or via another helper) has no base case to unroll. Move recursive logic out of the ' +
495
- 'handler, or precompute the value.');
496
- }
497
- // Bind each passed argument to its parameter as a local holding the argument's expression.
498
- const locals = new Map(environment.locals);
499
- helper.params.forEach((parameter, parameterIndex) => {
500
- if (parameter.type !== 'Identifier') {
501
- throw aotError(`AOT: helper "${helperName}" must take simple (identifier) params to be inlined`, 'a helper called from a handler must use plain positional params (e.g. `(a, b) => …`) ' +
502
- '— destructuring or default params in the signature are not supported.');
503
- }
504
- if (callArguments[parameterIndex]) {
505
- const argumentExpression = lowerSourcedWide(callArguments[parameterIndex], environment);
506
- locals.set(parameter.name, {
507
- slotKind: argumentExpression.slotKind,
508
- isBoolean: argumentExpression.isBoolean,
509
- isLiteral: argumentExpression.isLiteral,
510
- wide: argumentExpression.wide,
511
- source: argumentExpression.source,
512
- expression: argumentExpression.expression,
513
- });
514
- }
515
- });
516
1516
  // An expression body is a single statement.
517
1517
  const body = helper.body;
518
1518
  const statements = body.type === 'BlockStatement'
519
1519
  ? body.body
520
1520
  : [{ type: 'ExpressionStatement', expression: body }];
521
- // The body is spliced into the caller, so reject its `return`, even in an effect body where one is allowed.
522
- const outerAllowReturn = context.allowReturn;
523
- context.inlining.add(helperName);
524
- context.allowReturn = false;
1521
+ const { helperList, usedReturn } = context;
1522
+ context.helperList = statements;
1523
+ context.usedReturn = false;
525
1524
  try {
526
- return lowerStmts(statements, { ...environment, locals }, state, context);
1525
+ const lowered = lowerStmts(statements, helperEnvironment(helperName, helper, callArguments, environment), state, context);
1526
+ return context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered;
527
1527
  }
528
1528
  finally {
529
- context.allowReturn = outerAllowReturn;
530
- context.inlining.delete(helperName);
1529
+ context.helperList = helperList;
1530
+ context.usedReturn = usedReturn;
1531
+ }
1532
+ }
1533
+ /** The console methods a package can call, as Flow A has them. */
1534
+ const CONSOLE_METHODS = new Set(['log', 'warn', 'error']);
1535
+ /**
1536
+ * Whether a call is `console.log`, `console.warn` or `console.error`, on the global console: not a local, a state
1537
+ * or a constant of that name.
1538
+ *
1539
+ * @param call The call.
1540
+ * @param environment The expression environment.
1541
+ *
1542
+ * @returns True when it is.
1543
+ */
1544
+ function isConsoleCall(call, environment) {
1545
+ const { callee } = call;
1546
+ if (callee.type !== 'MemberExpression' ||
1547
+ callee.computed ||
1548
+ callee.object.type !== 'Identifier' ||
1549
+ callee.object.name !== 'console' ||
1550
+ callee.property.type !== 'Identifier' ||
1551
+ environment.locals.has('console') ||
1552
+ environment.state.has('console') ||
1553
+ 'console' in (environment.constants ?? {})) {
1554
+ return false;
1555
+ }
1556
+ if (!CONSOLE_METHODS.has(callee.property.name)) {
1557
+ throw aotError(`AOT: console.${callee.property.name} is not supported`, 'a package has console.log, console.warn and console.error, each one line in the host log.');
531
1558
  }
1559
+ return true;
532
1560
  }
533
1561
  /**
534
1562
  * Lowers one handler ExpressionStatement: a state setter, ref mutation, timer, updateVector, helper call, or
@@ -541,7 +1569,28 @@ function inlineHelperCall(helperName, helper, callArguments, environment, state,
541
1569
  *
542
1570
  * @returns The statements.
543
1571
  */
544
- function lowerHandlerExprImpl(expression, environment, state, context) {
1572
+ function lowerHandlerExprImpl(expression, handlerEnvironment, state, context) {
1573
+ const environment = handlerEnvironment.outsideRender
1574
+ ? handlerEnvironment
1575
+ : { ...handlerEnvironment, outsideRender: true };
1576
+ // `Sensors.setLed(on)`: a native method called for what it does.
1577
+ if (expression.type === 'CallExpression') {
1578
+ const nativeCallee = nativeCalleeOf(expression, environment);
1579
+ if (nativeCallee) {
1580
+ return [
1581
+ {
1582
+ kind: 'callNative',
1583
+ call: lowerNativeCall(expression, nativeCallee, environment),
1584
+ },
1585
+ ];
1586
+ }
1587
+ }
1588
+ // console.log / warn / error(…) → one line for the host's log.
1589
+ if (expression.type === 'CallExpression' &&
1590
+ isConsoleCall(expression, environment)) {
1591
+ const text = lowerLogText(expression.arguments, environment);
1592
+ return context.output.release ? [] : [{ kind: 'log', text }];
1593
+ }
545
1594
  // updateVector(ref, shapes, dirtyRect?) — imperative vector redraw (no update).
546
1595
  if (expression.type === 'CallExpression' &&
547
1596
  expression.callee.type === 'Identifier' &&
@@ -573,139 +1622,58 @@ function lowerHandlerExprImpl(expression, environment, state, context) {
573
1622
  },
574
1623
  ];
575
1624
  }
576
- // `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
577
- if (expression.type === 'AssignmentExpression') {
578
- const ref = refTarget(expression.left, environment);
579
- if (!ref) {
580
- throw new Error('AOT: the only assignment allowed in a handler is `ref.current = ...`');
581
- }
582
- // Lower the right side in the ref's width and check it fits; a 64-bit `%=` keeps its constant divisor.
583
- const refEnvironment = ref.slotKind === 'i64' ? { ...environment, math64: true } : environment;
584
- const loweredValue = lowerSource(expression.right, refEnvironment);
585
- const valueExpression = loweredValue.expression;
586
- const refHoldsTime = isTime(refType(ref));
587
- if (expression.operator === '/=' &&
588
- (refHoldsTime || isTime64(valueExpression))) {
589
- throw aotError('AOT: `/=` on a 64-bit time value is not supported', 'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.');
590
- }
591
- const wideModuloDivisor = expression.operator === '%=' &&
592
- (refHoldsTime || isTime64(valueExpression))
593
- ? constDivisor(expression.right, environment)
1625
+ // `x = …`, `x += …` and `x++` on a local, which must be a `let`.
1626
+ const assigned = expression.type === 'AssignmentExpression'
1627
+ ? expression.left
1628
+ : expression.type === 'UpdateExpression'
1629
+ ? expression.argument
594
1630
  : null;
595
- storeCheck(loweredValue, ref.slotKind, false, ref.kind === 'value' ? ref.widened : undefined, ref.slotName, `ref "${expression.left.object.name}"`, environment);
596
- // Lower whole-ref `+= -= *=`, float `/=` and float `%=` as the binary op to share its checked and float math.
597
- const isWholeRef = ref.slotKind === 'int' || ref.slotKind === 'i64';
598
- const binaryOperation = { '+=': '+', '-=': '-', '*=': '*' }[expression.operator];
599
- const isFloatModulo = expression.operator === '%=' &&
600
- (ref.slotKind === 'float' || valueExpression.type.kind === 'float');
601
- if ((isWholeRef &&
602
- (binaryOperation ||
603
- (expression.operator === '/=' &&
604
- valueExpression.type.kind === 'float'))) ||
605
- isFloatModulo) {
606
- const resultExpression = lowerExprWide({
607
- type: 'BinaryExpression',
608
- operator: binaryOperation ?? expression.operator.slice(0, -1),
609
- left: expression.left,
610
- right: expression.right,
611
- loc: expression.loc,
612
- }, refEnvironment);
1631
+ if (assigned?.type === 'Identifier') {
1632
+ const local = environment.locals.get(assigned.name);
1633
+ if (local) {
613
1634
  return [
614
- {
615
- kind: 'writeRef',
616
- ref,
617
- operator: '=',
618
- value: storeValue(resultExpression, ref.slotKind),
619
- },
1635
+ lowerLocalAssign(expression, assigned, local, environment),
620
1636
  ];
621
1637
  }
622
- // Whole-number `/=` and `%=` use the checked helpers for JS's answer, in 64 bits on a 64-bit ref that holds no
623
- // time; a constant divisor other than 0 or -1 needs no check.
624
- const isWholeValue = isIntSlot(valueExpression.type) ||
625
- (valueExpression.type.kind === 'int64' && !isTime64(valueExpression));
626
- const refBits = ref.slotKind === 'i64' ? 64 : 32;
627
- if (((ref.slotKind === 'int' && isIntSlot(valueExpression.type)) ||
628
- (ref.slotKind === 'i64' && !refHoldsTime && isWholeValue)) &&
629
- (expression.operator === '/=' || expression.operator === '%=')) {
630
- const staticDivisor = staticInt(expression.right, environment);
631
- if (expression.operator === '/=' &&
632
- (staticDivisor === null || staticDivisor === 0 || staticDivisor === -1)) {
633
- return [
634
- {
635
- kind: 'writeRef',
636
- ref,
637
- operator: '=',
638
- value: {
639
- kind: 'helper',
640
- helper: 'div',
641
- bits: refBits,
642
- callArguments: [refRead(ref), valueExpression],
643
- type: refType(ref),
644
- },
645
- },
646
- ];
647
- }
648
- if (expression.operator === '%=' &&
649
- (staticDivisor === 0 || staticDivisor === -1)) {
650
- return [{ kind: 'writeRef', ref, operator: '=', value: ZERO }];
651
- }
652
- if (expression.operator === '%=' && staticDivisor === null) {
653
- return [
654
- {
655
- kind: 'writeRef',
656
- ref,
657
- operator: '=',
658
- value: {
659
- kind: 'helper',
660
- helper: 'mod',
661
- bits: refBits,
662
- callArguments: [refRead(ref), valueExpression],
663
- type: refType(ref),
664
- },
665
- },
666
- ];
667
- }
1638
+ }
1639
+ // `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
1640
+ if (expression.type === 'AssignmentExpression') {
1641
+ const ref = refTarget(expression.left, environment);
1642
+ if (!ref) {
1643
+ throw new Error('AOT: a handler can only assign a `let` local or `ref.current`');
668
1644
  }
669
- // A 64-bit `%=` by 0 or ±1 stores 0: no remainder, JS's NaN as 0, and no overflow on INT64_MIN % -1.
670
- if (wideModuloDivisor === 0 ||
671
- wideModuloDivisor === 1 ||
672
- wideModuloDivisor === -1) {
673
- return [{ kind: 'writeRef', ref, operator: '=', value: ZERO }];
1645
+ // Lower the right side; the typing pass works out the write, once it knows the ref's width.
1646
+ const value = lowerSource(expression.right, storeEnvironment(environment, () => is64BitSlot(ref)));
1647
+ if (ref.kind === 'value' && ref.slotKind !== 'float') {
1648
+ recordStore(value.source, ref.slotName, ref, environment);
674
1649
  }
675
- // Everything else is a plain assignment or compound assignment.
676
- return [
677
- {
678
- kind: 'writeRef',
679
- ref,
680
- operator: expression.operator,
681
- value: expression.operator === '='
682
- ? storeValue(valueExpression, ref.slotKind)
683
- : valueExpression,
684
- },
685
- ];
1650
+ const statement = { kind: 'writeRef', ref };
1651
+ setLater(statement, ['operator', 'value'], () => typedRefWrite(expression, ref, value, environment));
1652
+ return [statement];
686
1653
  }
687
1654
  // `ref.current++` / `ref.current--`; a whole-number ref steps through the checked `+ 1` / `- 1`.
688
1655
  if (expression.type === 'UpdateExpression') {
689
1656
  const ref = refTarget(expression.argument, environment);
690
1657
  if (!ref) {
691
- throw new Error('AOT: the only ++/-- allowed in a handler is on `ref.current`');
1658
+ throw new Error('AOT: a handler can only use ++/-- on a `let` local or `ref.current`');
692
1659
  }
693
1660
  if (ref.slotKind === 'int' || ref.slotKind === 'i64') {
1661
+ const { operator } = expression;
694
1662
  return [
695
1663
  {
696
1664
  kind: 'writeRef',
697
1665
  ref,
698
1666
  operator: '=',
699
- value: {
1667
+ value: typedLater('number', () => ({
700
1668
  kind: 'helper',
701
- helper: expression.operator === '++' ? 'add' : 'sub',
1669
+ helper: operator === '++' ? 'add' : 'sub',
702
1670
  bits: ref.slotKind === 'i64' ? 64 : 32,
703
1671
  callArguments: [
704
1672
  refRead(ref),
705
1673
  { kind: 'number', value: 1, type: INT },
706
1674
  ],
707
1675
  type: refType(ref),
708
- },
1676
+ })),
709
1677
  },
710
1678
  ];
711
1679
  }
@@ -748,41 +1716,74 @@ function lowerHandlerExprImpl(expression, environment, state, context) {
748
1716
  if (!targetState) {
749
1717
  throw aotError(`AOT: "${expression.callee.name}" is not a known state setter`, `a handler can only call a setter from this component's own useState (e.g. setCount), ` +
750
1718
  `a ref write, updateVector(…), or Animated…start(). "${expression.callee.name}" isn't one ` +
751
- `of those — arbitrary functions (fetch, console.*, helpers) can't be lowered.`);
1719
+ `of those — arbitrary functions (fetch, helpers) can't be lowered.`);
752
1720
  }
753
1721
  context.stateChanged = true;
754
1722
  const setterArgument = expression.arguments[0];
1723
+ const setterCall = expression;
1724
+ // An object's updater and reducer read its fields as they are now. A scalar's parameter is marked itself.
1725
+ if (targetState.kind === 'record' &&
1726
+ (targetState.reducer || isFn(setterArgument))) {
1727
+ const slots = [...targetState.fields.values(), targetState.tag?.state];
1728
+ return readingLatest(lowerSetter(setterCall, targetState, environment, state, context), new Set(slots.filter(slot => slot !== undefined)));
1729
+ }
1730
+ return lowerSetter(setterCall, targetState, environment, state, context);
1731
+ }
1732
+ /**
1733
+ * Lowers a state setter's call: a dispatch, an updater, or the new value itself.
1734
+ *
1735
+ * @param expression The call.
1736
+ * @param targetState The state it sets.
1737
+ * @param environment The expression environment.
1738
+ * @param state The component's state table.
1739
+ * @param context The statement compiler's context.
1740
+ *
1741
+ * @returns The statements.
1742
+ */
1743
+ function lowerSetter(expression, targetState, environment, state, context) {
1744
+ const setterArgument = expression.arguments[0];
1745
+ // A dispatch runs the reducer. Its reads of the state are an updater's, so inside a loop only the list rule holds.
1746
+ if (targetState.reducer && !isReturnSet(expression)) {
1747
+ if (context.loops?.length) {
1748
+ checkLoopSetter(expression.callee.name, targetState, undefined, environment, context.loops);
1749
+ }
1750
+ return inlineReducer(expression.callee.name, targetState, targetState.reducer, setterArgument, environment, state, context);
1751
+ }
1752
+ if (context.loops?.length && !isReturnSet(expression)) {
1753
+ checkLoopSetter(expression.callee.name, targetState, setterArgument, environment, context.loops);
1754
+ }
1755
+ // An updater with a block body runs here, each `return next` setting the state.
1756
+ if (isFn(setterArgument) && setterArgument.body.type === 'BlockStatement') {
1757
+ return inlineUpdater(expression.callee.name, targetState, setterArgument, environment, state, context);
1758
+ }
755
1759
  if (targetState.kind === 'list') {
1760
+ // setItems(prev => …): the parameter names the list.
1761
+ if (isFn(setterArgument)) {
1762
+ const { itemName: previousName, body } = itemCallback(setterArgument, `${expression.callee.name}'s updater`);
1763
+ if (!previousName) {
1764
+ return lowerListOp(targetState, body, environment);
1765
+ }
1766
+ return lowerListOp(targetState, body, {
1767
+ ...environment,
1768
+ state: new Map(environment.state).set(previousName, targetState),
1769
+ }, previousName);
1770
+ }
756
1771
  return lowerListOp(targetState, setterArgument, environment);
757
1772
  }
1773
+ // An object setter writes each field; setP(prev => …) binds the parameter to the object.
1774
+ if (targetState.kind === 'record') {
1775
+ if (isFn(setterArgument)) {
1776
+ return lowerRecordSet(targetState, setterArgument.body, updaterEnvironment(targetState, setterArgument, environment), RECORD_LOWERING);
1777
+ }
1778
+ return lowerRecordSet(targetState, setterArgument, environment, RECORD_LOWERING);
1779
+ }
758
1780
  // A scalar setter takes either an updater function or the new value itself.
759
1781
  if (setterArgument &&
760
1782
  (setterArgument.type === 'ArrowFunctionExpression' ||
761
1783
  setterArgument.type === 'FunctionExpression')) {
762
- // setState(prev => expr): bind the param to the current value, typed as a read of it, and assign the result.
763
- const previousParameter = setterArgument.params[0]?.name;
764
- const locals = new Map(environment.locals);
765
- if (previousParameter) {
766
- locals.set(previousParameter, {
767
- slotKind: targetState.slotKind,
768
- isBoolean: targetState.isBoolean,
769
- ...(targetState.widened === 'number' ? { isLiteral: true } : {}),
770
- source: { kind: 'state', state: targetState, location: undefined },
771
- expression: {
772
- kind: 'state',
773
- state: targetState,
774
- type: stateType(targetState),
775
- },
776
- });
777
- }
778
- if (setterArgument.body.type === 'BlockStatement') {
779
- throw new Error('AOT: updater function must be a single expression (for now)');
780
- }
1784
+ // setState(prev => expr): the param reads the current value, and the result is assigned.
781
1785
  return [
782
- lowerScalarSet(targetState, setterArgument.body, {
783
- ...environment,
784
- locals,
785
- }),
1786
+ lowerScalarSet(targetState, setterArgument.body, updaterEnvironment(targetState, setterArgument, environment)),
786
1787
  ];
787
1788
  }
788
1789
  return [lowerScalarSet(targetState, setterArgument, environment)];
@@ -793,10 +1794,10 @@ const lowerHandlerExpression = withLoc(lowerHandlerExprImpl);
793
1794
  * Lowers a list of handler statements to the IR. This one-statement lowering runs event handlers, effect bodies
794
1795
  * (useEffect), timer callbacks, and inlined helper calls. Supports: `const x = expr` (a local, visible to later
795
1796
  * statements), `if (cond) {...} else {...}`, state setters (list setters included), ref writes, timers,
796
- * updateVector() and Animated.*(...).start(). `context` accumulates `stateChanged` (→ a trailing update)
797
- * and `usedReturn` (an early `return` was lowered, so the body needs a
798
- * function of its own). `context.allowReturn` and `context.bodyList` mark which body a `return` may exit and which
799
- * statement of it is the tail.
1797
+ * updateVector() and Animated.*(...).start(), `switch` (as an if/else chain) and `return`. `context` accumulates
1798
+ * `stateChanged` (→ a trailing update) and `usedReturn` (an early `return` was lowered, so the body or helper is a
1799
+ * block it leaves, or an effect's function of its own). `context.bodyList` and `context.helperList` mark the
1800
+ * statements whose tail `return` needs no jump.
800
1801
  *
801
1802
  * @param statements The statements.
802
1803
  * @param environment The expression environment.
@@ -805,19 +1806,88 @@ const lowerHandlerExpression = withLoc(lowerHandlerExprImpl);
805
1806
  *
806
1807
  * @returns The lowered statements.
807
1808
  */
808
- export function lowerStmts(statements, environment, state, context) {
1809
+ export function lowerStmts(statements, bodyEnvironment, state, context) {
1810
+ let environment = bodyEnvironment.outsideRender
1811
+ ? bodyEnvironment
1812
+ : { ...bodyEnvironment, outsideRender: true };
809
1813
  const lowered = [];
810
- // What each statement lowers to is marked with where it is, once the next one starts.
1814
+ // What each statement lowers to is marked with where it is, once the next one starts, after the values a helper
1815
+ // loops for that it reads.
811
1816
  let from = 0;
812
1817
  let location;
813
- for (let statementIndex = 0; statementIndex < statements.length; statementIndex++) {
1818
+ let before;
1819
+ const settle = () => {
1820
+ if (before?.statements.length)
1821
+ lowered.splice(from, 0, ...before.statements);
814
1822
  markLoc(lowered, from, location);
1823
+ };
1824
+ for (let statementIndex = 0; statementIndex < statements.length; statementIndex++) {
1825
+ settle();
815
1826
  const statement = statements[statementIndex];
816
1827
  from = lowered.length;
817
1828
  location = startOf(statement);
1829
+ before = { statements: [], state, output: context.output };
1830
+ environment = { ...environment, before };
818
1831
  // `const x = …` declares a local that the statements after it can read.
819
1832
  if (statement.type === 'VariableDeclaration') {
820
- for (const declarator of statement.declarations) {
1833
+ // An object's declaration expands into a local per field, put back in the queue.
1834
+ const queue = [
1835
+ ...statement.declarations,
1836
+ ];
1837
+ // Each initializer's looping values go just before it, as a later one may read an earlier local.
1838
+ const sink = before;
1839
+ let declaratorFrom = lowered.length;
1840
+ const nextDeclarator = () => {
1841
+ lowered.splice(declaratorFrom, 0, ...sink.statements);
1842
+ sink.statements = [];
1843
+ declaratorFrom = lowered.length;
1844
+ };
1845
+ while (queue.length) {
1846
+ nextDeclarator();
1847
+ const entry = queue.shift();
1848
+ if (!('type' in entry)) {
1849
+ const locals = new Map(environment.locals);
1850
+ locals.delete(entry.name);
1851
+ environment = {
1852
+ ...environment,
1853
+ locals,
1854
+ constants: {
1855
+ ...environment.constants,
1856
+ [entry.name]: boundObjectOf(entry, environment.locals),
1857
+ },
1858
+ };
1859
+ continue;
1860
+ }
1861
+ const declarator = entry;
1862
+ // A native method's record: its values kept in locals, then declared as an object of them, or a field.
1863
+ const recordRoot = nativeRecordRootOf(declarator.init, environment);
1864
+ if (recordRoot) {
1865
+ const kept = keepNativeRecord(recordRoot.call, recordRoot.callee, environment);
1866
+ lowered.push(kept.statement);
1867
+ environment = kept.environment;
1868
+ queue.unshift({
1869
+ ...declarator,
1870
+ init: recordRoot.replaced({
1871
+ type: 'Identifier',
1872
+ name: kept.name,
1873
+ }),
1874
+ });
1875
+ continue;
1876
+ }
1877
+ const expanded = expandObjectDeclarator(declarator, environment);
1878
+ if (expanded) {
1879
+ if (statement.kind !== 'const') {
1880
+ throw aotError('AOT: an object in a handler must be a `const`', 'build a new object instead of changing this one, and declare it with const.');
1881
+ }
1882
+ queue.unshift(...expanded.entries);
1883
+ if (expanded.locals.size) {
1884
+ environment = {
1885
+ ...environment,
1886
+ locals: new Map([...environment.locals, ...expanded.locals]),
1887
+ };
1888
+ }
1889
+ continue;
1890
+ }
821
1891
  if (declarator.id.type !== 'Identifier') {
822
1892
  throw new Error('AOT: destructuring a handler local is not supported');
823
1893
  }
@@ -835,11 +1905,28 @@ export function lowerStmts(statements, environment, state, context) {
835
1905
  };
836
1906
  continue;
837
1907
  }
838
- // A dep-driven effect's cleanup outlives the call, so the body's locals become slots.
1908
+ // `const parts = text.split(',')` fills a list of the handler's own, read as `parts[i]` and `parts.length`.
1909
+ const split = handlerSplitList(declarator.id.name, declarator.init, statement.kind, environment);
1910
+ if (split) {
1911
+ lowered.push(...split.statements);
1912
+ const locals = new Map(environment.locals);
1913
+ locals.delete(declarator.id.name);
1914
+ environment = {
1915
+ ...environment,
1916
+ locals,
1917
+ state: new Map(environment.state).set(declarator.id.name, split.list),
1918
+ };
1919
+ continue;
1920
+ }
1921
+ // A dep-driven effect's cleanup outlives the call, so the body's locals become slots. A `let`, and a local
1922
+ // that hides an outer one, has a name of its own, so the two keep apart, string buffers too.
839
1923
  const isHoisted = Boolean(context.hoist && statements === context.bodyList);
1924
+ const isLet = statement.kind !== 'const';
840
1925
  const localName = isHoisted
841
1926
  ? `${context.hoist.prefix}${declarator.id.name}`
842
- : `local_${declarator.id.name}`;
1927
+ : isLet || environment.locals.has(declarator.id.name)
1928
+ ? `local_${declarator.id.name}@${declarator.start ?? 0}`
1929
+ : `local_${declarator.id.name}`;
843
1930
  // `const id = setInterval/setTimeout(…)` is an int timer-id local, so a later clearInterval(id) resolves.
844
1931
  if (declarator.init.type === 'CallExpression' &&
845
1932
  declarator.init.callee.type === 'Identifier' &&
@@ -867,12 +1954,25 @@ export function lowerStmts(statements, environment, state, context) {
867
1954
  };
868
1955
  continue;
869
1956
  }
870
- // Any other initializer must lower to a number, a boolean or a string.
871
- const { source: initialSource, expression: initialExpression } = lowerSource(declarator.init, environment);
872
- if (initialExpression.type.kind === 'string') {
873
- if (initialExpression.kind === 'string') {
874
- checkConstantFits({ parts: [{ kind: 'literal', text: initialExpression.value }] }, `local "${declarator.id.name}"`, environment);
1957
+ // Any other initializer must lower to a number, a boolean or a string. A built string is text.
1958
+ const text = buildsText(declarator.init, environment)
1959
+ ? lowerText(declarator.init, environment)
1960
+ : undefined;
1961
+ const initial = text
1962
+ ? {
1963
+ source: undefined,
1964
+ expression: { kind: 'string', value: '', type: STRING },
875
1965
  }
1966
+ : lowerSource(declarator.init, environment);
1967
+ const { source: initialSource, expression: initialExpression } = initial;
1968
+ const localId = declarator.id.name;
1969
+ const shape = shapeOf(initialExpression);
1970
+ if (shape === 'string') {
1971
+ whenTyped(() => {
1972
+ if (initialExpression.kind === 'string') {
1973
+ checkConstantFits({ parts: [{ kind: 'literal', text: initialExpression.value }] }, `local "${localId}"`);
1974
+ }
1975
+ });
876
1976
  // Copy into a buffer of its own; aliasing a state slot would hide a self-read like `setLabel(t + '!')`.
877
1977
  if (isHoisted) {
878
1978
  context.hoist.declarations.push({
@@ -882,50 +1982,130 @@ export function lowerStmts(statements, environment, state, context) {
882
1982
  });
883
1983
  }
884
1984
  }
885
- else {
886
- const slot = slotOf(initialExpression.type);
887
- if (slot !== 'int' && slot !== 'float' && slot !== 'i64') {
888
- throw aotError('AOT: a handler local must hold a number, a boolean or a string', 'bind the value itself — e.g. `const id = item.id` — rather than a list item or a node ref.');
889
- }
890
- if (isHoisted) {
891
- context.hoist.declarations.push({
892
- kind: 'local',
1985
+ else if (shape !== 'number' && shape !== 'bool') {
1986
+ throw aotError('AOT: a handler local must hold a number, a boolean or a string', 'bind the value itself — e.g. `const id = item.id` — rather than a list item or a node ref.');
1987
+ }
1988
+ // A whole-number `let` set to a fraction or a timestamp later holds one from the start. Later statements
1989
+ // read the name as the local; a `let` is read from where it is kept, whatever set it last.
1990
+ const letKey = `let@${declarator.id.name}@${declarator.start ?? 0}`;
1991
+ const widthOf = () => isLet && initialExpression.type.kind === 'int'
1992
+ ? environment.wide.get(letKey)
1993
+ : undefined;
1994
+ const bare = !isLet && initialSource
1995
+ ? bareLocalOf({
1996
+ source: initialSource,
1997
+ expression: initialExpression,
1998
+ })
1999
+ : null;
2000
+ const local = bare
2001
+ ? copyLocal(bare, { name: localName, source: initialSource })
2002
+ : holdLater(isLet
2003
+ ? {
893
2004
  name: localName,
894
- slotKind: slot,
895
- });
896
- }
2005
+ assignable: letKey,
2006
+ declared: initialSource,
2007
+ }
2008
+ : { name: localName, source: initialSource }, shape, () => {
2009
+ const width = widthOf();
2010
+ const held = width
2011
+ ? width === 'float'
2012
+ ? { slotKind: 'float' }
2013
+ : {
2014
+ slotKind: 'i64',
2015
+ ...(width === 'number' ? { isLiteral: true } : {}),
2016
+ }
2017
+ : slotValueOf(initialExpression);
2018
+ return isLet
2019
+ ? {
2020
+ slotKind: held.slotKind,
2021
+ ...(held.isBoolean ? { isBoolean: true } : {}),
2022
+ ...(held.isLiteral ? { isLiteral: true } : {}),
2023
+ ...(held.wide ? { wide: true } : {}),
2024
+ }
2025
+ : held;
2026
+ });
2027
+ if (isHoisted && shape !== 'string') {
2028
+ const declaration = { kind: 'local', name: localName };
2029
+ context.hoist.declarations.push(declaration);
2030
+ setLater(declaration, ['slotKind'], () => ({
2031
+ slotKind: local.slotKind,
2032
+ }));
897
2033
  }
898
- lowered.push({
2034
+ const declare = {
899
2035
  kind: 'declareLocal',
900
2036
  name: localName,
901
2037
  initializer: initialExpression,
2038
+ ...(text ? { text } : {}),
902
2039
  isHoisted,
903
- stringCapacity: environment.caps.listStrCap,
904
- });
905
- // Later statements read the name as the local.
2040
+ };
2041
+ if (isLet && shape === 'number') {
2042
+ setLater(declare, ['widenedTo'], () => {
2043
+ const width = widthOf();
2044
+ const widenedTo = !width
2045
+ ? undefined
2046
+ : width === 'float'
2047
+ ? 'float'
2048
+ : 'int64';
2049
+ return { widenedTo };
2050
+ });
2051
+ }
2052
+ lowered.push(declare);
906
2053
  environment = {
907
2054
  ...environment,
908
- locals: new Map(environment.locals).set(declarator.id.name, {
909
- ...slotValueOf(initialExpression),
910
- name: localName,
911
- source: initialSource,
912
- }),
2055
+ locals: new Map(environment.locals).set(declarator.id.name, local),
913
2056
  };
914
2057
  }
2058
+ nextDeclarator();
915
2059
  continue;
916
2060
  }
917
- // A tail `return` is the cleanup, dropped on mount and armed if dep-driven; an earlier one is a guard.
918
- if (statement.type === 'ReturnStatement') {
919
- if (!context.allowReturn) {
920
- const error = aotError('AOT: `return` is only supported inside a useEffect body', 'a handler, timer, animation or inlined-helper body cannot return early — flatten the logic into if/else.');
921
- if (statement.loc) {
922
- error.aotLoc = statement.loc.start;
923
- }
924
- throw error;
2061
+ // `switch` runs as an if/else chain; a bare block lowers in place, its locals its own.
2062
+ if (statement.type === 'SwitchStatement') {
2063
+ lowered.push(...lowerStmts([switchAsIf(statement)], environment, state, context));
2064
+ continue;
2065
+ }
2066
+ if (statement.type === 'BlockStatement') {
2067
+ lowered.push(...lowerStmts(statement.body, environment, state, context));
2068
+ continue;
2069
+ }
2070
+ // `for` counts to a bound the compiler works out, and `for…of` visits a list's rows.
2071
+ if (statement.type === 'ForStatement') {
2072
+ lowered.push(...lowerFor(statement, environment, state, context, lowerStmts));
2073
+ continue;
2074
+ }
2075
+ if (statement.type === 'ForOfStatement') {
2076
+ lowered.push(...lowerForOf(statement, environment, state, context, lowerStmts));
2077
+ continue;
2078
+ }
2079
+ if (statement.type === 'BreakStatement' ||
2080
+ statement.type === 'ContinueStatement') {
2081
+ const word = statement.type === 'BreakStatement' ? 'break' : 'continue';
2082
+ if (statement.label) {
2083
+ throw located(aotError(`AOT: a labeled \`${word}\` is not supported`, 'leave the inner loop with a plain break and test a let after it, or move the loops into a helper ' +
2084
+ 'and return from it.'), statement);
2085
+ }
2086
+ if (!context.loops?.length) {
2087
+ throw located(aotError(`AOT: a \`${word}\` must be inside a loop`), statement);
925
2088
  }
926
- const isTail = statements === context.bodyList &&
927
- statementIndex === statements.length - 1;
928
- if (context.dependencyDriven && isFn(statement.argument) && !isTail) {
2089
+ lowered.push({ kind: word });
2090
+ continue;
2091
+ }
2092
+ if (statement.type === 'LabeledStatement') {
2093
+ throw located(aotError('AOT: a labeled statement is not supported', 'leave the inner loop with a plain break and test a let after it, or move the loops into a helper ' +
2094
+ 'and return from it.'), statement);
2095
+ }
2096
+ if (statement.type === 'WhileStatement' ||
2097
+ statement.type === 'DoWhileStatement' ||
2098
+ statement.type === 'ForInStatement') {
2099
+ throw located(aotError(`AOT: a ${statement.type === 'ForInStatement' ? 'for…in' : 'while'} loop is not supported`, "a loop needs a bound the compiler can count. Write a for loop from a constant or a list's length to " +
2100
+ 'another, or for (const item of items), and break out of it early.'), statement);
2101
+ }
2102
+ // An effect body's tail `return` is the cleanup, dropped on mount and armed if dep-driven; any other `return`
2103
+ // leaves the body or helper, the value it gives unused.
2104
+ if (statement.type === 'ReturnStatement') {
2105
+ const argument = statement.argument;
2106
+ const isLast = statementIndex === statements.length - 1;
2107
+ const isBodyTail = isLast && statements === context.bodyList;
2108
+ if (context.dependencyDriven && isFn(argument) && !isBodyTail) {
929
2109
  const error = aotError('AOT: a useEffect cleanup must be the last statement of the effect body', 'a cleanup returned from inside an `if` would be dropped. Return `undefined` from the ' +
930
2110
  'guard and put the single `return () => …` at the end of the body.');
931
2111
  if (statement.loc) {
@@ -933,11 +2113,22 @@ export function lowerStmts(statements, environment, state, context) {
933
2113
  }
934
2114
  throw error;
935
2115
  }
936
- if (isTail) {
937
- if (context.cleanup && isFn(statement.argument)) {
938
- context.cleanup.emit(statement.argument, environment);
939
- lowered.push({ kind: 'armCleanup', flag: context.cleanup.armed });
940
- }
2116
+ if (isBodyTail && context.cleanup && isFn(argument)) {
2117
+ context.cleanup.emit(argument, environment);
2118
+ lowered.push({ kind: 'armCleanup', flag: context.cleanup.armed });
2119
+ continue;
2120
+ }
2121
+ // A body that works out a value keeps what it returns; elsewhere `return setX(…)` still sets it.
2122
+ if (context.returnsValue && argument) {
2123
+ lowered.push(...context.returnsValue(argument, environment));
2124
+ }
2125
+ else if (argument?.type === 'CallExpression' ||
2126
+ argument?.type === 'AssignmentExpression' ||
2127
+ argument?.type === 'UpdateExpression') {
2128
+ lowered.push(...lowerHandlerExpression(argument, environment, state, context));
2129
+ }
2130
+ if (isLast &&
2131
+ (statements === context.bodyList || statements === context.helperList)) {
941
2132
  continue;
942
2133
  }
943
2134
  context.usedReturn = true;
@@ -947,25 +2138,94 @@ export function lowerStmts(statements, environment, state, context) {
947
2138
  // `if (…) { … } else { … }` lowers each branch in order: the test, then the consequent, then the alternate.
948
2139
  if (statement.type === 'IfStatement') {
949
2140
  const test = lowerExprWide(statement.test, environment);
950
- const consequent = lowerStmts(blockList(statement.consequent), environment, state, context);
2141
+ // A test on a tagged object's tag narrows the fields each branch can read.
2142
+ const narrowing = narrowOn(statement.test, environment);
2143
+ const consequentStatements = statementsOf(statement.consequent);
2144
+ const alternateStatements = statement.alternate
2145
+ ? statementsOf(statement.alternate)
2146
+ : [];
2147
+ const consequent = lowerStmts(consequentStatements, narrowed(environment, narrowing.whenTrue), state, context);
951
2148
  const alternate = statement.alternate
952
- ? lowerStmts(blockList(statement.alternate), environment, state, context)
2149
+ ? lowerStmts(alternateStatements, narrowed(environment, narrowing.whenFalse), state, context)
953
2150
  : null;
954
2151
  lowered.push({ kind: 'if', test, consequent, alternate });
2152
+ // The statements after a branch that returns, breaks or continues read what the other branch's test leaves.
2153
+ const inLoop = Boolean(context.loops?.length);
2154
+ if (exits(consequentStatements, inLoop)) {
2155
+ environment = narrowed(environment, narrowing.whenFalse);
2156
+ }
2157
+ else if (exits(alternateStatements, inLoop)) {
2158
+ environment = narrowed(environment, narrowing.whenTrue);
2159
+ }
955
2160
  continue;
956
2161
  }
957
2162
  // Anything else must be an expression statement: a setter call, a ref write, a timer, and so on.
958
2163
  if (statement.type !== 'ExpressionStatement') {
959
- throw aotError(`AOT: unsupported statement "${statement.type}" in event handler`, 'a handler supports only `const x = …` locals, `if (…) { … } else { … }`, and ' +
960
- 'expression statements (setters / ref writes / updateVector / Animated…start). Loops ' +
961
- '(for/while), switch and try/catch are not lowered — precompute values or flatten the ' +
962
- 'logic into if/else.');
2164
+ throw aotError(`AOT: unsupported statement "${statement.type}" in event handler`, 'a handler supports only `const` and `let` locals, `if`, `switch`, `for`, `for…of`, `return`, and ' +
2165
+ 'expression statements (setters / ref and local writes / updateVector / Animated…start). ' +
2166
+ 'try/catch is not lowered.');
2167
+ }
2168
+ // A native method's record given straight to a call that takes one, setFix(Gps.fix()), or a field of it,
2169
+ // setLat(Gps.fix().lat): kept first, then passed by its name.
2170
+ let expression = statement.expression;
2171
+ const keptRoot = (argument, index) => {
2172
+ const recordRoot = nativeRecordRootOf(argument, environment);
2173
+ return recordRoot &&
2174
+ (recordRoot.call !== argument ||
2175
+ takesRecord(expression, index, environment, state))
2176
+ ? recordRoot
2177
+ : null;
2178
+ };
2179
+ if (expression.type === 'CallExpression' &&
2180
+ expression.arguments.some(keptRoot)) {
2181
+ const callArguments = expression.arguments.map((argument, index) => {
2182
+ const recordRoot = keptRoot(argument, index);
2183
+ if (!recordRoot)
2184
+ return argument;
2185
+ const kept = keepNativeRecord(recordRoot.call, recordRoot.callee, environment);
2186
+ lowered.push(kept.statement);
2187
+ environment = kept.environment;
2188
+ return recordRoot.replaced({
2189
+ type: 'Identifier',
2190
+ name: kept.name,
2191
+ });
2192
+ });
2193
+ expression = { ...expression, arguments: callArguments };
963
2194
  }
964
- lowered.push(...lowerHandlerExpression(statement.expression, environment, state, context));
2195
+ lowered.push(...lowerHandlerExpression(expression, environment, state, context));
965
2196
  }
966
- markLoc(lowered, from, location);
2197
+ settle();
967
2198
  return lowered;
968
2199
  }
2200
+ /**
2201
+ * An error located at a statement.
2202
+ *
2203
+ * @param error The error.
2204
+ * @param statement The statement.
2205
+ *
2206
+ * @returns The error.
2207
+ */
2208
+ function located(error, statement) {
2209
+ if (statement.loc)
2210
+ error.aotLoc = statement.loc.start;
2211
+ return error;
2212
+ }
2213
+ /**
2214
+ * Lowers a body of its own: a handler's, a timer's, an animation completion's or an effect cleanup's. A `return` in
2215
+ * it leaves the block it becomes.
2216
+ *
2217
+ * @param statements The body's statements.
2218
+ * @param environment The expression environment.
2219
+ * @param state The component's state table.
2220
+ * @param context The statement compiler's context, new for this body.
2221
+ *
2222
+ * @returns The lowered statements.
2223
+ */
2224
+ export function lowerBody(statements, environment, state, context) {
2225
+ context.bodyList = statements;
2226
+ const lowered = lowerStmts(statements, environment, state, context);
2227
+ return keepingStates(context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered, context.output);
2228
+ }
969
2229
  /**
970
2230
  * Where a statement starts. An expression body made into a statement has no location of its own.
971
2231
  *
@@ -996,9 +2256,9 @@ function markLoc(lowered, from, location) {
996
2256
  * Lowers a useEffect (App or child). Two shapes:
997
2257
  * - `useEffect(fn, [])` — MOUNT-ONCE: body runs after the initial the update (in the build).
998
2258
  * - `useEffect(fn, [dep…])` — DEP-DRIVEN: body becomes a function of its own; runs once at mount,
999
- * then again from the update whenever a SCALAR dep changes (compared against a stored prev). The body is
1000
- * compiled WITHOUT a trailing update — it runs INSIDE an update / at mount, so re-applying state it
1001
- * sets happens on the next update (one-frame), and it can never re-enter an update (no infinite loop).
2259
+ * then again after an update whenever a SCALAR dep changes (compared against a stored prev). It runs after
2260
+ * the update pass, and one that set state asks for another pass, which shows it; an effect that keeps changing
2261
+ * its deps stops the app at the runtime's pass limit, where React reports an update loop.
1002
2262
  * A dep-driven `return () => …` becomes `effect_N_cleanup()`, run at the top of the next re-run.
1003
2263
  *
1004
2264
  * @param effect The effect.
@@ -1019,10 +2279,9 @@ export function lowerEffect(effect, environment, state, output) {
1019
2279
  const context = {
1020
2280
  stateChanged: false,
1021
2281
  output,
1022
- allowReturn: true,
1023
2282
  bodyList: statements,
1024
2283
  };
1025
- const lowered = lowerStmts(statements, environment, state, context);
2284
+ const lowered = keepingStates(lowerStmts(statements, environment, state, context), output);
1026
2285
  if (!context.usedReturn) {
1027
2286
  output.mountEffects.push({
1028
2287
  kind: 'inline',
@@ -1049,8 +2308,12 @@ export function lowerEffect(effect, environment, state, output) {
1049
2308
  if (!dependencyNode) {
1050
2309
  throw aotError('AOT: a useEffect dependency must be an expression');
1051
2310
  }
2311
+ if (objectTreeOf(dependencyNode, environment)) {
2312
+ throw aotError('AOT: a useEffect dependency on a whole object', 'depend on the fields the effect reads: [p.x, p.y].');
2313
+ }
1052
2314
  const dependencyExpression = lowerExprWide(dependencyNode, environment);
1053
- if (!['int', 'float', 'i64', 'string'].includes(slotValueOf(dependencyExpression).slotKind)) {
2315
+ const dependencyShape = shapeOf(dependencyExpression);
2316
+ if (dependencyShape === 'struct' || dependencyShape === 'node') {
1054
2317
  throw aotError('AOT: useEffect dependencies must be scalar (number / bool / string)', 'depend on scalar state values; object/array dependencies are not yet supported.');
1055
2318
  }
1056
2319
  return dependencyExpression;
@@ -1068,7 +2331,6 @@ export function lowerEffect(effect, environment, state, output) {
1068
2331
  const context = {
1069
2332
  stateChanged: false,
1070
2333
  output,
1071
- allowReturn: true,
1072
2334
  bodyList: statements,
1073
2335
  dependencyDriven: true,
1074
2336
  };
@@ -1089,7 +2351,7 @@ export function lowerEffect(effect, environment, state, output) {
1089
2351
  stateChanged: false,
1090
2352
  output,
1091
2353
  };
1092
- dependencyEffect.cleanup = lowerStmts(cleanupStatements, cleanupEnvironment, state, cleanupContext);
2354
+ dependencyEffect.cleanup = lowerBody(cleanupStatements, cleanupEnvironment, state, cleanupContext);
1093
2355
  output.effectFunctions.push({
1094
2356
  kind: 'cleanup',
1095
2357
  effect: dependencyEffect,
@@ -1099,13 +2361,147 @@ export function lowerEffect(effect, environment, state, output) {
1099
2361
  output.effectDeclarations.push({ kind: 'armed', effect: dependencyEffect });
1100
2362
  }
1101
2363
  // The effect function runs the last run's cleanup first, if that run armed it, then the body.
1102
- dependencyEffect.body = lowerStmts(statements, environment, state, context);
2364
+ dependencyEffect.body = keepingStates(lowerStmts(statements, environment, state, context), output);
1103
2365
  output.effectFunctions.push({ kind: 'effect', effect: dependencyEffect });
1104
2366
  // A copy of each dep, taken at mount; the update re-runs the effect when one no longer matches its copy.
1105
2367
  output.effectDeclarations.push({ kind: 'deps', effect: dependencyEffect });
1106
2368
  output.mountEffects.push({ kind: 'depEffect', effect: dependencyEffect });
1107
2369
  output.dependencyEffects.push(dependencyEffect);
1108
2370
  }
2371
+ /**
2372
+ * The native call that returns a record at the root of an expression: the call itself, or the record a field read
2373
+ * starts from, `Gps.fix().place.lat`.
2374
+ *
2375
+ * @param node The expression.
2376
+ * @param environment The expression environment.
2377
+ *
2378
+ * @returns The call and its callee, and the expression with the call replaced by another; or null.
2379
+ */
2380
+ function nativeRecordRootOf(node, environment) {
2381
+ if (node?.type === 'MemberExpression') {
2382
+ const root = nativeRecordRootOf(node.object, environment);
2383
+ return (root && {
2384
+ ...root,
2385
+ replaced: by => ({ ...node, object: root.replaced(by) }),
2386
+ });
2387
+ }
2388
+ const callee = nativeRecordCallOf(node, environment);
2389
+ return (callee && {
2390
+ call: node,
2391
+ callee,
2392
+ replaced: by => by,
2393
+ });
2394
+ }
2395
+ /**
2396
+ * Whether a call takes a record as one of its arguments: an object state's setter, or a native method's record
2397
+ * parameter.
2398
+ *
2399
+ * @param call The call.
2400
+ * @param index The argument's position.
2401
+ * @param environment The expression environment.
2402
+ * @param state The component's state table.
2403
+ *
2404
+ * @returns True when it does.
2405
+ */
2406
+ function takesRecord(call, index, environment, state) {
2407
+ if (call.callee.type === 'Identifier' &&
2408
+ state.bySetter.get(call.callee.name)?.kind === 'record') {
2409
+ return true;
2410
+ }
2411
+ const callee = nativeCalleeOf(call, environment);
2412
+ const member = callee?.module.members.get(callee.method);
2413
+ return member?.kind === 'method' && typeof member.params[index] === 'object';
2414
+ }
2415
+ /**
2416
+ * Calls a native method that returns a record, keeping its values in locals, and binds the record to a name no JS
2417
+ * binding has, as an object of them.
2418
+ *
2419
+ * @param node The call.
2420
+ * @param callee Its module, method and record (see nativeRecordCallOf).
2421
+ * @param environment The expression environment.
2422
+ *
2423
+ * @returns The call, the name, and the environment that binds it.
2424
+ */
2425
+ function keepNativeRecord(node, callee, environment) {
2426
+ const call = lowerNativeCall(node, callee, environment);
2427
+ const name = `#record${keptRecords++}`;
2428
+ const results = call.import.results.map((_, index) => `${name}_${index}`);
2429
+ const tree = recordTreeOf(callee.record, (index, type) => new RuntimeLeaf({ name: results[index], ...VALUE_SLOTS[type] }));
2430
+ return {
2431
+ statement: { kind: 'callNative', call, results },
2432
+ name,
2433
+ environment: {
2434
+ ...environment,
2435
+ constants: { ...environment.constants, [name]: tree },
2436
+ },
2437
+ };
2438
+ }
2439
+ /**
2440
+ * Lowers a `useNativeEvent(Module, 'event', handler)` to a handler the runtime runs with the event's values. The
2441
+ * handler does nothing while its component isn't mounted: the conditions it is built under, read as it runs.
2442
+ *
2443
+ * @param call The call.
2444
+ * @param environment The component's expression environment.
2445
+ * @param state The component's state table.
2446
+ * @param output Everything emitted so far; the handler is added to it.
2447
+ */
2448
+ export function lowerNativeEvent(call, environment, state, output) {
2449
+ const { event, values: declared, handler } = nativeEventOf(call, environment);
2450
+ const index = output.nativeEventHandlers.length;
2451
+ // Each value is a register the handler is entered with, read by a name no JS binding can have. A record's fields
2452
+ // are values of their own, and the record is bound as an object of them; destructuring one declares its fields.
2453
+ const values = event.params.map((_, position) => `#native${index}_${position}`);
2454
+ const locals = new Map(environment.locals);
2455
+ const constants = { ...environment.constants };
2456
+ const destructured = [];
2457
+ let first = 0;
2458
+ handler.params.forEach((parameter, position) => {
2459
+ const type = declared[position];
2460
+ const from = first;
2461
+ first += valueCount(type);
2462
+ if (typeof type === 'string') {
2463
+ locals.set(parameter.name, {
2464
+ name: values[from],
2465
+ ...VALUE_SLOTS[type],
2466
+ });
2467
+ return;
2468
+ }
2469
+ const name = parameter.type === 'Identifier'
2470
+ ? parameter.name
2471
+ : `#value${index}_${position}`;
2472
+ locals.delete(name);
2473
+ constants[name] = recordTreeOf(type, (leaf, leafType) => new RuntimeLeaf({ name: values[leaf], ...VALUE_SLOTS[leafType] }), from);
2474
+ if (parameter.type === 'ObjectPattern') {
2475
+ destructured.push({
2476
+ type: 'VariableDeclaration',
2477
+ kind: 'const',
2478
+ declarations: [
2479
+ {
2480
+ type: 'VariableDeclarator',
2481
+ id: parameter,
2482
+ init: { type: 'Identifier', name },
2483
+ },
2484
+ ],
2485
+ });
2486
+ }
2487
+ });
2488
+ const body = handler.body;
2489
+ const statements = [
2490
+ ...destructured,
2491
+ ...(body.type === 'BlockStatement'
2492
+ ? body.body
2493
+ : [{ type: 'ExpressionStatement', expression: body }]),
2494
+ ];
2495
+ const context = { stateChanged: false, output };
2496
+ const lowered = lowerBody(statements, { ...environment, locals, constants }, state, context);
2497
+ output.nativeEventHandlers.push({
2498
+ name: `native_event_${index}`,
2499
+ event,
2500
+ values,
2501
+ mounted: environment.mounted ?? null,
2502
+ callback: { body: lowered, updatesState: context.stateChanged },
2503
+ });
2504
+ }
1109
2505
  /**
1110
2506
  * Lowers an event handler to a callback. Its first parameter is the event, whose touch fields read
1111
2507
  * EREventData; a PanResponder callback's second is RN's gestureState (see lowerGestureField).
@@ -1145,7 +2541,7 @@ export function lowerHandler(functionNode, environment, state, output, pan = nul
1145
2541
  // The body re-applies state-dependent props once at its end if it set state.
1146
2542
  const context = { stateChanged: false, output };
1147
2543
  return {
1148
- body: lowerStmts(statements, handlerEnvironment, state, context),
2544
+ body: lowerBody(statements, handlerEnvironment, state, context),
1149
2545
  updatesState: context.stateChanged,
1150
2546
  };
1151
2547
  }
@@ -1190,7 +2586,7 @@ export function lowerValueHandler(functionNode, environment, state, output, slot
1190
2586
  ? body.body
1191
2587
  : [{ type: 'ExpressionStatement', expression: body }];
1192
2588
  return {
1193
- body: lowerStmts(statements, { ...environment, locals }, state, context),
2589
+ body: lowerBody(statements, { ...environment, locals }, state, context),
1194
2590
  updatesState: context.stateChanged,
1195
2591
  };
1196
2592
  }