embedded-react 0.15.0 → 0.16.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 (57) hide show
  1. package/aot/compile.mjs +173 -8272
  2. package/aot/compiler/animations.mjs +1001 -0
  3. package/aot/compiler/assemble.mjs +806 -0
  4. package/aot/compiler/c/animations.mjs +362 -0
  5. package/aot/compiler/c/expressions.mjs +215 -0
  6. package/aot/compiler/c/functions.mjs +268 -0
  7. package/aot/compiler/c/keyboard.mjs +96 -0
  8. package/aot/compiler/c/nodes.mjs +282 -0
  9. package/aot/compiler/c/pan-responder.mjs +136 -0
  10. package/aot/compiler/c/statements.mjs +242 -0
  11. package/aot/compiler/c/text.mjs +83 -0
  12. package/aot/compiler/c/vectors.mjs +381 -0
  13. package/aot/compiler/c-syntax.mjs +127 -0
  14. package/aot/compiler/check.mjs +165 -0
  15. package/aot/compiler/collect.mjs +743 -0
  16. package/aot/compiler/control-flow.mjs +683 -0
  17. package/aot/compiler/diagnostics.mjs +137 -0
  18. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  19. package/aot/compiler/elements/dial.mjs +343 -0
  20. package/aot/compiler/elements/flat-list.mjs +139 -0
  21. package/aot/compiler/elements/image.mjs +151 -0
  22. package/aot/compiler/elements/modal.mjs +158 -0
  23. package/aot/compiler/elements/props.mjs +474 -0
  24. package/aot/compiler/elements/switch.mjs +183 -0
  25. package/aot/compiler/elements/text-input.mjs +171 -0
  26. package/aot/compiler/expressions.mjs +1479 -0
  27. package/aot/compiler/handlers.mjs +1072 -0
  28. package/aot/compiler/ir/animations.mjs +16 -0
  29. package/aot/compiler/ir/app.mjs +16 -0
  30. package/aot/compiler/ir/expressions.mjs +16 -0
  31. package/aot/compiler/ir/functions.mjs +16 -0
  32. package/aot/compiler/ir/keyboard.mjs +16 -0
  33. package/aot/compiler/ir/nodes.mjs +83 -0
  34. package/aot/compiler/ir/pan-responder.mjs +16 -0
  35. package/aot/compiler/ir/source.mjs +16 -0
  36. package/aot/compiler/ir/statements.mjs +16 -0
  37. package/aot/compiler/ir/text.mjs +16 -0
  38. package/aot/compiler/ir/types.mjs +185 -0
  39. package/aot/compiler/ir/vectors.mjs +16 -0
  40. package/aot/compiler/keyboard.mjs +152 -0
  41. package/aot/compiler/lower.mjs +282 -0
  42. package/aot/compiler/nodes.mjs +683 -0
  43. package/aot/compiler/options.mjs +55 -0
  44. package/aot/compiler/out.mjs +94 -0
  45. package/aot/compiler/pan-responder.mjs +354 -0
  46. package/aot/compiler/parse.mjs +300 -0
  47. package/aot/compiler/static-eval.mjs +228 -0
  48. package/aot/compiler/style-text.mjs +648 -0
  49. package/aot/compiler/svg.mjs +1167 -0
  50. package/aot/compiler/types.mjs +16 -0
  51. package/aot/screenshot-smoke.mjs +95 -55
  52. package/aot/style-map.mjs +366 -304
  53. package/cli.mjs +5 -8
  54. package/package.json +14 -6
  55. package/sim/embedded-react.wasm +0 -0
  56. package/src/embedded-react/FlatList.js +4 -4
  57. package/src/props.js +1 -1
