embedded-react 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -19,17 +19,32 @@
19
19
  import { checkNumber } from './check.mjs';
20
20
  import { parse } from '@babel/parser';
21
21
  import { readFileSync, existsSync } from 'node:fs';
22
- import { resolve } from 'node:path';
23
- import { aotError } from './diagnostics.mjs';
22
+ import { posix, resolve } from 'node:path';
23
+ import { aotError, locateError } from './diagnostics.mjs';
24
24
  import { mergeBranchElements } from './branch-merge.mjs';
25
- import { bootCheckpoint, foldBoot, isBoot, nameBootValues, screenBinding, } from './boot.mjs';
26
- import { evalStaticOrThrow, evalStatic, setBinding, withUndefined, } from './static-eval.mjs';
27
- import { cConstant, cTypeOfValue } from './c-syntax.mjs';
25
+ import { inferItemStruct } from './list-items.mjs';
26
+ import { flattenTree, isObjectTree } from './records.mjs';
27
+ import { recordShapesOf, returnedObjects, writtenObjects, } from './record-shapes.mjs';
28
+ import { stateLocal, tagText, taggedTreeOf } from './tagged-records.mjs';
29
+ import { patternNames } from './updaters.mjs';
30
+ import { splitCallOf } from './list-split.mjs';
31
+ import { bootCheckpoint, bootSlotOf, buildValueOf, foldBoot, isBoot, isContainer, nameBootValues, PANEL_KEY, screenBinding, } from './boot.mjs';
32
+ import { evalStaticOrThrow, evalStatic, setBinding, withUndefined, rethrowFoldLimit, HiddenField, RuntimeLeaf, } from './static-eval.mjs';
28
33
  /*----------------------------------------------------------------------------------------------------------------------
29
34
  - Constants
30
35
  ---------------------------------------------------------------------------------------------------------------------*/
31
- /** No state or ref slot widened to 64 bits — the collectors' default. */
32
- export const NO_WIDE = new Map();
36
+ /**
37
+ * The kind of slot a constant is stored in: string, float (a fractional number), or int (anything else).
38
+ *
39
+ * @param value A compile-time value.
40
+ *
41
+ * @returns Its slot kind.
42
+ */
43
+ const slotKindOfValue = (value) => typeof value === 'string'
44
+ ? 'string'
45
+ : typeof value === 'number' && !Number.isInteger(value)
46
+ ? 'float'
47
+ : 'int';
33
48
  /**
34
49
  * What a whole-number initial value needs beyond an int slot, typed as a constant of its size is: nothing in
35
50
  * the int range, a 64-bit number past it, a float past 64 bits.
@@ -68,8 +83,10 @@ export const isFn = (node) => (node &&
68
83
  * @returns The App function.
69
84
  */
