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