@@ -0,0 +1,1072 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.js';
20
+ import { aotError, withLoc } from './diagnostics.mjs';
21
+ import { evalStatic } from './static-eval.mjs';
22
+ import { mix64Error, staticInt, isTime64, constDivisor, emitSourcedWide, lowerSource, lowerExpr, lowerExprWide, lowerText, } from './expressions.mjs';
23
+ import { isFn } from './collect.mjs';
24
+ import { isAnimatedCall, resolveAnim, animValues, lowerAnimateStart, stopWaitOwner, } from './animations.mjs';
25
+ import { svgNum, CAP_MAP, JOIN_MAP, arcTape, circleTape, rectTape, lineTape, checkedTapeNumber, checkVectorPaints, vectorPaintOf, } from './svg.mjs';
26
+ import { armedFlag } from './c/functions.mjs';
27
+ import { toCExpr } from './c/expressions.mjs';
28
+ import { INT, isConvertible64, isIntSlot, isTime, refType, slotOf, } from './ir/types.mjs';
29
+ /*----------------------------------------------------------------------------------------------------------------------
30
+ - Constants
31
+ ---------------------------------------------------------------------------------------------------------------------*/
32
+ /** The constant 0, which a remainder by 0 or ±1 stores. */
33
+ const ZERO = { kind: 'number', value: 0, type: INT };
34
+ /** Each updateVector shape key and the numbers its array takes, for errors. */
35
+ const UPDATE_VECTOR_ARGS = {
36
+ arc: '[cx, cy, r, startAngle, endAngle]',
37
+ circle: '[cx, cy, r]',
38
+ rect: '[x, y, width, height] or [x, y, width, height, rx, ry]',
39
+ line: '[x1, y1, x2, y2]',
40
+ };
41
+ /*----------------------------------------------------------------------------------------------------------------------
42
+ - Implementation
43
+ ---------------------------------------------------------------------------------------------------------------------*/
44
+ /**
45
+ * Lowers a list-state setter call (`setItems(...)`) to bounded list operations.
46
+ *
47
+ * @param listState The list state.
48
+ * @param nextList The setter's argument: the list's next value.
49
+ * @param env The expression environment.
50
+ *
51
+ * @returns The statements.
52
+ */
53
+ function lowerListOp(listState, nextList, env) {
54
+ const { cap: capacity, struct } = listState;
55
+ // setItems([...items, a, b]) — append; setItems([]) — clear.
56
+ if (nextList.type === 'ArrayExpression') {
57
+ if (nextList.elements.length === 0) {
58
+ return [{ kind: 'clearList', list: listState }];
59
+ }
60
+ const [firstElement, ...appendedItems] = nextList.elements;
61
+ if (firstElement?.type !== 'SpreadElement' ||
62
+ firstElement.argument.name !== listState.name) {
63
+ throw new Error(`AOT: a list literal must spread the current list first: [...${listState.name}, item]`);
64
+ }
65
+ // Each appended object literal fills the fields of the next free slot; a full list drops it.
66
+ const statements = [];
67
+ for (const item of appendedItems) {
68
+ if (item.type !== 'ObjectExpression') {
69
+ throw new Error('AOT: appended list items must be object literals');
70
+ }
71
+ const props = new Map(item.properties.map((prop) => [
72
+ prop.key.name ??
73
+ prop.key.value,
74
+ prop.value,
75
+ ]));
76
+ const values = [];
77
+ for (const field of struct.fields) {
78
+ const valueNode = props.get(field.key);
79
+ if (!valueNode)
80
+ continue;
81
+ if (field.kind === 'string') {
82
+ values.push({ field, text: lowerText(valueNode, env) });
83
+ }
84
+ else {
85
+ values.push({
86
+ field,
87
+ value: storeValue(lowerExpr(valueNode, env), field.kind),
88
+ });
89
+ }
90
+ }
91
+ statements.push({ kind: 'appendItem', list: listState, values });
92
+ }
93
+ return statements;
94
+ }
95
+ // slice(0, end) keeps the first items by JS rules: a negative end counts back, a large or missing one keeps all.
96
+ if (nextList.type === 'CallExpression' &&
97
+ nextList.callee.type === 'MemberExpression' &&
98
+ nextList.callee.object.name === listState.name &&
99
+ nextList.callee.property.name === 'slice') {
100
+ const [start, end] = nextList.arguments;
101
+ if (start && staticInt(start, env) !== 0) {
102
+ throw aotError(`AOT: only ${listState.name}.slice(0, end) is supported on a list`, `a list is a fixed C array and a count, so a slice can only drop items from the end — ` +
103
+ `e.g. ${listState.name}.slice(0, -1) drops the last one.`);
104
+ }
105
+ if (!end)
106
+ return [];
107
+ // Settle a constant end here, clamped to ±capacity (past which nothing changes), so it needs no 64-bit math.
108
+ const staticEnd = staticInt(end, env);
109
+ if (staticEnd !== null) {
110
+ const clampedEnd = Math.max(-capacity, Math.min(capacity, staticEnd));
111
+ if (clampedEnd === -1) {
112
+ return [{ kind: 'dropLastItem', list: listState }];
113
+ }
114
+ if (clampedEnd >= 0) {
115
+ return [{ kind: 'keepFirstItems', list: listState, count: clampedEnd }];
116
+ }
117
+ return [
118
+ {
119
+ kind: 'sliceItems',
120
+ list: listState,
121
+ end: { kind: 'number', value: clampedEnd, type: INT },
122
+ },
123
+ ];
124
+ }
125
+ // A runtime end goes through app_slice_len, which applies the same JS rules.
126
+ return [
127
+ { kind: 'sliceItems', list: listState, end: asInt(lowerExpr(end, env)) },
128
+ ];
129
+ }
130
+ throw new Error(`AOT: unsupported list operation on "${listState.name}" (use [...${listState.name}, ` +
131
+ `item], ${listState.name}.slice(0, n), or [])`);
132
+ }
133
+ /**
134
+ * Returns a statement node's body list: a BlockStatement's contents, or the lone statement wrapped.
135
+ *
136
+ * @param node An `if` branch.
137
+ *
138
+ * @returns Its statements.
139
+ */
140
+ function blockList(node) {
141
+ return node.type === 'BlockStatement' ? node.body : [node];
142
+ }
143
+ /**
144
+ * Checks a value written to a numeric state or ref slot, whose C type came from its initial value. Every value
145
+ * written to an int slot is recorded in env.stores, from which the typing pass infers the slots that hold a
146
+ * 64-bit timestamp, and compileWidened compiles again with those slots widened to int64_t. A timestamp cannot
147
+ * go into a float or boolean slot (a 64-bit constant can go into a float one), and a widened slot takes no
148
+ * floats.
149
+ *
150
+ * @param lowered The value: its source, and its type.
151
+ * @param slotType The slot's C kind.
152
+ * @param isBool The slot holds a boolean.
153
+ * @param widened What the slot holds, if it was widened to 64 bits.
154
+ * @param slotCName The slot's C name, for env.stores.
155
+ * @param slotDescription The slot, for the message.
156
+ * @param env The expression environment.
157
+ */
158
+ function storeCheck(lowered, slotType, isBool, widened, slotCName, slotDescription, env) {
159
+ const value = lowered.expr;
160
+ if ((slotType === 'int' && !isBool) || widened === 'number') {
161
+ env.stores.push({
162
+ slot: slotCName,
163
+ value: lowered.source,
164
+ math64: Boolean(env.math64),
165
+ });
166
+ }
167
+ if (value.type.kind === 'int64' && slotType !== 'i64') {
168
+ if (slotType === 'int' && !isBool)
169
+ return;
170
+ if (isConvertible64(value.type) && slotType === 'float')
171
+ return;
172
+ throw aotError(`AOT: a 64-bit time value cannot be stored in ${slotDescription}`, 'give it a whole-number initial value — useState(0) or useRef(0) — and it widens to hold the timestamp.');
173
+ }
174
+ if (slotType === 'i64' && value.type.kind === 'float') {
175
+ throw mix64Error();
176
+ }
177
+ }
178
+ /**
179
+ * `value` for an int destination. A float goes through app_f2i: C's own conversion is undefined behavior for
180
+ * NaN or a value past the int range.
181
+ *
182
+ * @param value The lowered value.
183
+ *
184
+ * @returns The value as an int.
185
+ */
186
+ const asInt = (value) => value.type.kind === 'float'
187
+ ? { kind: 'toInt', operand: value, type: INT }
188
+ : value;
189
+ /**
190
+ * `value` for a slot of `slotType`: an int slot takes a float the way asInt does.
191
+ *
192
+ * @param value The lowered value.
193
+ * @param slotType The slot's C kind.
194
+ *
195
+ * @returns The value the slot stores.
196
+ */
197
+ const storeValue = (value, slotType) => slotType === 'int' ? asInt(value) : value;
198
+ /**
199
+ * A read of a ref's current value.
200
+ *
201
+ * @param ref The ref.
202
+ *
203
+ * @returns The read.
204
+ */
205
+ const refRead = (ref) => ({
206
+ kind: 'ref',
207
+ ref,
208
+ type: refType(ref),
209
+ });
210
+ /**
211
+ * Lowers a write of an expression into a scalar state slot: text for a string buffer (so a `+` chain keeps its
212
+ * parts), a plain value otherwise.
213
+ *
214
+ * @param scalarState The state slot.
215
+ * @param valueNode The value.
216
+ * @param env The expression environment.
217
+ *
218
+ * @returns The write.
219
+ */
220
+ function lowerScalarSet(scalarState, valueNode, env) {
221
+ if (scalarState.cType !== 'string') {
222
+ // A 64-bit slot takes int `+ - *` worked out in 64 bits.
223
+ const lowered = lowerSource(valueNode, scalarState.cType === 'i64' ? { ...env, math64: true } : env);
224
+ const value = lowered.expr;
225
+ storeCheck(lowered, scalarState.cType, scalarState.isBool, scalarState.widened, scalarState.cField, `state "${scalarState.name}"`, env);
226
+ return {
227
+ kind: 'setState',
228
+ state: scalarState,
229
+ value: storeValue(value, scalarState.cType),
230
+ };
231
+ }
232
+ return {
233
+ kind: 'setStateText',
234
+ state: scalarState,
235
+ text: lowerText(valueNode, env),
236
+ };
237
+ }
238
+ /**
239
+ * Resolves `node` to its ref when it is `<ref>.current` member access on a known value ref.
240
+ *
241
+ * @param node An assignment or update target.
242
+ * @param env The expression environment.
243
+ *
244
+ * @returns The ref, marked used, or null when the node is not such an access.
245
+ */
246
+ function refTarget(node, env) {
247
+ if (node?.type === 'MemberExpression' &&
248
+ !node.computed &&
249
+ node.object.type === 'Identifier' &&
250
+ node.property.name === 'current' &&
251
+ env.refs?.has(node.object.name)) {
252
+ const ref = env.refs.get(node.object.name);
253
+ ref.used = true;
254
+ return ref;
255
+ }
256
+ return null;
257
+ }
258
+ /**
259
+ * An imperative updateVector shape `{ arc:[…]|circle:[…]|rect:[x, y, w, h, rx?, ry?]|line:[…]|path:'…', fill, … }`:
260
+ * its tape slots, the locals they need, and its static paint. Geometry coords may reference state, refs or event
261
+ * fields; the paint must be static. The geometry is the same as the JSX path's. `tag` names any locals and must
262
+ * be unique in the handler block they are written into.
263
+ *
264
+ * @param shapeNode The shape's object literal.
265
+ * @param env The expression environment.
266
+ * @param tag Names the shape's locals.
267
+ *
268
+ * @returns The shape's tape slots, the locals they need, and its paint.
269
+ */
270
+ function imperativeShape(shapeNode, env, tag) {
271
+ // Index the shape's properties by name.
272
+ if (shapeNode?.type !== 'ObjectExpression') {
273
+ throw new Error('AOT: each updateVector shape must be an object literal');
274
+ }
275
+ const props = {};
276
+ for (const prop of shapeNode.properties) {
277
+ if (prop.type !== 'ObjectProperty') {
278
+ throw new Error('AOT: spread/method in an updateVector shape not supported');
279
+ }
280
+ props[prop.key.name ?? prop.key.value] = prop.value;
281
+ }
282
+ // Lower whichever geometry key is present; array numbers may be runtime values, a path string must be static.
283
+ const geometryArgs = (key, count, required = count) => {
284
+ if (props[key].type !== 'ArrayExpression') {
285
+ throw new Error(`AOT: updateVector "${key}" must be an array literal`);
286
+ }
287
+ const elements = props[key].elements;
288
+ const shapeHint = `${key}: ${UPDATE_VECTOR_ARGS[key]}.`;
289
+ if (elements.length < required) {
290
+ throw aotError(`AOT: updateVector "${key}" needs ${required} numbers (got ${elements.length})`, shapeHint);
291
+ }
292
+ // A hole (`[1, , 3]`) has no value to lower; an optional rect radius left out is just a shorter array.
293
+ const values = elements.slice(0, count);
294
+ const hole = values.findIndex(valueNode => valueNode == null);
295
+ if (hole >= 0) {
296
+ throw aotError(`AOT: updateVector "${key}" has an empty slot at position ${hole}`, shapeHint);
297
+ }
298
+ return values.map(valueNode => ({
299
+ kind: 'float',
300
+ value: lowerExpr(valueNode, env),
301
+ }));
302
+ };
303
+ let geometry;
304
+ if (props.arc) {
305
+ const [cx, cy, radius, startDeg, endDeg] = geometryArgs('arc', 5);
306
+ geometry = { entries: arcTape(cx, cy, radius, startDeg, endDeg), locals: [] };
307
+ }
308
+ else if (props.circle) {
309
+ const [cx, cy, radius] = geometryArgs('circle', 3);
310
+ geometry = { entries: circleTape(cx, cy, radius), locals: [] };
311
+ }
312
+ else if (props.rect) {
313
+ const [x, y, width, height, rx = null, ry = null] = geometryArgs('rect', 6, 4);
314
+ geometry = rectTape(x, y, width, height, rx, ry, tag);
315
+ }
316
+ else if (props.line) {
317
+ const [x1, y1, x2, y2] = geometryArgs('line', 4);
318
+ geometry = { entries: lineTape(x1, y1, x2, y2), locals: [] };
319
+ }
320
+ else if (props.path) {
321
+ geometry = {
322
+ entries: parsePath(String(evalStatic(props.path, env.consts ?? {}))).map((value) => checkedTapeNumber(value)),
323
+ locals: [],
324
+ };
325
+ }
326
+ else {
327
+ throw new Error('AOT: an updateVector shape needs one of arc / circle / rect / line / path');
328
+ }
329
+ // Fold the paint to its static record: fill, stroke, stroke width, miter limit, cap, join, fill rule.
330
+ const paintValue = (key, fallback) => {
331
+ if (props[key] == null)
332
+ return fallback;
333
+ try {
334
+ return evalStatic(props[key], env.consts ?? {});
335
+ }
336
+ catch {
337
+ throw new Error(`AOT: updateVector paint "${key}" must be static`);
338
+ }
339
+ };
340
+ const paint = vectorPaintOf([
341
+ parseColor(paintValue('fill', 'none')),
342
+ parseColor(paintValue('stroke', 'none')),
343
+ svgNum(paintValue('strokeWidth', 1), 1),
344
+ svgNum(paintValue('miter', 4), 4),
345
+ CAP_MAP[paintValue('cap', 'butt')] ?? 0,
346
+ JOIN_MAP[paintValue('join', 'miter')] ?? 0,
347
+ paintValue('fillRule', 'nonzero') === 'evenodd' ? 1 : 0,
348
+ ]);
349
+ return { ...geometry, paint };
350
+ }
351
+ /**
352
+ * Lowers `updateVector(nodeRef, shapes, [x,y,w,h]?)`: fill a mutable op-tape, push it to the node, and
353
+ * (optionally) hint the dirty sub-rect — the imperative fast path (drag) that bypasses app_update. The call's
354
+ * tables are declared at file scope here.
355
+ *
356
+ * @param expr The updateVector call.
357
+ * @param env The expression environment.
358
+ * @param ctx The statement compiler's context.
359
+ *
360
+ * @returns The statement.
361
+ */
362
+ function lowerUpdateVector(expr, env, ctx) {
363
+ // The first argument must be a node ref, and the second an array literal of shapes.
364
+ const out = ctx.out;
365
+ const [refArg, shapesArg, dirtyArg] = expr.arguments;
366
+ const ref = refArg?.type === 'Identifier' ? env.refs?.get(refArg.name) : null;
367
+ if (ref?.kind !== 'node') {
368
+ throw new Error('AOT: updateVector(ref, …) first arg must be a node ref (const r = useRef())');
369
+ }
370
+ ref.used = true;
371
+ if (shapesArg?.type !== 'ArrayExpression') {
372
+ throw new Error('AOT: updateVector(ref, shapes, …) shapes must be an array literal');
373
+ }
374
+ // Claim the id first so two updateVector calls in one handler get distinct locals, then lower each shape.
375
+ const vectorId = out.svgN++;
376
+ const update = {
377
+ kind: 'updateVector',
378
+ id: vectorId,
379
+ node: ref.cVar,
380
+ locals: [],
381
+ tape: [],
382
+ paints: [],
383
+ dirty: null,
384
+ };
385
+ for (const shapeNode of shapesArg.elements) {
386
+ const shape = imperativeShape(shapeNode, env, `uv${vectorId}_${update.paints.length}`);
387
+ update.locals.push(...shape.locals);
388
+ update.tape.push({ kind: 'op', op: 'ER_VOP_SHAPE' }, checkedTapeNumber(update.paints.length), ...shape.entries);
389
+ update.paints.push(shape.paint);
390
+ }
391
+ // Declare the op-tape and its paint table at file scope.
392
+ checkVectorPaints(update.paints);
393
+ out.needsMath = true;
394
+ out.vectors.push({ kind: 'updateVector', update });
395
+ // Hint the dirty sub-rect when the call gives one.
396
+ if (dirtyArg) {
397
+ if (dirtyArg.type !== 'ArrayExpression' || dirtyArg.elements.length < 4) {
398
+ throw new Error('AOT: updateVector dirtyRect must be a [x, y, w, h] array literal');
399
+ }
400
+ update.dirty = dirtyArg.elements
401
+ .slice(0, 4)
402
+ .map(edgeNode => lowerExpr(edgeNode, env));
403
+ }
404
+ return update;
405
+ }
406
+ /**
407
+ * Lowers setInterval/setTimeout(cb, ms) to a timer, and registers cb as a timer function of its own.
408
+ *
409
+ * @param expr The setInterval / setTimeout call.
410
+ * @param env The expression environment.
411
+ * @param state The component's state table.
412
+ * @param ctx The statement compiler's context.
413
+ *
414
+ * @returns The timer.
415
+ */
416
+ function lowerTimer(expr, env, state, ctx) {
417
+ const cb = expr.arguments[0];
418
+ if (!isFn(cb)) {
419
+ throw aotError('AOT: a setInterval/setTimeout callback must be an inline function', 'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).');
420
+ }
421
+ // Any delay is accepted here; the printer converts a timestamp or float one the way Flow A's setTimeout does.
422
+ const delay = expr.arguments[1]
423
+ ? lowerExprWide(expr.arguments[1], env)
424
+ : null;
425
+ const isRepeating = expr.callee.name === 'setInterval';
426
+ // Reserve the timer's slot before compiling its body, which may add timers of its own.
427
+ const slot = ctx.out.timerFns.length;
428
+ const timerFnName = `er_timer_fn_${slot}`;
429
+ ctx.out.usesTimers = true;
430
+ ctx.out.timerFns.push({ name: timerFnName, callback: null });
431
+ ctx.out.timerFns[slot].callback = lowerHandler(cb, env, state, ctx.out);
432
+ return { delay, isRepeating, fn: timerFnName };
433
+ }
434
+ /**
435
+ * Inlines a handler-statement call to a helper / useCallback: binds the call's args to the helper's params
436
+ * as locals, then lowers the helper body here in the current env/state/ctx. Guards against recursion.
437
+ *
438
+ * @param helperName The helper's name.
439
+ * @param helper The helper.
440
+ * @param args The call's arguments.
441
+ * @param env The expression environment.
442
+ * @param state The component's state table.
443
+ * @param ctx The statement compiler's context.
444
+ *
445
+ * @returns The helper's body as statements.
446
+ */
447
+ function inlineHelperCall(helperName, helper, args, env, state, ctx) {
448
+ // A helper already being inlined further up this call chain is recursive.
449
+ ctx.inlining = ctx.inlining ?? new Set();
450
+ if (ctx.inlining.has(helperName)) {
451
+ throw aotError(`AOT: helper "${helperName}" is recursive — can't be inlined into a handler`, 'handlers are flattened to straight-line C, so a helper that calls itself (directly ' +
452
+ 'or via another helper) has no base case to unroll. Move recursive logic out of the ' +
453
+ 'handler, or precompute the value.');
454
+ }
455
+ // Bind each passed argument to its parameter as a local holding the argument's C expression.
456
+ const locals = new Map(env.locals);
457
+ helper.params.forEach((param, paramIndex) => {
458
+ if (param.type !== 'Identifier') {
459
+ 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) => …`) ' +
460
+ '— destructuring or default params in the signature are not supported.');
461
+ }
462
+ if (args[paramIndex]) {
463
+ const argExpr = emitSourcedWide(args[paramIndex], env);
464
+ locals.set(param.name, {
465
+ code: argExpr.code,
466
+ cType: argExpr.cType,
467
+ isBool: argExpr.isBool,
468
+ lit: argExpr.lit,
469
+ wide: argExpr.wide,
470
+ source: argExpr.source,
471
+ });
472
+ }
473
+ });
474
+ // An expression body is a single statement.
475
+ const body = helper.body;
476
+ const statements = body.type === 'BlockStatement'
477
+ ? body.body
478
+ : [{ type: 'ExpressionStatement', expression: body }];
479
+ // The body is spliced into the caller, so reject its `return`, even in an effect body where one is allowed.
480
+ const outerAllowReturn = ctx.allowReturn;
481
+ ctx.inlining.add(helperName);
482
+ ctx.allowReturn = false;
483
+ try {
484
+ return lowerStmts(statements, { ...env, locals }, state, ctx);
485
+ }
486
+ finally {
487
+ ctx.allowReturn = outerAllowReturn;
488
+ ctx.inlining.delete(helperName);
489
+ }
490
+ }
491
+ /**
492
+ * Lowers one handler ExpressionStatement: a state setter, ref mutation, timer, updateVector, helper call, or
493
+ * Animated.*(...).start() / .stop() (see lowerHandlerExpr, the located entry point).
494
+ *
495
+ * @param expr The statement's expression.
496
+ * @param env The expression environment.
497
+ * @param state The component's state table.
498
+ * @param ctx The statement compiler's context.
499
+ *
500
+ * @returns The statements.
501
+ */
502
+ function lowerHandlerExprImpl(expr, env, state, ctx) {
503
+ // updateVector(ref, shapes, dirtyRect?) — imperative vector redraw (no app_update).
504
+ if (expr.type === 'CallExpression' &&
505
+ expr.callee.type === 'Identifier' &&
506
+ expr.callee.name === 'updateVector') {
507
+ return [lowerUpdateVector(expr, env, ctx)];
508
+ }
509
+ // setInterval / setTimeout(cb, ms) → register a host-tick timer (the returned id is discarded here).
510
+ if (expr.type === 'CallExpression' &&
511
+ expr.callee.type === 'Identifier' &&
512
+ (expr.callee.name === 'setInterval' || expr.callee.name === 'setTimeout')) {
513
+ return [
514
+ {
515
+ kind: 'startTimer',
516
+ timer: lowerTimer(expr, env, state, ctx),
517
+ idLocal: null,
518
+ },
519
+ ];
520
+ }
521
+ // clearInterval / clearTimeout(id) → deactivate the timer slot.
522
+ if (expr.type === 'CallExpression' &&
523
+ expr.callee.type === 'Identifier' &&
524
+ (expr.callee.name === 'clearInterval' ||
525
+ expr.callee.name === 'clearTimeout')) {
526
+ return [{ kind: 'clearTimer', id: asInt(lowerExpr(expr.arguments[0], env)) }];
527
+ }
528
+ // `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
529
+ if (expr.type === 'AssignmentExpression') {
530
+ const ref = refTarget(expr.left, env);
531
+ if (!ref) {
532
+ throw new Error('AOT: the only assignment allowed in a handler is `ref.current = ...`');
533
+ }
534
+ // Lower the right side in the ref's width and check it fits; a 64-bit `%=` keeps its constant divisor.
535
+ const refEnv = ref.cType === 'i64' ? { ...env, math64: true } : env;
536
+ const loweredValue = lowerSource(expr.right, refEnv);
537
+ const valueExpr = loweredValue.expr;
538
+ const refHoldsTime = isTime(refType(ref));
539
+ if (expr.operator === '/=' && (refHoldsTime || isTime64(valueExpr))) {
540
+ 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.');
541
+ }
542
+ const wideModDivisor = expr.operator === '%=' && (refHoldsTime || isTime64(valueExpr))
543
+ ? constDivisor(expr.right, env)
544
+ : null;
545
+ storeCheck(loweredValue, ref.cType, false, ref.kind === 'value' ? ref.widened : undefined, ref.cVar, `ref "${expr.left.object.name}"`, env);
546
+ // Lower whole-ref `+= -= *=`, float `/=` and float `%=` as the binary op to share its checked and float math.
547
+ const isWholeRef = ref.cType === 'int' || ref.cType === 'i64';
548
+ const binaryOp = { '+=': '+', '-=': '-', '*=': '*' }[expr.operator];
549
+ const isFloatMod = expr.operator === '%=' &&
550
+ (ref.cType === 'float' || valueExpr.type.kind === 'float');
551
+ if ((isWholeRef &&
552
+ (binaryOp ||
553
+ (expr.operator === '/=' && valueExpr.type.kind === 'float'))) ||
554
+ isFloatMod) {
555
+ const resultExpr = lowerExprWide({
556
+ type: 'BinaryExpression',
557
+ operator: binaryOp ?? expr.operator.slice(0, -1),
558
+ left: expr.left,
559
+ right: expr.right,
560
+ loc: expr.loc,
561
+ }, refEnv);
562
+ return [
563
+ {
564
+ kind: 'writeRef',
565
+ ref,
566
+ op: '=',
567
+ value: storeValue(resultExpr, ref.cType),
568
+ },
569
+ ];
570
+ }
571
+ // Whole-number `/=` and `%=` use app_div/app_mod for JS's answer, in 64 bits on a 64-bit ref that holds no
572
+ // time; a constant divisor other than 0 or -1 needs no check.
573
+ const isWholeValue = isIntSlot(valueExpr.type) ||
574
+ (valueExpr.type.kind === 'int64' && !isTime64(valueExpr));
575
+ const refBits = ref.cType === 'i64' ? 64 : 32;
576
+ if (((ref.cType === 'int' && isIntSlot(valueExpr.type)) ||
577
+ (ref.cType === 'i64' && !refHoldsTime && isWholeValue)) &&
578
+ (expr.operator === '/=' || expr.operator === '%=')) {
579
+ const staticDivisor = staticInt(expr.right, env);
580
+ if (expr.operator === '/=' &&
581
+ (staticDivisor === null || staticDivisor === 0 || staticDivisor === -1)) {
582
+ return [
583
+ {
584
+ kind: 'writeRef',
585
+ ref,
586
+ op: '=',
587
+ value: {
588
+ kind: 'helper',
589
+ helper: 'div',
590
+ bits: refBits,
591
+ args: [refRead(ref), valueExpr],
592
+ type: refType(ref),
593
+ },
594
+ },
595
+ ];
596
+ }
597
+ if (expr.operator === '%=' &&
598
+ (staticDivisor === 0 || staticDivisor === -1)) {
599
+ return [{ kind: 'writeRef', ref, op: '=', value: ZERO }];
600
+ }
601
+ if (expr.operator === '%=' && staticDivisor === null) {
602
+ return [
603
+ {
604
+ kind: 'writeRef',
605
+ ref,
606
+ op: '=',
607
+ value: {
608
+ kind: 'helper',
609
+ helper: 'mod',
610
+ bits: refBits,
611
+ args: [refRead(ref), valueExpr],
612
+ type: refType(ref),
613
+ },
614
+ },
615
+ ];
616
+ }
617
+ }
618
+ // A 64-bit `%=` by 0 or ±1 stores 0: no remainder, JS's NaN as 0, and no C overflow on INT64_MIN % -1.
619
+ if (wideModDivisor === 0 || wideModDivisor === 1 || wideModDivisor === -1) {
620
+ return [{ kind: 'writeRef', ref, op: '=', value: ZERO }];
621
+ }
622
+ // Everything else is a plain assignment or compound assignment.
623
+ return [
624
+ {
625
+ kind: 'writeRef',
626
+ ref,
627
+ op: expr.operator,
628
+ value: expr.operator === '='
629
+ ? storeValue(valueExpr, ref.cType)
630
+ : valueExpr,
631
+ },
632
+ ];
633
+ }
634
+ // `ref.current++` / `ref.current--`; a whole-number ref steps through the checked `+ 1` / `- 1`.
635
+ if (expr.type === 'UpdateExpression') {
636
+ const ref = refTarget(expr.argument, env);
637
+ if (!ref) {
638
+ throw new Error('AOT: the only ++/-- allowed in a handler is on `ref.current`');
639
+ }
640
+ if (ref.cType === 'int' || ref.cType === 'i64') {
641
+ return [
642
+ {
643
+ kind: 'writeRef',
644
+ ref,
645
+ op: '=',
646
+ value: {
647
+ kind: 'helper',
648
+ helper: expr.operator === '++' ? 'add' : 'sub',
649
+ bits: ref.cType === 'i64' ? 64 : 32,
650
+ args: [refRead(ref), { kind: 'number', value: 1, type: INT }],
651
+ type: refType(ref),
652
+ },
653
+ },
654
+ ];
655
+ }
656
+ return [{ kind: 'stepRef', ref, op: expr.operator }];
657
+ }
658
+ // `anim.stop()` freezes each driven value; the cancel reports !finished, which ends any sequence or loop chain.
659
+ if (expr.type === 'CallExpression' &&
660
+ expr.callee.type === 'MemberExpression' &&
661
+ expr.callee.property.name === 'stop' &&
662
+ isAnimatedCall(resolveAnim(expr.callee.object, env))) {
663
+ return [
664
+ {
665
+ kind: 'stopAnimations',
666
+ handles: [...animValues(expr.callee.object, env)],
667
+ waitOwner: stopWaitOwner(expr.callee.object, env, ctx),
668
+ },
669
+ ];
670
+ }
671
+ // Animated.*(…).start(), atomic or composed, is native-driven, so it sets no state and needs no app_update.
672
+ if (expr.type === 'CallExpression' &&
673
+ expr.callee.type === 'MemberExpression' &&
674
+ expr.callee.property.name === 'start') {
675
+ return [lowerAnimateStart(expr, env, state, ctx)];
676
+ }
677
+ // What is left must be a plain call: to a helper or a state setter.
678
+ if (expr.type !== 'CallExpression' || expr.callee.type !== 'Identifier') {
679
+ throw aotError('AOT: a handler statement must be a state setter, a ref write, or Animated.timing/spring(...).start()', 'each statement in a handler must be one of: setX(value) / setX(prev => …), a ' +
680
+ '`ref.current = …` write, an `updateVector(…)` call, or `Animated.timing|spring(v, ' +
681
+ '…).start()`. Wrap conditional logic in `if (…) { … }`.');
682
+ }
683
+ // A call to a helper / useCallback (e.g. `reset();`) → inline its body here so handlers can compose logic.
684
+ const helperFn = env.helpers?.get(expr.callee.name) ?? env.callbacks?.get(expr.callee.name);
685
+ if (helperFn) {
686
+ return inlineHelperCall(expr.callee.name, helperFn, expr.arguments, env, state, ctx);
687
+ }
688
+ // A state setter. Flag the state change, which tells the caller to re-apply state once the body is done.
689
+ const targetState = state.bySetter.get(expr.callee.name);
690
+ if (!targetState) {
691
+ throw aotError(`AOT: "${expr.callee.name}" is not a known state setter`, `a handler can only call a setter from this component's own useState (e.g. setCount), ` +
692
+ `a ref write, updateVector(…), or Animated…start(). "${expr.callee.name}" isn't one ` +
693
+ `of those — arbitrary functions (fetch, console.*, helpers) can't be lowered to C.`);
694
+ }
695
+ ctx.stateChanged = true;
696
+ const setterArg = expr.arguments[0];
697
+ if (targetState.kind === 'list') {
698
+ return lowerListOp(targetState, setterArg, env);
699
+ }
700
+ // A scalar setter takes either an updater function or the new value itself.
701
+ if (setterArg &&
702
+ (setterArg.type === 'ArrowFunctionExpression' ||
703
+ setterArg.type === 'FunctionExpression')) {
704
+ // setState(prev => expr): bind the param to the current value, typed as a read of it, and assign the result.
705
+ const prevParam = setterArg.params[0]?.name;
706
+ const locals = new Map(env.locals);
707
+ if (prevParam) {
708
+ locals.set(prevParam, {
709
+ code: targetState.cMember,
710
+ cType: targetState.cType,
711
+ isBool: targetState.isBool,
712
+ ...(targetState.widened === 'number' ? { lit: true } : {}),
713
+ source: { kind: 'state', state: targetState, loc: undefined },
714
+ });
715
+ }
716
+ if (setterArg.body.type === 'BlockStatement') {
717
+ throw new Error('AOT: updater function must be a single expression (for now)');
718
+ }
719
+ return [lowerScalarSet(targetState, setterArg.body, { ...env, locals })];
720
+ }
721
+ return [lowerScalarSet(targetState, setterArg, env)];
722
+ }
723
+ /** lowerHandlerExprImpl, with the expression's source location attached to any AOT error it throws. */
724
+ const lowerHandlerExpr = withLoc(lowerHandlerExprImpl);
725
+ /**
726
+ * Lowers a list of handler statements to the IR. This one-statement lowering runs event handlers, effect bodies
727
+ * (useEffect), timer callbacks, and inlined helper calls. Supports: `const x = expr` (a local, visible to later
728
+ * statements), `if (cond) {...} else {...}`, state setters (list setters included), ref writes, timers,
729
+ * updateVector() and Animated.*(...).start(). `ctx` accumulates `stateChanged` (→ trailing app_update),
730
+ * `animIdx` (unique ERAnimConfig locals) and `usedReturn` (an early `return` was lowered, so the body needs a C
731
+ * function of its own). `ctx.allowReturn` and `ctx.bodyList` mark which body a `return` may exit and which
732
+ * statement of it is the tail.
733
+ *
734
+ * @param statements The statements.
735
+ * @param env The expression environment.
736
+ * @param state The component's state table.
737
+ * @param ctx The statement compiler's context.
738
+ *
739
+ * @returns The lowered statements.
740
+ */
741
+ export function lowerStmts(statements, env, state, ctx) {
742
+ const lowered = [];
743
+ for (let statementIndex = 0; statementIndex < statements.length; statementIndex++) {
744
+ const statement = statements[statementIndex];
745
+ // `const x = …` declares a local that the statements after it can read.
746
+ if (statement.type === 'VariableDeclaration') {
747
+ for (const decl of statement.declarations) {
748
+ if (decl.id.type !== 'Identifier') {
749
+ throw new Error('AOT: destructuring a handler local is not supported');
750
+ }
751
+ if (!decl.init) {
752
+ throw new Error('AOT: a handler local must have an initializer');
753
+ }
754
+ // `const anim = Animated.…` holds no C value; `anim.start()`/`anim.stop()` compile the animation it names.
755
+ if (isAnimatedCall(decl.init)) {
756
+ const locals = new Map(env.locals);
757
+ locals.delete(decl.id.name);
758
+ env = {
759
+ ...env,
760
+ locals,
761
+ animLocals: new Map(env.animLocals).set(decl.id.name, decl.init),
762
+ };
763
+ continue;
764
+ }
765
+ // A dep-driven effect's cleanup outlives the call, so the body's locals become file-scope slots.
766
+ const isHoisted = Boolean(ctx.hoist && statements === ctx.bodyList);
767
+ const cName = isHoisted
768
+ ? `${ctx.hoist.prefix}${decl.id.name}`
769
+ : `l_${decl.id.name}`;
770
+ // `const id = setInterval/setTimeout(…)` is an int timer-id local, so a later clearInterval(id) resolves.
771
+ if (decl.init.type === 'CallExpression' &&
772
+ decl.init.callee.type === 'Identifier' &&
773
+ (decl.init.callee.name === 'setInterval' ||
774
+ decl.init.callee.name === 'setTimeout')) {
775
+ // The id is only needed for a later clear*(); a mount effect drops its cleanup, so mark it used.
776
+ if (isHoisted) {
777
+ ctx.hoist.decls.push({ kind: 'local', name: cName, cType: 'int' });
778
+ }
779
+ lowered.push({
780
+ kind: 'startTimer',
781
+ timer: lowerTimer(decl.init, env, state, ctx),
782
+ idLocal: { name: cName, isHoisted },
783
+ });
784
+ env = {
785
+ ...env,
786
+ locals: new Map(env.locals).set(decl.id.name, {
787
+ code: cName,
788
+ cType: 'int',
789
+ }),
790
+ };
791
+ continue;
792
+ }
793
+ // Any other initializer must lower to a number, a boolean or a string.
794
+ const { source: initSource, expr: initExpr } = lowerSource(decl.init, env);
795
+ if (initExpr.type.kind === 'string') {
796
+ // Copy into a buffer of its own; aliasing a state slot would hide a self-read like `setLabel(t + '!')`.
797
+ if (isHoisted) {
798
+ ctx.hoist.decls.push({
799
+ kind: 'local',
800
+ name: cName,
801
+ cType: 'string',
802
+ });
803
+ }
804
+ }
805
+ else {
806
+ const slot = slotOf(initExpr.type);
807
+ if (slot !== 'int' && slot !== 'float' && slot !== 'i64') {
808
+ 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.');
809
+ }
810
+ if (isHoisted) {
811
+ ctx.hoist.decls.push({
812
+ kind: 'local',
813
+ name: cName,
814
+ cType: slot,
815
+ });
816
+ }
817
+ }
818
+ lowered.push({
819
+ kind: 'declareLocal',
820
+ name: cName,
821
+ init: initExpr,
822
+ isHoisted,
823
+ stringCap: env.caps.listStrCap,
824
+ });
825
+ // Later statements read the name as the C local.
826
+ env = {
827
+ ...env,
828
+ locals: new Map(env.locals).set(decl.id.name, {
829
+ ...toCExpr(initExpr),
830
+ code: cName,
831
+ source: initSource,
832
+ }),
833
+ };
834
+ }
835
+ continue;
836
+ }
837
+ // A tail `return` is the cleanup, dropped on mount and armed if dep-driven; an earlier one is a guard.
838
+ if (statement.type === 'ReturnStatement') {
839
+ if (!ctx.allowReturn) {
840
+ 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.');
841
+ if (statement.loc) {
842
+ error.aotLoc = statement.loc.start;
843
+ }
844
+ throw error;
845
+ }
846
+ const isTail = statements === ctx.bodyList && statementIndex === statements.length - 1;
847
+ if (ctx.depDriven && isFn(statement.argument) && !isTail) {
848
+ 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 ' +
849
+ 'guard and put the single `return () => …` at the end of the body.');
850
+ if (statement.loc) {
851
+ error.aotLoc = statement.loc.start;
852
+ }
853
+ throw error;
854
+ }
855
+ if (isTail) {
856
+ if (ctx.cleanup && isFn(statement.argument)) {
857
+ ctx.cleanup.emit(statement.argument, env);
858
+ lowered.push({ kind: 'armCleanup', flag: ctx.cleanup.armed });
859
+ }
860
+ continue;
861
+ }
862
+ ctx.usedReturn = true;
863
+ lowered.push({ kind: 'return' });
864
+ continue;
865
+ }
866
+ // `if (…) { … } else { … }` lowers each branch in order: the test, then the consequent, then the alternate.
867
+ if (statement.type === 'IfStatement') {
868
+ const test = lowerExprWide(statement.test, env);
869
+ const consequent = lowerStmts(blockList(statement.consequent), env, state, ctx);
870
+ const alternate = statement.alternate
871
+ ? lowerStmts(blockList(statement.alternate), env, state, ctx)
872
+ : null;
873
+ lowered.push({ kind: 'if', test, consequent, alternate });
874
+ continue;
875
+ }
876
+ // Anything else must be an expression statement: a setter call, a ref write, a timer, and so on.
877
+ if (statement.type !== 'ExpressionStatement') {
878
+ throw aotError(`AOT: unsupported statement "${statement.type}" in event handler`, 'a handler supports only `const x = …` locals, `if (…) { … } else { … }`, and ' +
879
+ 'expression statements (setters / ref writes / updateVector / Animated…start). Loops ' +
880
+ '(for/while), switch and try/catch are not lowered — precompute values or flatten the ' +
881
+ 'logic into if/else.');
882
+ }
883
+ lowered.push(...lowerHandlerExpr(statement.expression, env, state, ctx));
884
+ }
885
+ return lowered;
886
+ }
887
+ /**
888
+ * Lowers a useEffect (App or child). Two shapes:
889
+ * - `useEffect(fn, [])` — MOUNT-ONCE: body runs after the initial app_update (in er_app_build).
890
+ * - `useEffect(fn, [dep…])` — DEP-DRIVEN: body becomes a file-scope `er_effect_N()`; runs once at mount,
891
+ * then again from app_update whenever a SCALAR dep changes (compared against a stored prev). The body is
892
+ * compiled WITHOUT a trailing app_update — it runs INSIDE app_update / at mount, so re-applying state it
893
+ * sets happens on the next app_update (one-frame), and it can never re-enter app_update (no infinite loop).
894
+ * A dep-driven `return () => …` becomes `er_effect_N_cleanup()`, run at the top of the next re-run.
895
+ *
896
+ * @param effect The effect.
897
+ * @param env The expression environment.
898
+ * @param state The component's state table.
899
+ * @param out Everything emitted so far; the effect is added to it.
900
+ */
901
+ export function lowerEffect(effect, env, state, out) {
902
+ // An expression body is a single statement.
903
+ const body = effect.fn.body;
904
+ const statements = body.type === 'BlockStatement'
905
+ ? body.body
906
+ : [{ type: 'ExpressionStatement', expression: body }];
907
+ // A mount-once effect (no dependency list, or `[]`) runs once, from er_app_build.
908
+ const isMount = !effect.deps ||
909
+ (effect.deps.type === 'ArrayExpression' &&
910
+ effect.deps.elements.length === 0);
911
+ if (isMount) {
912
+ const ctx = {
913
+ stateChanged: false,
914
+ animIdx: 0,
915
+ out,
916
+ allowReturn: true,
917
+ bodyList: statements,
918
+ };
919
+ const lowered = lowerStmts(statements, env, state, ctx);
920
+ if (!ctx.usedReturn) {
921
+ out.mountEffects.push({
922
+ kind: 'inline',
923
+ callback: { body: lowered, updatesState: ctx.stateChanged },
924
+ });
925
+ return;
926
+ }
927
+ // With an early `return` the body gets its own function, so it cannot skip later mount effects.
928
+ const name = `er_effect_${out.effN++}`;
929
+ out.effectFns.push({ kind: 'mount', name, body: lowered });
930
+ out.mountEffects.push({
931
+ kind: 'call',
932
+ name,
933
+ updatesState: ctx.stateChanged,
934
+ });
935
+ return;
936
+ }
937
+ // A dep-driven effect gets its own C function; each dep must be scalar, so a change shows against a stored copy.
938
+ if (effect.deps.type !== 'ArrayExpression') {
939
+ throw aotError('AOT: a useEffect dependency list must be an array literal', 'pass `[]` (run once) or `[a, b]` (re-run when a/b change).');
940
+ }
941
+ const effectId = out.effN++;
942
+ const deps = effect.deps.elements.map(depNode => {
943
+ if (!depNode) {
944
+ throw aotError('AOT: a useEffect dependency must be an expression');
945
+ }
946
+ const depExpr = lowerExprWide(depNode, env);
947
+ if (!['int', 'float', 'i64', 'string'].includes(toCExpr(depExpr).cType)) {
948
+ throw aotError('AOT: useEffect dependencies must be scalar (number / bool / string)', 'depend on scalar state values; object/array dependencies are not yet supported.');
949
+ }
950
+ return depExpr;
951
+ });
952
+ // React runs the previous cleanup before a re-run; an `armed` flag records whether the last run reached it.
953
+ const lastStatement = statements[statements.length - 1];
954
+ const hasCleanup = lastStatement?.type === 'ReturnStatement' && isFn(lastStatement.argument);
955
+ const depEffect = {
956
+ id: effectId,
957
+ deps,
958
+ body: [],
959
+ hasCleanup,
960
+ cleanup: null,
961
+ };
962
+ const ctx = {
963
+ stateChanged: false,
964
+ animIdx: 0,
965
+ out,
966
+ allowReturn: true,
967
+ bodyList: statements,
968
+ depDriven: true,
969
+ };
970
+ // With a cleanup, hoist the body's locals and lower the tail `return () => …` into `<effect>_cleanup()`.
971
+ if (hasCleanup) {
972
+ ctx.hoist = { prefix: `s_eff${effectId}_l_`, decls: out.effectDecls };
973
+ ctx.cleanup = {
974
+ armed: armedFlag(effectId),
975
+ emit: (cleanupFn, cleanupEnv) => {
976
+ const cleanupBody = cleanupFn.body;
977
+ const cleanupStatements = cleanupBody.type === 'BlockStatement'
978
+ ? cleanupBody.body
979
+ : [{ type: 'ExpressionStatement', expression: cleanupBody }];
980
+ const cleanupCtx = {
981
+ stateChanged: false,
982
+ animIdx: 0,
983
+ out,
984
+ };
985
+ depEffect.cleanup = lowerStmts(cleanupStatements, cleanupEnv, state, cleanupCtx);
986
+ out.effectFns.push({ kind: 'cleanup', effect: depEffect });
987
+ },
988
+ };
989
+ out.effectDecls.push({ kind: 'armed', effect: depEffect });
990
+ }
991
+ // The effect function runs the last run's cleanup first, if that run armed it, then the body.
992
+ depEffect.body = lowerStmts(statements, env, state, ctx);
993
+ out.effectFns.push({ kind: 'effect', effect: depEffect });
994
+ // A copy of each dep, taken at mount; app_update() re-runs the effect when one no longer matches its copy.
995
+ out.effectDecls.push({ kind: 'deps', effect: depEffect });
996
+ out.mountEffects.push({ kind: 'depEffect', effect: depEffect });
997
+ out.depEffects.push(depEffect);
998
+ }
999
+ /**
1000
+ * Lowers an event handler to a callback. Its first parameter is the event, whose touch fields read
1001
+ * EREventData; a PanResponder callback's second is RN's gestureState (see lowerGestureField).
1002
+ *
1003
+ * @param fnNode The handler.
1004
+ * @param env The expression environment.
1005
+ * @param state The component's state table.
1006
+ * @param out Everything emitted so far.
1007
+ * @param pan The PanResponder the handler belongs to, if any.
1008
+ *
1009
+ * @returns The callback.
1010
+ */
1011
+ export function lowerHandler(fnNode, env, state, out, pan = null) {
1012
+ // An expression body is a single statement.
1013
+ const body = fnNode.body;
1014
+ const statements = body.type === 'BlockStatement'
1015
+ ? body.body
1016
+ : [{ type: 'ExpressionStatement', expression: body }];
1017
+ // The first parameter is the event (fields map to EREventData); a PanResponder's second is RN's gestureState.
1018
+ const eventParam = fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
1019
+ const gestureParam = pan && fnNode.params[1]?.type === 'Identifier'
1020
+ ? fnNode.params[1].name
1021
+ : null;
1022
+ let handlerEnv = env;
1023
+ if (eventParam) {
1024
+ handlerEnv = { ...handlerEnv, event: eventParam };
1025
+ }
1026
+ if (gestureParam) {
1027
+ handlerEnv = { ...handlerEnv, gesture: gestureParam, pan };
1028
+ }
1029
+ // The body re-applies state-dependent props once at its end if it set state.
1030
+ const ctx = { stateChanged: false, animIdx: 0, out };
1031
+ return {
1032
+ body: lowerStmts(statements, handlerEnv, state, ctx),
1033
+ updatesState: ctx.stateChanged,
1034
+ };
1035
+ }
1036
+ /**
1037
+ * Lowers a value-callback (e.g., Switch onValueChange) — binds its first param to `valueCode`, not an event.
1038
+ *
1039
+ * @param fnNode The callback.
1040
+ * @param valueCode C for the value its first parameter receives.
1041
+ * @param env The expression environment.
1042
+ * @param state The component's state table.
1043
+ * @param out Everything emitted so far.
1044
+ * @param cType The value's C kind.
1045
+ * @param secondValueCode C for a second parameter's value (a range <Dial>'s low end), if any.
1046
+ * @param isBool The value is a boolean, so text prints it as true/false.
1047
+ *
1048
+ * @returns The callback.
1049
+ */
1050
+ export function lowerValueHandler(fnNode, valueCode, env, state, out, cType = 'int', secondValueCode = null, isBool = false) {
1051
+ // A <Switch> hands its callback a boolean; carry that so `'on=' + v` prints true/false, not 1/0.
1052
+ const valueParam = fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
1053
+ const locals = new Map(env.locals);
1054
+ if (valueParam) {
1055
+ locals.set(valueParam, { code: valueCode, cType, isBool });
1056
+ }
1057
+ // A RANGE <Dial>'s second parameter binds the same way, lowering to data->value_start with no object on device.
1058
+ const secondParam = fnNode.params[1]?.type === 'Identifier' ? fnNode.params[1].name : null;
1059
+ if (secondParam && secondValueCode) {
1060
+ locals.set(secondParam, { code: secondValueCode, cType });
1061
+ }
1062
+ // Lower the body (an expression body is a single statement); it re-applies state once if it set any.
1063
+ const ctx = { stateChanged: false, animIdx: 0, out };
1064
+ const body = fnNode.body;
1065
+ const statements = body.type === 'BlockStatement'
1066
+ ? body.body
1067
+ : [{ type: 'ExpressionStatement', expression: body }];
1068
+ return {
1069
+ body: lowerStmts(statements, { ...env, locals }, state, ctx),
1070
+ updatesState: ctx.stateChanged,
1071
+ };
1072
+ }