70
85
  export function findComponent(program) {
71
- for (const stmt of program.body) {
72
- const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
86
+ for (const statement of program.body) {
87
+ const declaration = statement.type === 'ExportNamedDeclaration'
88
+ ? statement.declaration
89
+ : statement;
73
90
  if (!declaration)
74
91
  continue;
75
92
  if (declaration.type === 'FunctionDeclaration' &&
@@ -77,9 +94,10 @@ export function findComponent(program) {
77
94
  return declaration;
78
95
  }
79
96
  if (declaration.type === 'VariableDeclaration') {
80
- for (const decl of declaration.declarations) {
81
- if (decl.id?.name === 'App' && isFn(decl.init)) {
82
- return decl.init;
97
+ for (const declarator of declaration.declarations) {
98
+ if (declarator.id?.name === 'App' &&
99
+ isFn(declarator.init)) {
100
+ return declarator.init;
83
101
  }
84
102
  }
85
103
  }
@@ -117,10 +135,10 @@ export function declaredNames(body) {
117
135
  }
118
136
  };
119
137
  // Collect identifiers from each top-level variable declaration, including destructured bindings.
120
- for (const stmt of body) {
121
- if (stmt.type === 'VariableDeclaration') {
122
- for (const decl of stmt.declarations) {
123
- walk(decl.id);
138
+ for (const statement of body) {
139
+ if (statement.type === 'VariableDeclaration') {
140
+ for (const declarator of statement.declarations) {
141
+ walk(declarator.id);
124
142
  }
125
143
  }
126
144
  }
@@ -138,6 +156,53 @@ export function bindConst(name, value) {
138
156
  nameBootValues(value, name);
139
157
  return value;
140
158
  }
159
+ /**
160
+ * Folds a destructured const and binds each name it takes, as `const {width, height} = screen`.
161
+ *
162
+ * @param scope The scope to fold against and bind in.
163
+ * @param pattern The pattern.
164
+ * @param init What it destructures.
165
+ *
166
+ * @throws An error when the object doesn't fold, or the pattern is more than plain names for fields it holds.
167
+ */
168
+ export function bindFoldedPattern(scope, pattern, init) {
169
+ const bound = [];
170
+ const collectFields = (objectPattern, value) => {
171
+ if (!isContainer(value) || Array.isArray(value)) {
172
+ throw new Error('AOT: only an object that folds is destructured here');
173
+ }
174
+ const fields = value;
175
+ for (const property of objectPattern.properties) {
176
+ if (property.type === 'RestElement' || property.computed) {
177
+ throw new Error('AOT: the pattern is more than plain names');
178
+ }
179
+ const key = property.key.type === 'Identifier'
180
+ ? property.key.name
181
+ : property.key.type === 'StringLiteral'
182
+ ? property.key.value
183
+ : null;
184
+ const field = key !== null && Object.hasOwn(fields, key) ? fields[key] : undefined;
185
+ if (field === undefined ||
186
+ field instanceof RuntimeLeaf ||
187
+ field instanceof HiddenField) {
188
+ throw new Error('AOT: the field does not fold');
189
+ }
190
+ if (property.value.type === 'Identifier') {
191
+ bound.push([property.value.name, field]);
192
+ }
193
+ else if (property.value.type === 'ObjectPattern') {
194
+ collectFields(property.value, field);
195
+ }
196
+ else {
197
+ throw new Error('AOT: the pattern is more than plain names');
198
+ }
199
+ }
200
+ };
201
+ collectFields(pattern, evalStatic(init, withUndefined(scope), 'boot'));
202
+ for (const [name, value] of bound) {
203
+ setBinding(scope, name, bindConst(name, value));
204
+ }
205
+ }
141
206
  /**
142
207
  * The module's compile-time scope: `screen`, the seed, and every module-level `const` that folds. A const
143
208
  * derived from `screen` is a boot value (see BootValue).
@@ -150,247 +215,554 @@ export function bindConst(name, value) {
150
215
  */
151
216
  export function moduleScope(program, screen, seed = {}) {
152
217
  // Seed the scope (image imports as asset names) before folding module consts, so a const can reference them.
153
- const scope = { screen: screenBinding(screen), ...seed };
154
- // Fold module variables in order so later ones see earlier ones; skip functions, destructuring and non-folds.
155
- for (const stmt of program.body) {
156
- const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
218
+ // The panel's size is kept twice: as `screen`, and as React Native reports it (see rewriteWindowDimensions).
219
+ const panel = screenBinding(screen);
220
+ const scope = {
221
+ screen: panel,
222
+ [PANEL_KEY]: { ...panel, scale: 1, fontScale: 1 },
223
+ ...seed,
224
+ };
225
+ // Fold module variables in order so later ones see earlier ones; skip functions and non-folds.
226
+ for (const statement of program.body) {
227
+ const declaration = statement.type === 'ExportNamedDeclaration'
228
+ ? statement.declaration
229
+ : statement;
157
230
  if (declaration?.type !== 'VariableDeclaration')
158
231
  continue;
159
- for (const decl of declaration.declarations) {
160
- if (!decl.id ||
161
- decl.id.type !== 'Identifier' ||
162
- !decl.init ||
163
- isFn(decl.init)) {
232
+ for (const declarator of declaration.declarations) {
233
+ if (declarator.id?.type === 'ObjectPattern' && declarator.init) {
234
+ try {
235
+ bindFoldedPattern(scope, declarator.id, declarator.init);
236
+ }
237
+ catch (error) {
238
+ rethrowFoldLimit(error);
239
+ }
240
+ continue;
241
+ }
242
+ if (!declarator.id ||
243
+ declarator.id.type !== 'Identifier' ||
244
+ !declarator.init ||
245
+ isFn(declarator.init)) {
164
246
  continue;
165
247
  }
166
248
  try {
167
- setBinding(scope, decl.id.name, bindConst(decl.id.name, evalStatic(decl.init, withUndefined(scope), 'boot')));
249
+ setBinding(scope, declarator.id.name, bindConst(declarator.id.name, evalStatic(declarator.init, withUndefined(scope), 'boot')));
168
250
  }
169
- catch {
170
- /* not a static const — skip */
251
+ catch (error) {
252
+ // Not a static const, so skipped, unless a string helper in it is past what a package can run.
253
+ rethrowFoldLimit(error);
171
254
  }
172
255
  }
173
256
  }
174
257
  return scope;
175
258
  }
176
259
  /**
177
- * Infers a C struct shape from a list-state's initial elements (objects of strings/numbers).
260
+ * Refuses an initial list with more rows than a list holds: they would be dropped at boot without a word. Each
261
+ * string's cap is sized from its values when the app is lowered.
178
262
  *
179
- * @param items The folded initial value.
180
- * @param name The state's name, for errors.
263
+ * @param stateName The state's JS name.
264
+ * @param items The list's initial rows.
265
+ * @param caps The compile's caps.
266
+ * @param initialArgument The initial value, for the error's location.
267
+ */
268
+ function checkInitialRows(stateName, items, caps, initialArgument) {
269
+ if (items.length <= caps.listCap) {
270
+ return;
271
+ }
272
+ const error = aotError(`AOT: list state "${stateName}" starts with ${items.length} rows, but a list holds ${caps.listCap}`, 'raise ER_AOT_LIST_CAP (the listCap option), or start with fewer rows.');
273
+ if (initialArgument?.loc) {
274
+ error.aotLoc = initialArgument.loc.start;
275
+ }
276
+ throw error;
277
+ }
278
+ /**
279
+ * A state's initial value, when it is a number or a boolean derived from `screen`. A string stays folded: a closed
280
+ * set of strings is an interned enum, and there are only as many layouts as strings.
281
+ *
282
+ * @param initialArgument The initial value.
283
+ * @param scope Compile-time constants it folds against.
181
284
  *
182
- * @returns The struct: one field per key of the first element.
285
+ * @returns The boot value, or null.
183
286
  */
184
- function inferItemStruct(items, name) {
185
- // Require a non-empty array so the first element can define the list state's fixed item shape.
186
- const shapeHint = 'a list state is a fixed-shape struct array: each element must be an OBJECT with the same string/number fields, ' +
187
- 'e.g. useState([{ title: "A", n: 1 }, { title: "B", n: 2 }]). The first element defines the columns.';
188
- if (!Array.isArray(items) || !items.length) {
189
- throw aotError(`AOT: list state "${name}" needs ≥1 initial element to infer its item shape`, shapeHint);
287
+ function bootNumberOf(initialArgument, scope) {
288
+ let value;
289
+ try {
290
+ value = evalStatic(initialArgument, scope, 'boot');
190
291
  }
191
- // Require the first list element to be a plain object so its keys can define the item struct.
192
- const first = items[0];
193
- if (typeof first !== 'object' || first === null || Array.isArray(first)) {
194
- throw aotError(`AOT: list state "${name}" elements must be objects`, shapeHint);
292
+ catch {
293
+ return null;
195
294
  }
196
- // Type each field from the first element's value: a string, an int or a float.
197
- const fields = Object.keys(first).map((key) => {
198
- const fieldValue = first[key];
199
- if (typeof fieldValue === 'string')
200
- return { key, kind: 'string' };
201
- if (typeof fieldValue === 'number') {
202
- return { key, kind: Number.isInteger(fieldValue) ? 'int' : 'float' };
295
+ if (!isBoot(value) || !value.lowerable)
296
+ return null;
297
+ const built = buildValueOf(value);
298
+ return typeof built === 'number' || typeof built === 'boolean' ? value : null;
299
+ }
300
+ /**
301
+ * Settles each initial value derived from `screen`, once slots can be lowered: boot works it out, typed by its
302
+ * expression so that every panel gets the same slot (`screen.width / 2` is a fraction on every panel, even where it
303
+ * comes out whole). One boot can't work out is taken at the build's panel.
304
+ *
305
+ * @param states The states.
306
+ */
307
+ export function settleBootInitials(states) {
308
+ for (const state of states) {
309
+ if (state.kind !== 'scalar' || !state.bootValue)
310
+ continue;
311
+ const slot = bootSlotOf(state.bootValue);
312
+ if (slot?.type.kind === 'float') {
313
+ state.slotKind = 'float';
314
+ state.isBoolean = false;
203
315
  }
204
- throw aotError(`AOT: list state "${name}" field "${key}" must be a string or number`, shapeHint);
205
- });
206
- return { fields };
316
+ else if (slot?.type.kind === 'int' || slot?.type.kind === 'bool') {
317
+ state.slotKind = state.widened ? 'i64' : 'int';
318
+ state.isBoolean = slot.type.kind === 'bool';
319
+ }
320
+ if (slot) {
321
+ state.bootInitial = slot;
322
+ }
323
+ else {
324
+ foldBoot(state.bootValue);
325
+ }
326
+ delete state.bootValue;
327
+ }
207
328
  }
208
329
  /**
209
- * Refuses an initial value too big for its fixed buffer: C would cut it short at boot without a word.
330
+ * A scalar state's slot, its kind picked from its initial value.
210
331
  *
211
- * @param stateName The state's JS name.
212
- * @param items The list's initial rows, or null for a scalar.
213
- * @param strings The initial strings it starts with, as `[what, text]` pairs.
214
- * @param caps The compile's caps.
215
- * @param initArg The initial value, for the error's location.
332
+ * @param name The JS name.
333
+ * @param slotName The storage name.
334
+ * @param setter The setter's JS name.
335
+ * @param initialValue The folded initial value.
336
+ * @param initialNode What it was written as, if anything: `70.0` makes a float slot.
337
+ * @param isHost It is a useHostValue.
338
+ * @param bootValue An initial value derived from `screen`.
339
+ *
340
+ * @returns The state.
341
+ */
342
+ function scalarStateOf(name, slotName, setter, initialValue, initialNode, isHost, bootValue) {
343
+ // Pick the slot's kind from the initial value.
344
+ let slotKind = slotKindOfValue(initialValue);
345
+ // Flag booleans: slotKindOfValue makes them int, but text lowering must render false differently from 0.
346
+ const isBoolean = typeof initialValue === 'boolean';
347
+ // A literal written like 70.0 forces a float slot so the state can hold fractions (a smooth drag).
348
+ if (slotKind === 'int' &&
349
+ initialNode?.type === 'NumericLiteral' &&
350
+ typeof initialNode.extra?.raw === 'string' &&
351
+ /[.eE]/.test(initialNode.extra.raw)) {
352
+ slotKind = 'float';
353
+ }
354
+ // A whole number past the int range starts it 64-bit (past 64 bits, a float). A setter that stores a timestamp
355
+ // or such a number in an int slot widens it later, once every store is lowered (see lowerApp).
356
+ const initialWidth = slotKind === 'int' ? wideInitial(initialValue) : null;
357
+ if (initialWidth === 'float') {
358
+ slotKind = 'float';
359
+ }
360
+ const widened = slotKind === 'int' && !isBoolean && initialWidth === 'number'
361
+ ? 'number'
362
+ : undefined;
363
+ if (widened) {
364
+ slotKind = 'i64';
365
+ }
366
+ // String scalar → a fixed buffer; setters format into it (see scalarAssign).
367
+ const initial = slotKind === 'string' ? String(initialValue) : Number(initialValue);
368
+ if (slotKind === 'float') {
369
+ checkNumber(initial);
370
+ }
371
+ else if (slotKind === 'i64') {
372
+ BigInt(initial); // refuses a value that is not a whole number
373
+ }
374
+ return {
375
+ name,
376
+ slotName,
377
+ setter,
378
+ kind: 'scalar',
379
+ slotKind,
380
+ isBoolean,
381
+ initial,
382
+ host: isHost, // host-fed → also an input the host sets
383
+ initialAt: initialNode?.loc?.start,
384
+ ...(widened ? { widened } : {}),
385
+ ...(bootValue ? { bootValue } : {}),
386
+ };
387
+ }
388
+ /**
389
+ * What an object literal holds at a key, when it is written as a plain field.
390
+ *
391
+ * @param node The object.
392
+ * @param key The key.
393
+ *
394
+ * @returns The field's value, or undefined.
216
395
  */
217
- function checkInitialFits(stateName, items, strings, caps, initArg) {
218
- let error = null;
219
- if (items && items.length > caps.listCap) {
220
- error = aotError(`AOT: list state "${stateName}" starts with ${items.length} rows, but a list holds ${caps.listCap}`, 'raise ER_AOT_LIST_CAP (the listCap option), or start with fewer rows.');
396
+ function fieldNodeOf(node, key) {
397
+ if (node?.type !== 'ObjectExpression')
398
+ return undefined;
399
+ for (const property of [...node.properties].reverse()) {
400
+ if (property.type !== 'ObjectProperty' || property.computed)
401
+ continue;
402
+ const name = property.key.type === 'Identifier'
403
+ ? property.key.name
404
+ : property.key.type === 'StringLiteral'
405
+ ? property.key.value
406
+ : null;
407
+ if (name === key)
408
+ return property.value;
221
409
  }
222
- // A string buffer keeps one byte for the terminator.
223
- const tooLong = strings.find(([, text]) => Buffer.byteLength(text, 'utf8') >= caps.listStrCap);
224
- if (!error && tooLong) {
225
- const [what, text] = tooLong;
226
- error = aotError(`AOT: ${what} starts ${Buffer.byteLength(text, 'utf8')} bytes long, but a string holds ` +
227
- `${caps.listStrCap - 1} bytes`, 'raise ER_AOT_LIST_STR_CAP (the listStrCap option), or shorten the string.');
410
+ return undefined;
411
+ }
412
+ /**
413
+ * An object state: one scalar state per field, nested objects flattened to dotted paths.
414
+ *
415
+ * @param name The JS name.
416
+ * @param prefix The storage prefix.
417
+ * @param setter The setter's JS name.
418
+ * @param value The folded initial value.
419
+ * @param initialNode What it was written as.
420
+ *
421
+ * @returns The record.
422
+ */
423
+ function recordStateOf(name, prefix, setter, value, initialNode) {
424
+ const fields = new Map();
425
+ const fail = (message, hint, at) => {
426
+ const error = aotError(message, hint);
427
+ const location = (at ?? initialNode).loc;
428
+ if (location)
429
+ error.aotLoc = location.start;
430
+ return error;
431
+ };
432
+ const flatten = (object, path, node) => {
433
+ const entries = Object.entries(object);
434
+ if (!entries.length) {
435
+ throw fail(`AOT: state "${[name, ...path].join('.')}" is an empty object`, 'give it the fields it will hold, each with a starting value.', node);
436
+ }
437
+ const folded = {};
438
+ for (const [key, fieldValue] of entries) {
439
+ const fieldPath = [...path, key];
440
+ const fieldName = [name, ...fieldPath].join('.');
441
+ const fieldNode = fieldNodeOf(node, key);
442
+ // Fields are keyed by their dotted path, so a key can't hold a dot.
443
+ if (key === '' || key.includes('.')) {
444
+ throw fail(`AOT: state "${[name, ...path].join('.')}" has a field named "${key}"`, 'name each field with letters, digits or `_`.', fieldNode);
445
+ }
446
+ if (isObjectTree(fieldValue)) {
447
+ folded[key] = flatten(fieldValue, fieldPath, fieldNode);
448
+ continue;
449
+ }
450
+ if (Array.isArray(fieldValue)) {
451
+ throw fail(`AOT: state "${fieldName}" is an array inside an object state`, 'keep the list in a useState of its own.', fieldNode);
452
+ }
453
+ if (fieldValue == null ||
454
+ (typeof fieldValue === 'number' && !Number.isFinite(fieldValue)) ||
455
+ !['number', 'string', 'boolean'].includes(typeof fieldValue)) {
456
+ throw fail(`AOT: the initial value of state "${fieldName}" is ${typeof fieldValue === 'function' ? 'a function' : String(fieldValue)}`, "give each field a concrete starting value: 0, '' or false.", fieldNode);
457
+ }
458
+ const state = scalarStateOf(fieldName, prefix + fieldName, undefined, fieldValue, fieldNode, false, null);
459
+ state.initialAt ??= initialNode.loc?.start;
460
+ fields.set(fieldPath.join('.'), state);
461
+ folded[key] = new RuntimeLeaf(stateLocal(state));
462
+ }
463
+ return folded;
464
+ };
465
+ const folded = flatten(value, [], initialNode);
466
+ return { kind: 'record', name, setter, fields, value: folded };
467
+ }
468
+ /**
469
+ * Makes an object state of several shapes a tagged record: a hidden slot holding the shape's index, and a slot for
470
+ * every field any shape has. A field the initial value lacks takes its kind from a constant written for it, and
471
+ * starts at zero.
472
+ *
473
+ * @param record The record of the initial value.
474
+ * @param shapes The shapes.
475
+ * @param written The objects the setter is given.
476
+ * @param prefix The storage prefix.
477
+ * @param initialNode What the initial value was written as.
478
+ *
479
+ * @returns The record.
480
+ */
481
+ function tagRecord(record, shapes, written, prefix, initialNode) {
482
+ const { name, setter } = record;
483
+ const fail = (message, hint) => {
484
+ const error = aotError(message, hint);
485
+ if (initialNode.loc)
486
+ error.aotLoc = initialNode.loc.start;
487
+ return error;
488
+ };
489
+ const describe = (value) => value === null || value === undefined ? String(value) : `a ${typeof value}`;
490
+ const keys = new Set(shapes.shapes.flatMap(shape => [...shape]));
491
+ const fields = new Map();
492
+ for (const key of keys) {
493
+ if ([...keys].some(other => other.startsWith(`${key}.`))) {
494
+ throw fail(`AOT: "${name}.${key}" is an object in one shape and a value in another`, 'give the field the same kind in every shape.');
495
+ }
496
+ const constants = written.flatMap(object => {
497
+ const field = object.fields.get(key);
498
+ return field?.known ? [field] : [];
499
+ });
500
+ let field = record.fields.get(key);
501
+ if (!field) {
502
+ if (!constants.length) {
503
+ throw fail(`AOT: "${name}.${key}" is never written with a constant`, `its kind comes from a constant; write one for it once: ${setter}({…, ${key.split('.').at(-1)}: 0}).`);
504
+ }
505
+ const representative = constants.find(({ value }) => typeof value === 'number' && !Number.isInteger(value)) ??
506
+ constants.find(({ node }) => node?.type === 'NumericLiteral' &&
507
+ /[.eE]/.test(String(node.extra?.raw ?? ''))) ??
508
+ constants[0];
509
+ const { value } = representative;
510
+ if (!['number', 'string', 'boolean'].includes(typeof value) ||
511
+ (typeof value === 'number' && !Number.isFinite(value))) {
512
+ throw fail(`AOT: "${name}.${key}" is written with ${typeof value === 'number' ? value : describe(value)}`, "give each field a concrete value: 0, '' or false.");
513
+ }
514
+ field = scalarStateOf(`${name}.${key}`, `${prefix}${name}.${key}`, undefined, value, representative.node, false, null);
515
+ field.initial = field.slotKind === 'string' ? '' : 0;
516
+ field.initialAt = initialNode.loc?.start;
517
+ }
518
+ const kind = field.slotKind === 'string'
519
+ ? 'string'
520
+ : field.isBoolean
521
+ ? 'boolean'
522
+ : 'number';
523
+ for (const { value } of constants) {
524
+ if (typeof value !== kind) {
525
+ throw fail(`AOT: "${name}.${key}" holds a ${kind} in one place and ${describe(value)} in another`, `give the field one kind in every shape, as ${tagText(shapes.values[0])} gives it.`);
526
+ }
527
+ }
528
+ fields.set(key, field);
228
529
  }
229
- if (error) {
230
- if (initArg?.loc) {
231
- error.aotLoc = initArg.loc.start;
530
+ const tagName = `${name}.${shapes.key}`;
531
+ const tagState = scalarStateOf(tagName, prefix + tagName, undefined, 0, undefined, false, null);
532
+ tagState.initialAt = initialNode.loc?.start;
533
+ const tagged = {
534
+ ...record,
535
+ fields,
536
+ tag: {
537
+ key: shapes.key,
538
+ state: tagState,
539
+ values: shapes.values,
540
+ shapes: shapes.shapes,
541
+ },
542
+ };
543
+ tagged.value = taggedTreeOf(tagged, shapes.values.map((_, shape) => shape));
544
+ return tagged;
545
+ }
546
+ /**
547
+ * An error pinned to a node.
548
+ *
549
+ * @param error The error.
550
+ * @param node The node.
551
+ *
552
+ * @returns The error.
553
+ */
554
+ function locatedAt(error, node) {
555
+ locateError(error, node?.loc?.start);
556
+ return error;
557
+ }
558
+ /**
559
+ * The function a useReducer is given: written inline, or named and declared in the component or the module.
560
+ *
561
+ * @param node The useReducer's first argument.
562
+ * @param stateName The state's name, for errors.
563
+ * @param functionBody The component's body.
564
+ * @param program The module.
565
+ *
566
+ * @returns The reducer.
567
+ */
568
+ function reducerOf(node, stateName, functionBody, program) {
569
+ // What a name is bound to at one level: a function, something else, or nothing.
570
+ const bindingIn = (statements, name) => {
571
+ for (const statement of statements) {
572
+ const declaration = statement.type === 'ExportNamedDeclaration'
573
+ ? statement.declaration
574
+ : statement;
575
+ if (declaration?.type === 'FunctionDeclaration' &&
576
+ declaration.id?.name === name) {
577
+ return declaration;
578
+ }
579
+ if (declaration?.type !== 'VariableDeclaration')
580
+ continue;
581
+ for (const declarator of declaration.declarations) {
582
+ if (!patternNames(declarator.id).includes(name))
583
+ continue;
584
+ return declarator.id.type === 'Identifier' && isFn(declarator.init)
585
+ ? declarator.init
586
+ : 'other';
587
+ }
232
588
  }
233
- throw error;
589
+ return null;
590
+ };
591
+ // The component's own binding of the name hides the module's.
592
+ const bound = isFn(node)
593
+ ? node
594
+ : node?.type === 'Identifier'
595
+ ? (bindingIn(functionBody.body, node.name) ??
596
+ bindingIn(program?.body ?? [], node.name))
597
+ : null;
598
+ const functionNode = bound === 'other' ? null : bound;
599
+ if (!functionNode) {
600
+ throw locatedAt(aotError(`AOT: the reducer for "${stateName}" must be a function in this file`, 'pass a function declared in this file, or write it inline: useReducer((state, action) => …, initial).'), node);
234
601
  }
602
+ const name = node?.type === 'Identifier' ? node.name : 'reducer';
603
+ if (functionNode.params.length > 2 ||
604
+ functionNode.params.some(parameter => parameter.type !== 'Identifier')) {
605
+ throw locatedAt(aotError(`AOT: reducer "${name}" must take plain (state, action) params`, 'name the state and the action: function reducer(state, action) { … }.'), functionNode);
606
+ }
607
+ return { name, functionNode };
235
608
  }
236
609
  /**
237
- * Collects a component's useState declarations → state descriptors keyed by JS name (reads) and setter
238
- * name (writes). `prefix` namespaces the C STORAGE so each inlined child instance gets its own slots: the
239
- * lookup keys stay the bare JS names (`count`), but the C field / array / count derive from `cField`
610
+ * Collects a component's useState and useReducer declarations → state descriptors keyed by JS name (reads) and setter
611
+ * name (writes): a useReducer's dispatch is its setter, and the state keeps its reducer. `prefix` namespaces the STORAGE so each inlined child instance gets its own slots: the
612
+ * lookup keys stay the bare JS names (`count`), but the field / array / count derive from `slotName`
240
613
  * (`<prefix>count`). prefix='' (the App) keeps the storage names exactly the JS names.
241
614
  * `caps` are the compiler's resolved caps (see resolveOptions); a list state takes its capacity from it.
242
615
  *
243
- * @param fnBody The component's body.
616
+ * @param functionBody The component's body.
244
617
  * @param scope Compile-time constants the initial values fold against.
245
618
  * @param caps The compile's caps.
246
- * @param prefix The C storage prefix: none for the App, `c<n>_` for an inlined instance.
247
- * @param wide Slots to declare 64-bit (see compileWidened).
619
+ * @param prefix The storage prefix: none for the App, `c<n>_` for an inlined instance.
620
+ * @param program The module, where a reducer may be declared.
248
621
  *
249
622
  * @returns The component's state table.
250
623
  */
251
- export function collectState(fnBody, scope, caps, prefix = '', wide = NO_WIDE) {
624
+ export function collectState(functionBody, scope, caps, prefix = '', program) {
252
625
  // Index each state by its JS name and, when it has one, by its setter's name.
253
626
  const byName = new Map();
254
627
  const bySetter = new Map();
255
628
  // Scan the body's top-level declarations for useState and useHostValue calls.
256
- for (const stmt of fnBody.body) {
257
- if (stmt.type !== 'VariableDeclaration')
629
+ for (const statement of functionBody.body) {
630
+ if (statement.type !== 'VariableDeclaration')
258
631
  continue;
259
632
  // Inspect each declaration in the statement so multiple hook bindings in one `const` are collected independently.
260
- for (const decl of stmt.declarations) {
633
+ for (const declarator of statement.declarations) {
261
634
  // Only hook-style call declarations can define collected state; plain variables and other initializers are skipped.
262
- const init = decl.init;
263
- if (init?.type !== 'CallExpression')
635
+ const initializer = declarator.init;
636
+ if (initializer?.type !== 'CallExpression')
264
637
  continue;
265
- // useHostValue is a host-fed scalar: an s_state field like useState, written only via er_app_set_<name>().
266
- const isHost = init.callee.name === 'useHostValue';
267
- if (init.callee.name !== 'useState' && !isHost) {
638
+ // useHostValue is a host-fed scalar: a state slot like useState, written only by the host through its input.
639
+ // useReducer is a state slot whose setter is its dispatch.
640
+ const hook = initializer.callee.name;
641
+ const isHost = hook === 'useHostValue';
642
+ const isReducer = hook === 'useReducer';
643
+ if (hook !== 'useState' && !isHost && !isReducer) {
268
644
  continue;
269
645
  }
270
646
  // Accept useHostValue(name) as a direct scalar binding, while useState must keep the usual [value, setter] tuple pattern.
271
- if (isHost ? decl.id.type !== 'Identifier' : decl.id.type !== 'ArrayPattern') {
647
+ if (isHost
648
+ ? declarator.id.type !== 'Identifier'
649
+ : declarator.id.type !== 'ArrayPattern') {
272
650
  continue;
273
651
  }
274
652
  // Derive the read name and optional setter from the binding shape: host values bind directly, while useState binds [value, setter].
275
653
  const name = isHost
276
- ? decl.id.name
277
- : decl.id.elements[0]
654
+ ? declarator.id.name
655
+ : declarator.id.elements[0]
278
656
  ?.name;
279
657
  const setter = isHost
280
658
  ? undefined
281
- : decl.id.elements[1]
659
+ : declarator.id.elements[1]
282
660
  ?.name;
283
661
  if (!name)
284
662
  continue;
285
- // Build either a list-state record from an array initializer or a scalar record from the folded initial value.
286
- const cField = prefix + name; // C storage name (== name for the App; instance-unique for a child)
287
- const initArg = init.arguments[0];
663
+ // Build either a list-state record from an array initializer, or a split of a constant, or a scalar record from
664
+ // the folded initial value.
665
+ const slotName = prefix + name; // storage name (== name for the App; instance-unique for a child)
666
+ const initialArgument = initializer.arguments[isReducer ? 1 : 0];
667
+ let reducer;
668
+ if (isReducer) {
669
+ if (initializer.arguments.length !== 2) {
670
+ throw locatedAt(aotError(`AOT: useReducer for "${name}" must take a reducer and an initial value`, 'work the initial value out in the call instead of passing an init function: ' +
671
+ 'useReducer(reducer, {count: 0}).'), initializer);
672
+ }
673
+ reducer = reducerOf(initializer.arguments[0], name, functionBody, program);
674
+ }
288
675
  let record;
289
- if (!isHost && initArg?.type === 'ArrayExpression') {
290
- // List state → a fixed-capacity C struct array + a count (s_<name>[CAP], s_<name>_count).
291
- const items = evalStaticOrThrow(initArg, scope, `AOT: the initial value of list state "${name}" must be a compile-time constant array`, 'useState([...]) initial must be a literal array of objects/numbers/strings — no ' +
292
- 'runtime values or function calls in the initial.');
676
+ if (!isHost &&
677
+ (initialArgument?.type === 'ArrayExpression' ||
678
+ splitCallOf(initialArgument))) {
679
+ // List state → a fixed-capacity pool of rows + a count.
680
+ const items = evalStaticOrThrow(initialArgument, scope, `AOT: the initial value of list state "${name}" must be a compile-time constant array`, 'useState([...]) initial must be a literal array of objects, numbers, strings or booleans, or a split ' +
681
+ 'of a constant string — no runtime values or other function calls in the initial.');
293
682
  // Infer the item struct, pinning any error to the initial value since this pass adds no location.
294
683
  let struct;
295
684
  try {
296
- struct = inferItemStruct(items, name);
685
+ struct = inferItemStruct(items, `list state "${name}"`);
297
686
  }
298
687
  catch (error) {
299
- if (initArg.loc && !error.aotLoc) {
300
- error.aotLoc = initArg.loc.start; // collectState isn't withLoc-wrapped
688
+ if (initialArgument.loc && !error.aotLoc) {
689
+ error.aotLoc = initialArgument.loc.start; // collectState isn't withLoc-wrapped
301
690
  }
302
691
  throw error;
303
692
  }
304
- checkInitialFits(name, items, items.flatMap(item => struct.fields
305
- .filter(field => field.kind === 'string')
306
- .map((field) => [
307
- `field "${field.key}" of list state "${name}"`,
308
- String(item[field.key] ?? ''),
309
- ])), caps, initArg);
693
+ checkInitialRows(name, items, caps, initialArgument);
310
694
  record = {
311
695
  name,
312
- cField,
696
+ slotName,
313
697
  setter,
314
698
  kind: 'list',
315
699
  struct,
316
700
  items,
317
- cap: caps.listCap,
318
- cTypeName: `ErItem_${cField}`,
319
- arrayName: `s_${cField}`,
320
- countMember: `s_${cField}_count`,
701
+ capacity: caps.listCap,
702
+ initialAt: initialArgument?.loc?.start,
321
703
  };
322
704
  }
323
705
  else {
324
- // Scalar state → one s_state field. Fold the initial value; no argument starts it at 0.
325
- const initValue = initArg
326
- ? evalStaticOrThrow(initArg, scope, `AOT: the initial value of state "${name}" must be a compile-time constant`, 'useState(x) initial must be a literal or a constant expression (number, string, ' +
327
- 'bool, or arithmetic over consts) — not a runtime value or function call.')
328
- : 0;
329
- // A host value must be a finite number; check it directly, since cTypeOfValue maps non-numbers to int.
330
- if (isHost && !Number.isFinite(initValue)) {
706
+ // Scalar state → one slot. Fold the initial value; no argument starts it at 0. A number derived
707
+ // from `screen` is worked out at boot (see settleBootInitials), so it doesn't take a layout per value.
708
+ const bootValue = !isHost && initialArgument
709
+ ? bootNumberOf(initialArgument, scope)
710
+ : null;
711
+ const initialValue = bootValue
712
+ ? buildValueOf(bootValue)
713
+ : initialArgument
714
+ ? evalStaticOrThrow(initialArgument, scope, `AOT: the initial value of state "${name}" must be a compile-time constant`, 'useState(x) initial must be a literal or a constant expression (number, string, ' +
715
+ 'bool, or arithmetic over consts) — not a runtime value or function call.')
716
+ : 0;
717
+ // Object state → a record, a scalar slot per field, which reads of its name fold through.
718
+ if (!isHost && isObjectTree(initialValue)) {
719
+ let recordState = recordStateOf(name, prefix, setter, initialValue, initialArgument);
720
+ // Objects written with other fields make it a tagged record of several shapes. A reducer writes the
721
+ // objects it returns.
722
+ const written = reducer
723
+ ? returnedObjects(reducer.functionNode, scope)
724
+ : setter
725
+ ? writtenObjects(functionBody, setter, scope)
726
+ : [];
727
+ const shapes = setter
728
+ ? recordShapesOf(name, setter, flattenTree(initialValue), written, reducer ? object => `return ${object}` : undefined)
729
+ : null;
730
+ if (shapes) {
731
+ recordState = tagRecord(recordState, shapes, written, prefix, initialArgument);
732
+ byName.set(`${name}.${shapes.key}`, recordState.tag.state);
733
+ }
734
+ if (reducer)
735
+ recordState.reducer = reducer;
736
+ for (const [key, field] of recordState.fields) {
737
+ byName.set(`${name}.${key}`, field);
738
+ }
739
+ if (setter) {
740
+ bySetter.set(setter, recordState);
741
+ }
742
+ setBinding(scope, name, recordState.value);
743
+ continue;
744
+ }
745
+ // A host value must be a finite number; check it directly, since slotKindOfValue maps non-numbers to int.
746
+ if (isHost && !Number.isFinite(initialValue)) {
331
747
  throw aotError(`AOT: useHostValue("${name}") must be a number — its initial value evaluated to ` +
332
- `${JSON.stringify(initValue)}`, 'useHostValue(0) / useHostValue(0.0) — the host feeds an int or float; booleans, ' +
748
+ `${JSON.stringify(initialValue)}`, 'useHostValue(0) / useHostValue(0.0) — the host feeds an int or float; booleans, ' +
333
749
  'strings, and objects are not supported.');
334
750
  }
335
- // Refuse undefined, null and non-finite initials here; they would fold into invalid C with no location.
336
- if (initValue === undefined ||
337
- initValue === null ||
338
- (typeof initValue === 'number' && !Number.isFinite(initValue))) {
339
- const error = aotError(`AOT: the initial value of state "${name}" is ${initValue === undefined ? 'undefined' : String(initValue)}`, "give it a concrete starting value: useState(0), useState(''), useState(false).");
340
- if (initArg?.loc) {
341
- error.aotLoc = initArg.loc.start;
751
+ // Refuse undefined, null and non-finite initials here; they would fold into nonsense with no location.
752
+ if (initialValue === undefined ||
753
+ initialValue === null ||
754
+ (typeof initialValue === 'number' && !Number.isFinite(initialValue))) {
755
+ const error = aotError(`AOT: the initial value of state "${name}" is ${initialValue === undefined ? 'undefined' : String(initialValue)}`, "give it a concrete starting value: useState(0), useState(''), useState(false).");
756
+ if (initialArgument?.loc) {
757
+ error.aotLoc = initialArgument.loc.start;
342
758
  }
343
759
  throw error;
344
760
  }
345
- // Pick the slot's C type from the initial value.
346
- let cType = cTypeOfValue(initValue);
347
- // Flag booleans: cTypeOfValue makes them int, but text lowering must render false differently from 0.
348
- const isBool = typeof initValue === 'boolean';
349
- // A literal written like 70.0 forces a float slot so the state can hold fractions (a smooth drag).
350
- if (cType === 'int' &&
351
- initArg?.type === 'NumericLiteral' &&
352
- typeof initArg.extra?.raw === 'string' &&
353
- /[.eE]/.test(initArg.extra.raw)) {
354
- cType = 'float';
355
- }
356
- // A whole number past the int range starts it 64-bit (past 64 bits, a float), as does a setter that
357
- // stores a timestamp or such a number in it (see compileWidened).
358
- const initialWidth = cType === 'int' ? wideInitial(initValue) : null;
359
- if (initialWidth === 'float') {
360
- cType = 'float';
361
- }
362
- const widened = cType === 'int' && !isBool
363
- ? (wide.get(cField) ??
364
- (initialWidth === 'number' ? 'number' : undefined))
365
- : undefined;
366
- if (widened) {
367
- cType = 'i64';
368
- }
369
- // String scalar → a fixed char buffer in ErAppState; setters snprintf into it (see scalarAssign).
370
- const initial = cType === 'string' ? String(initValue) : Number(initValue);
371
- if (cType === 'float') {
372
- checkNumber(initial);
373
- }
374
- else if (cType === 'i64') {
375
- cConstant(initial, cType); // BigInt refuses a value that is not a whole number
376
- }
377
- else if (cType === 'string') {
378
- checkInitialFits(name, null, [[`state "${name}"`, String(initial)]], caps, initArg);
379
- }
380
- record = {
381
- name,
382
- cField,
383
- setter,
384
- kind: 'scalar',
385
- cType,
386
- isBool,
387
- cMember: `s_state.${cField}`,
388
- initial,
389
- host: isHost, // host-fed → also emit a public er_app_set_<name>() setter
390
- ...(widened ? { widened } : {}),
391
- };
761
+ record = scalarStateOf(name, slotName, setter, initialValue, initialArgument, isHost, bootValue);
392
762
  }
393
763
  // Register the state for reads by name and for writes through its setter.
764
+ if (reducer)
765
+ record.reducer = reducer;
394
766
  byName.set(name, record);
395
767
  if (setter) {
396
768
  bySetter.set(setter, record);
@@ -404,21 +776,21 @@ export function collectState(fnBody, scope, caps, prefix = '', wide = NO_WIDE) {
404
776
  * responsive layout returns the branch for this build's screen. When the test depends on the panel and both
405
777
  * outcomes return elements of one shape, they merge into one element whose values boot picks.
406
778
  *
407
- * @param fnBody The component's body.
779
+ * @param functionBody The component's body.
408
780
  * @param scope Compile-time constants the `if` tests fold against.
409
781
  *
410
782
  * @returns The returned element.
411
783
  */
412
- export function findReturnJSX(fnBody, scope = {}) {
784
+ export function findReturnJSX(functionBody, scope = {}) {
413
785
  const statementsOf = (branch) => branch.type === 'BlockStatement' ? branch.body : [branch];
414
786
  // Fold top-level `if (staticCond) return …` at compile time — responsive layouts switch on `screen`.
415
787
  const scan = (statements) => {
416
- for (const [index, stmt] of statements.entries()) {
788
+ for (const [index, statement] of statements.entries()) {
417
789
  // A top-level `if` must fold; only the branch it takes is scanned.
418
- if (stmt.type === 'IfStatement') {
790
+ if (statement.type === 'IfStatement') {
419
791
  let testValue;
420
792
  try {
421
- testValue = evalStatic(stmt.test, scope, 'boot');
793
+ testValue = evalStatic(statement.test, scope, 'boot');
422
794
  }
423
795
  catch {
424
796
  throw new Error('AOT: a top-level `if` in the component must have a compile-time-constant test (e.g. ' +
@@ -426,13 +798,13 @@ export function findReturnJSX(fnBody, scope = {}) {
426
798
  }
427
799
  // A test that depends on the panel needs no variant when both outcomes have one shape.
428
800
  if (isBoot(testValue)) {
429
- const merged = mergeOutcomes(stmt, statements.slice(index + 1));
801
+ const merged = mergeOutcomes(statement, statements.slice(index + 1));
430
802
  if (merged)
431
803
  return merged;
432
804
  testValue = foldBoot(testValue);
433
805
  }
434
806
  // Follow only the statically selected branch and keep scanning it until a JSX return is found.
435
- const branch = testValue ? stmt.consequent : stmt.alternate;
807
+ const branch = testValue ? statement.consequent : statement.alternate;
436
808
  if (branch) {
437
809
  const branchJSX = scan(statementsOf(branch));
438
810
  if (branchJSX)
@@ -441,22 +813,51 @@ export function findReturnJSX(fnBody, scope = {}) {
441
813
  continue;
442
814
  }
443
815
  // A `return` with a value ends the scan and must return a single JSX element.
444
- if (stmt.type === 'ReturnStatement' && stmt.argument) {
445
- if (stmt.argument.type === 'JSXElement')
446
- return stmt.argument;
447
- throw new Error(`AOT: the component must return a single JSX element (got ${stmt.argument.type})`);
816
+ if (statement.type === 'ReturnStatement' && statement.argument) {
817
+ return returned(statement.argument);
448
818
  }
449
819
  }
450
820
  return null;
451
821
  };
822
+ // The element a `return` gives: a ternary on the panel is decided as a top-level `if` is.
823
+ const returned = (argument) => {
824
+ if (argument.type === 'JSXElement')
825
+ return argument;
826
+ if (argument.type !== 'ConditionalExpression') {
827
+ throw new Error(`AOT: the component must return a single JSX element (got ${argument.type})`);
828
+ }
829
+ let testValue;
830
+ try {
831
+ testValue = evalStatic(argument.test, scope, 'boot');
832
+ }
833
+ catch {
834
+ throw new Error('AOT: a ternary the component returns must have a compile-time-constant test (e.g. on the `screen` ' +
835
+ 'global) — runtime layout branching is not supported');
836
+ }
837
+ if (isBoot(testValue)) {
838
+ const restore = bootCheckpoint();
839
+ try {
840
+ const merged = mergeBranchElements(argument.test, returned(argument.consequent), returned(argument.alternate));
841
+ if (merged)
842
+ return merged;
843
+ }
844
+ catch {
845
+ /* an outcome that does not compile here is left to the fold, which reports it if it is taken */
846
+ }
847
+ restore();
848
+ testValue = foldBoot(testValue);
849
+ }
850
+ return returned(testValue ? argument.consequent : argument.alternate);
851
+ };
452
852
  // What each outcome of an `if` returns (a branch that does not return falls through), merged when it can be.
453
- const mergeOutcomes = (stmt, rest) => {
853
+ const mergeOutcomes = (statement, rest) => {
454
854
  const restore = bootCheckpoint();
455
855
  try {
456
- const whenTrue = scan(statementsOf(stmt.consequent)) ?? scan(rest);
457
- const whenFalse = (stmt.alternate && scan(statementsOf(stmt.alternate))) ?? scan(rest);
856
+ const whenTrue = scan(statementsOf(statement.consequent)) ?? scan(rest);
857
+ const whenFalse = (statement.alternate && scan(statementsOf(statement.alternate))) ??
858
+ scan(rest);
458
859
  const merged = whenTrue && whenFalse
459
- ? mergeBranchElements(stmt.test, whenTrue, whenFalse)
860
+ ? mergeBranchElements(statement.test, whenTrue, whenFalse)
460
861
  : null;
461
862
  if (merged)
462
863
  return merged;
@@ -468,7 +869,7 @@ export function findReturnJSX(fnBody, scope = {}) {
468
869
  return null;
469
870
  };
470
871
  // Scan the body; a component that never returns is an error.
471
- const returnJSX = scan(fnBody.body);
872
+ const returnJSX = scan(functionBody.body);
472
873
  if (!returnJSX) {
473
874
  throw new Error('AOT: component has no return statement');
474
875
  }
@@ -477,28 +878,28 @@ export function findReturnJSX(fnBody, scope = {}) {
477
878
  /**
478
879
  * Returns the JSX a function component returns (arrow expression body or a block's return).
479
880
  *
480
- * @param fn The component.
881
+ * @param functionNode The component.
481
882
  * @param scope Compile-time constants its top-level `if` tests fold against.
482
883
  *
483
884
  * @returns The returned element.
484
885
  */
485
- export function componentReturnJSX(fn, scope = {}) {
486
- if (fn.body.type === 'JSXElement')
487
- return fn.body;
488
- if (fn.body.type === 'BlockStatement')
489
- return findReturnJSX(fn.body, scope);
886
+ export function componentReturnJSX(functionNode, scope = {}) {
887
+ if (functionNode.body.type === 'JSXElement')
888
+ return functionNode.body;
889
+ if (functionNode.body.type === 'BlockStatement')
890
+ return findReturnJSX(functionNode.body, scope);
490
891
  throw new Error('AOT: component body must return a JSX element');
491
892
  }
492
893
  /**
493
894
  * Whether a function returns JSX (a component) rather than a value (a helper).
494
895
  *
495
- * @param fn The function.
896
+ * @param functionNode The function.
496
897
  *
497
898
  * @returns Whether its body is JSX or has a top-level `return <…/>`.
498
899
  */
499
- const fnReturnsJSX = (fn) => fn.body.type === 'JSXElement' ||
500
- (fn.body.type === 'BlockStatement' &&
501
- fn.body.body.some(statement => statement.type === 'ReturnStatement' &&
900
+ const fnReturnsJSX = (functionNode) => functionNode.body.type === 'JSXElement' ||
901
+ (functionNode.body.type === 'BlockStatement' &&
902
+ functionNode.body.body.some(statement => statement.type === 'ReturnStatement' &&
502
903
  statement.argument?.type === 'JSXElement'));
503
904
  /**
504
905
  * Resolves a component definition expression to its function node, unwrapping memo(fn) / React.memo(fn).
@@ -529,8 +930,10 @@ function asComponentFn(node) {
529
930
  */
530
931
  export function collectComponents(program) {
531
932
  const components = new Map();
532
- for (const stmt of program.body) {
533
- const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
933
+ for (const statement of program.body) {
934
+ const declaration = statement.type === 'ExportNamedDeclaration'
935
+ ? statement.declaration
936
+ : statement;
534
937
  if (!declaration)
535
938
  continue;
536
939
  // `function Card() { return <…/>; }`
@@ -542,12 +945,13 @@ export function collectComponents(program) {
542
945
  }
543
946
  // `const Card = (…) => <…/>`, optionally wrapped in memo(…).
544
947
  if (declaration.type === 'VariableDeclaration') {
545
- for (const decl of declaration.declarations) {
546
- if (decl.id?.type !== 'Identifier' || decl.id.name === 'App')
948
+ for (const declarator of declaration.declarations) {
949
+ if (declarator.id?.type !== 'Identifier' ||
950
+ declarator.id.name === 'App')
547
951
  continue;
548
- const fn = asComponentFn(decl.init); // unwrap memo(...)
549
- if (fn && fnReturnsJSX(fn)) {
550
- components.set(decl.id.name, fn);
952
+ const functionNode = asComponentFn(declarator.init); // unwrap memo(...)
953
+ if (functionNode && fnReturnsJSX(functionNode)) {
954
+ components.set(declarator.id.name, functionNode);
551
955
  }
552
956
  }
553
957
  }
@@ -568,46 +972,58 @@ export function collectComponents(program) {
568
972
  export function collectHelpers(componentBody, program) {
569
973
  // Record a binding as a helper when it holds a function that does not return JSX.
570
974
  const helpers = new Map();
571
- const addHelper = (name, fn) => {
572
- if (name && name !== 'App' && isFn(fn) && !fnReturnsJSX(fn)) {
573
- helpers.set(name, fn);
975
+ const addHelper = (name, functionNode) => {
976
+ if (name &&
977
+ name !== 'App' &&
978
+ isFn(functionNode) &&
979
+ !fnReturnsJSX(functionNode)) {
980
+ helpers.set(name, functionNode);
574
981
  }
575
982
  };
576
983
  // Module-level function declarations and function-valued variables.
577
- for (const stmt of program.body) {
578
- const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
984
+ for (const statement of program.body) {
985
+ const declaration = statement.type === 'ExportNamedDeclaration'
986
+ ? statement.declaration
987
+ : statement;
579
988
  if (!declaration)
580
989
  continue;
581
990
  if (declaration.type === 'FunctionDeclaration' && declaration.id) {
582
991
  addHelper(declaration.id.name, declaration);
583
992
  }
584
993
  if (declaration.type === 'VariableDeclaration') {
585
- for (const decl of declaration.declarations) {
586
- if (decl.id?.type === 'Identifier') {
587
- addHelper(decl.id.name, decl.init);
994
+ for (const declarator of declaration.declarations) {
995
+ if (declarator.id?.type === 'Identifier') {
996
+ addHelper(declarator.id.name, declarator.init);
588
997
  }
589
998
  }
590
999
  }
591
1000
  }
592
1001
  // The component's own top-level arrows and functions (a hook call is not a function, so it is skipped).
593
1002
  if (componentBody.type === 'BlockStatement') {
594
- for (const stmt of componentBody.body) {
595
- if (stmt.type !== 'VariableDeclaration')
1003
+ for (const statement of componentBody.body) {
1004
+ if (statement.type !== 'VariableDeclaration')
596
1005
  continue;
597
- for (const decl of stmt.declarations) {
598
- if (decl.id?.type === 'Identifier') {
599
- addHelper(decl.id.name, decl.init);
1006
+ for (const declarator of statement.declarations) {
1007
+ if (declarator.id?.type === 'Identifier') {
1008
+ addHelper(declarator.id.name, declarator.init);
600
1009
  }
601
1010
  }
602
1011
  }
603
1012
  }
1013
+ // A block-bodied memo is a helper with no params.
1014
+ for (const [name, functionNode] of memoFunctions(componentBody)) {
1015
+ if (functionNode.body.type === 'BlockStatement') {
1016
+ helpers.set(memoHelperName(name), functionNode);
1017
+ }
1018
+ }
604
1019
  return helpers;
605
1020
  }
606
1021
  /**
607
1022
  * Collects image imports — `import wxSun from './assets/wx_sun.png'` → Map (local → { name, importPath }).
608
1023
  * `name` is the file's basename without extension (the asset key `<Image source>` resolves to and that the
609
1024
  * Flow A bundler also uses); `importPath` is the source-relative path the CLI bakes from. Mirrors the Flow A
610
- * esbuild asset plugin so the same `import → basename` convention holds in both flows.
1025
+ * esbuild asset plugin so the same `import → basename` convention holds in both flows. Two different files of
1026
+ * one name would be one asset, so they are refused.
611
1027
  *
612
1028
  * @param program The parsed module.
613
1029
  *
@@ -616,16 +1032,25 @@ export function collectHelpers(componentBody, program) {
616
1032
  export function collectImageImports(program) {
617
1033
  // Map each default import of an image file to the file's basename.
618
1034
  const byLocal = new Map();
619
- for (const stmt of program.body) {
620
- if (stmt.type !== 'ImportDeclaration' ||
621
- typeof stmt.source.value !== 'string') {
1035
+ const pathOf = new Map(); // name → the file it names
1036
+ const normalized = (path) => posix.normalize(path.replace(/\\/g, '/'));
1037
+ for (const statement of program.body) {
1038
+ if (statement.type !== 'ImportDeclaration' ||
1039
+ typeof statement.source.value !== 'string') {
622
1040
  continue;
623
1041
  }
624
- const importPath = stmt.source.value;
1042
+ const importPath = statement.source.value;
625
1043
  if (!IMAGE_EXT_RE.test(importPath))
626
1044
  continue;
627
1045
  const name = importPath.split(/[\\/]/).pop().replace(IMAGE_EXT_RE, '');
628
- for (const specifier of stmt.specifiers) {
1046
+ const first = pathOf.get(name);
1047
+ if (first !== undefined && normalized(first) !== normalized(importPath)) {
1048
+ const error = aotError(`AOT: two images are named "${name}" (${first} and ${importPath})`, 'an image is named by its file name, so rename one of the files.');
1049
+ locateError(error, statement.loc?.start);
1050
+ throw error;
1051
+ }
1052
+ pathOf.set(name, importPath);
1053
+ for (const specifier of statement.specifiers) {
629
1054
  if (specifier.type === 'ImportDefaultSpecifier') {
630
1055
  byLocal.set(specifier.local.name, { name, importPath });
631
1056
  }
@@ -637,7 +1062,7 @@ export function collectImageImports(program) {
637
1062
  * Collects `import x from './foo.svg'` → Map(localName → { name, importPath }). Unlike an image (whose
638
1063
  * bytes the CLI bakes AFTER compile, so compile only needs its asset name), an <Svg source> needs the
639
1064
  * GEOMETRY during compile — so the CLI bakes the .svg to a vector artifact up front (bakeSvgArtifacts) and
640
- * passes it in as opts.svgArtifacts, keyed by `name`. emitSvgSource resolves the local → name → artifact.
1065
+ * passes it in as options.svgArtifacts, keyed by `name`. emitSvgSource resolves the local → name → artifact.
641
1066
  *
642
1067
  * @param program The parsed module.
643
1068
  *
@@ -646,19 +1071,19 @@ export function collectImageImports(program) {
646
1071
  export function collectSvgImports(program) {
647
1072
  // Map each default import of a .svg file to the file's basename.
648
1073
  const byLocal = new Map();
649
- for (const stmt of program.body) {
650
- if (stmt.type !== 'ImportDeclaration' ||
651
- typeof stmt.source.value !== 'string') {
1074
+ for (const statement of program.body) {
1075
+ if (statement.type !== 'ImportDeclaration' ||
1076
+ typeof statement.source.value !== 'string') {
652
1077
  continue;
653
1078
  }
654
- const importPath = stmt.source.value;
1079
+ const importPath = statement.source.value;
655
1080
  if (!/\.svg$/i.test(importPath))
656
1081
  continue;
657
1082
  const name = importPath
658
1083
  .split(/[\\/]/)
659
1084
  .pop()
660
1085
  .replace(/\.svg$/i, '');
661
- for (const specifier of stmt.specifiers) {
1086
+ for (const specifier of statement.specifiers) {
662
1087
  if (specifier.type === 'ImportDefaultSpecifier') {
663
1088
  byLocal.set(specifier.local.name, { name, importPath });
664
1089
  }
@@ -668,17 +1093,17 @@ export function collectSvgImports(program) {
668
1093
  }
669
1094
  /**
670
1095
  * Bakes a Flow B app's <Svg source> imports → { assetName: artifact } via the SAME baker Flow A's esbuild
671
- * .svg loader uses (svgToVector). This is the I/O half (reads .svg files) kept OUT of the pure compileSource;
672
- * both CLI entries (aot/compile.mts and the consumer cli.mjs) call it and hand the result to opts.svgArtifacts.
1096
+ * .svg loader uses (svgToVector). This is the I/O half (reads .svg files) kept OUT of the pure compilePackage;
1097
+ * both CLI entries (aot/compile.mts and the consumer cli.mjs) call it and hand the result to options.svgArtifacts.
673
1098
  *
674
- * @param src App.jsx source text.
675
- * @param baseDir Directory the import paths are resolved against (the app's dir).
1099
+ * @param source App.jsx source text.
1100
+ * @param baseDirectory Directory the import paths are resolved against (the app's dir).
676
1101
  *
677
1102
  * @returns Each import's artifact, by asset name: its op-tape, or a PNG for one the vector baker cannot draw.
678
1103
  */
679
- export async function bakeSvgArtifacts(src, baseDir) {
1104
+ export async function bakeSvgArtifacts(source, baseDirectory) {
680
1105
  // Parse with the TS plugin too (harmless for plain JSX), so a .tsx app's <Svg source> imports are found.
681
- const program = parse(src, {
1106
+ const program = parse(source, {
682
1107
  sourceType: 'module',
683
1108
  plugins: ['jsx', 'typescript'],
684
1109
  }).program;
@@ -690,7 +1115,7 @@ export async function bakeSvgArtifacts(src, baseDir) {
690
1115
  // Read each imported file and bake it to a vector op-tape.
691
1116
  const artifacts = {};
692
1117
  for (const [, svgImport] of imports) {
693
- const svgPath = resolve(baseDir, svgImport.importPath);
1118
+ const svgPath = resolve(baseDirectory, svgImport.importPath);
694
1119
  if (!existsSync(svgPath)) {
695
1120
  throw new Error(`AOT: <Svg source> asset "${svgImport.name}" not found at ${svgPath}`);
696
1121
  }
@@ -699,7 +1124,7 @@ export async function bakeSvgArtifacts(src, baseDir) {
699
1124
  const artifact = (await svgToVector(svgText));
700
1125
  if (artifact.dropped && artifact.dropped.length) {
701
1126
  console.warn(`embedded-react: ${svgImport.name}.svg uses unsupported SVG feature(s) [${artifact.dropped.join(', ')}] — ` +
702
- `rasterizing it as a fallback image (Flow B bakes the PNG into assets.generated.c). Simplify the SVG ` +
1127
+ `rasterising it as a fallback image (Flow B bakes the PNG into the package). Simplify the SVG ` +
703
1128
  `to keep it a live vector.`);
704
1129
  const { width, height, png } = await svgToRaster(svgText);
705
1130
  artifacts[svgImport.name] = {
@@ -718,79 +1143,153 @@ export async function bakeSvgArtifacts(src, baseDir) {
718
1143
  }
719
1144
  /**
720
1145
  * Collects `const fn = useCallback((...) => {...}, deps)` → Map (name → arrow fn node). Deps are ignored:
721
- * the AOT re-renders via its own dependency tracking, so useCallback only names a shared C handler.
1146
+ * the AOT re-renders via its own dependency tracking, so useCallback only names a shared handler.
722
1147
  *
723
- * @param fnBody The component's body.
1148
+ * @param functionBody The component's body.
724
1149
  *
725
1150
  * @returns The callbacks, by name.
726
1151
  */
727
- export function collectCallbacks(fnBody) {
1152
+ export function collectCallbacks(functionBody) {
728
1153
  const callbacks = new Map();
729
- if (fnBody.type !== 'BlockStatement')
1154
+ if (functionBody.type !== 'BlockStatement')
730
1155
  return callbacks;
731
1156
  // Collect top-level useCallback bindings whose first argument is an inline function, keyed by the variable name.
732
- for (const stmt of fnBody.body) {
733
- if (stmt.type !== 'VariableDeclaration')
1157
+ for (const statement of functionBody.body) {
1158
+ if (statement.type !== 'VariableDeclaration')
734
1159
  continue;
735
- for (const decl of stmt.declarations) {
736
- const init = decl.init;
737
- if (init?.type === 'CallExpression' &&
738
- init.callee.name === 'useCallback' &&
739
- decl.id.type === 'Identifier' &&
740
- isFn(init.arguments[0])) {
741
- callbacks.set(decl.id.name, init.arguments[0]);
1160
+ for (const declarator of statement.declarations) {
1161
+ const initializer = declarator.init;
1162
+ if (initializer?.type === 'CallExpression' &&
1163
+ initializer.callee.name === 'useCallback' &&
1164
+ declarator.id.type === 'Identifier' &&
1165
+ isFn(initializer.arguments[0])) {
1166
+ callbacks.set(declarator.id.name, initializer.arguments[0]);
742
1167
  }
743
1168
  }
744
1169
  }
745
1170
  return callbacks;
746
1171
  }
747
1172
  /**
748
- * Collects `const m = useMemo(() => expr, deps)` → Map (name → the memo's expression node).
1173
+ * The name a block-bodied memo is kept under as a helper. No binding can have it.
749
1174
  *
750
- * @param fnBody The component's body.
1175
+ * @param name The memo's name.
751
1176
  *
752
- * @returns Each memo's expression, by name.
1177
+ * @returns The helper's name.
753
1178
  */
754
- export function collectMemos(fnBody) {
755
- const memos = new Map();
756
- if (fnBody.type !== 'BlockStatement')
757
- return memos;
758
- // Collect expression-bodied useMemo bindings; block-bodied memos are rejected until statement-bodied folding is supported.
759
- for (const stmt of fnBody.body) {
760
- if (stmt.type !== 'VariableDeclaration')
1179
+ export const memoHelperName = (name) => `useMemo(${name})`;
1180
+ /**
1181
+ * Each `const m = useMemo(() => …, deps)` in a component's body, with its function.
1182
+ *
1183
+ * @param functionBody The component's body.
1184
+ *
1185
+ * @returns Each memo's name and function.
1186
+ */
1187
+ function memoFunctions(functionBody) {
1188
+ if (functionBody.type !== 'BlockStatement')
1189
+ return [];
1190
+ const found = [];
1191
+ for (const statement of functionBody.body) {
1192
+ if (statement.type !== 'VariableDeclaration')
761
1193
  continue;
762
- for (const decl of stmt.declarations) {
763
- const init = decl.init;
764
- if (init?.type === 'CallExpression' &&
765
- init.callee.name === 'useMemo' &&
766
- decl.id.type === 'Identifier' &&
767
- isFn(init.arguments[0])) {
768
- const body = init.arguments[0].body;
769
- if (body.type === 'BlockStatement') {
770
- throw new Error(`AOT: useMemo for "${decl.id.name}" must be a single expression (for now)`);
771
- }
772
- memos.set(decl.id.name, body);
1194
+ for (const declarator of statement.declarations) {
1195
+ const initializer = declarator.init;
1196
+ if (initializer?.type === 'CallExpression' &&
1197
+ initializer.callee.name === 'useMemo' &&
1198
+ declarator.id.type === 'Identifier' &&
1199
+ isFn(initializer.arguments[0])) {
1200
+ found.push([declarator.id.name, initializer.arguments[0]]);
773
1201
  }
774
1202
  }
775
1203
  }
1204
+ return found;
1205
+ }
1206
+ /**
1207
+ * Collects `const m = useMemo(() => expr, deps)` → Map (name → the memo's expression node). A block body is a call to
1208
+ * the helper collectHelpers keeps it as, so it is worked out as a helper's value is.
1209
+ *
1210
+ * @param functionBody The component's body.
1211
+ *
1212
+ * @returns Each memo's expression, by name.
1213
+ */
1214
+ export function collectMemos(functionBody) {
1215
+ const memos = new Map();
1216
+ for (const [name, { body }] of memoFunctions(functionBody)) {
1217
+ memos.set(name, body.type === 'BlockStatement'
1218
+ ? {
1219
+ type: 'CallExpression',
1220
+ callee: { type: 'Identifier', name: memoHelperName(name) },
1221
+ arguments: [],
1222
+ loc: body.loc,
1223
+ }
1224
+ : body);
1225
+ }
776
1226
  return memos;
777
1227
  }
1228
+ /**
1229
+ * Collects the `useNativeEvent(Module, 'event', handler)` calls at the top of a component's body. One anywhere else is
1230
+ * refused, as a hook React calls conditionally would be.
1231
+ *
1232
+ * @param functionBody The component's body.
1233
+ *
1234
+ * @returns The calls, in source order.
1235
+ */
1236
+ export function collectNativeEvents(functionBody) {
1237
+ const isSubscription = (node) => node?.type === 'CallExpression' &&
1238
+ node.callee.type === 'Identifier' &&
1239
+ node.callee.name === 'useNativeEvent';
1240
+ const calls = [];
1241
+ const topLevel = new Set();
1242
+ if (functionBody.type === 'BlockStatement') {
1243
+ for (const statement of functionBody.body) {
1244
+ if (statement.type === 'ExpressionStatement' &&
1245
+ isSubscription(statement.expression)) {
1246
+ calls.push(statement.expression);
1247
+ topLevel.add(statement.expression);
1248
+ }
1249
+ }
1250
+ }
1251
+ // Anywhere else: in a condition, a loop, a handler, or as a value.
1252
+ const refuseNested = (node) => {
1253
+ if (!node || typeof node !== 'object')
1254
+ return;
1255
+ if (Array.isArray(node)) {
1256
+ node.forEach(refuseNested);
1257
+ return;
1258
+ }
1259
+ const record = node;
1260
+ if (typeof record.type !== 'string')
1261
+ return;
1262
+ if (isSubscription(record) && !topLevel.has(record)) {
1263
+ const error = aotError('AOT: useNativeEvent() is called inside a condition, a loop, a function or an expression', 'call it as a statement at the top of the component, as React calls every hook.');
1264
+ if (record.loc)
1265
+ error.aotLoc = record.loc.start;
1266
+ throw error;
1267
+ }
1268
+ for (const key of Object.keys(record)) {
1269
+ if (key !== 'loc' && !key.endsWith('Comments')) {
1270
+ refuseNested(record[key]);
1271
+ }
1272
+ }
1273
+ };
1274
+ refuseNested(functionBody);
1275
+ return calls;
1276
+ }
778
1277
  /**
779
1278
  * Collects `useEffect(() => {…}, deps)` calls → { fn, deps, node }. Dep validity is checked at compile time.
780
1279
  *
781
- * @param fnBody The component's body.
1280
+ * @param functionBody The component's body.
782
1281
  *
783
1282
  * @returns The effects, in source order.
784
1283
  */
785
- export function collectEffects(fnBody) {
1284
+ export function collectEffects(functionBody) {
786
1285
  const effects = [];
787
- if (fnBody.type !== 'BlockStatement')
1286
+ if (functionBody.type !== 'BlockStatement')
788
1287
  return effects;
789
1288
  // Collect top-level useEffect calls, requiring an inline function so the effect body can be lowered later with its deps.
790
- for (const stmt of fnBody.body) {
791
- if (stmt.type !== 'ExpressionStatement')
1289
+ for (const statement of functionBody.body) {
1290
+ if (statement.type !== 'ExpressionStatement')
792
1291
  continue;
793
- const call = stmt.expression;
1292
+ const call = statement.expression;
794
1293
  if (call?.type === 'CallExpression' &&
795
1294
  call.callee.type === 'Identifier' &&
796
1295
  call.callee.name === 'useEffect') {
@@ -805,8 +1304,8 @@ export function collectEffects(fnBody) {
805
1304
  throw error;
806
1305
  }
807
1306
  effects.push({
808
- fn: call.arguments[0],
809
- deps: call.arguments[1],
1307
+ functionNode: call.arguments[0],
1308
+ dependencies: call.arguments[1],
810
1309
  node: call,
811
1310
  });
812
1311
  }
@@ -816,14 +1315,14 @@ export function collectEffects(fnBody) {
816
1315
  /**
817
1316
  * True if a function component declares any useState (per-instance child state — not yet supported).
818
1317
  *
819
- * @param fn The component.
1318
+ * @param functionNode The component.
820
1319
  *
821
1320
  * @returns Whether its body calls useState.
822
1321
  */
823
- export function usesState(fn) {
824
- if (fn.body.type !== 'BlockStatement')
1322
+ export function usesState(functionNode) {
1323
+ if (functionNode.body.type !== 'BlockStatement')
825
1324
  return false;
826
- return fn.body.body.some(statement => statement.type === 'VariableDeclaration' &&
827
- statement.declarations.some(decl => decl.init?.type === 'CallExpression' &&
828
- decl.init.callee.name === 'useState'));
1325
+ return functionNode.body.body.some(statement => statement.type === 'VariableDeclaration' &&
1326
+ statement.declarations.some(declarator => declarator.init?.type === 'CallExpression' &&
1327
+ ['useState', 'useReducer'].includes(declarator.init.callee.name)));
829
1328
  }