embedded-react 0.13.0 → 0.14.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.
package/aot/compile.mjs CHANGED
@@ -34,6 +34,7 @@
34
34
  // npm run aot # default demo (thermostat) — but use a minimal demo for the slice
35
35
  // npm run aot -- watch-face # a specific demo by folder name
36
36
  import {parse} from '@babel/parser';
37
+ import {traverse} from '@babel/core';
37
38
  import {codeFrameColumns} from '@babel/code-frame';
38
39
  import {
39
40
  readFileSync,
@@ -46,6 +47,8 @@ import {resolve, dirname} from 'node:path';
46
47
  import {fileURLToPath} from 'node:url';
47
48
  import {
48
49
  lowerStyle,
50
+ isStyleKey,
51
+ STYLE_KEYS,
49
52
  NODE_TYPES,
50
53
  DYN_FIELDS,
51
54
  colorLiteral,
@@ -103,6 +106,15 @@ const [PKG_MAJOR, PKG_MINOR] = PKG_VERSION.split('.');
103
106
  // DEEPEST node that failed pins the location; compileSource formats it at the top.
104
107
  // ---------------------------------------------------------------------------------------------------
105
108
 
109
+ /**
110
+ * The `#ifndef` marker a board example guards on, from a demo name. Every character outside [A-Za-z0-9]
111
+ * becomes `_<hex code point>_`, so the result is a C identifier AND the mapping is one-to-one: `foo-bar`
112
+ * is ER_AOT_DEMO_foo_2d_bar and `foo_bar` is ER_AOT_DEMO_foo_5f_bar. Flattening both to `foo_bar` would
113
+ * let a board guard accept the wrong app, from either entry point that generates one.
114
+ */
115
+ export const demoMarker = demo =>
116
+ `ER_AOT_DEMO_${demo.replace(/[^A-Za-z0-9]/gu, ch => `_${ch.codePointAt(0).toString(16)}_`)}`;
117
+
106
118
  /** Throws an AOT error carrying an optional `hint` (a "rewrite it like this" suggestion shown to the user). */
107
119
  function aotError(message, hint) {
108
120
  const e = new Error(message.startsWith('AOT:') ? message : `AOT: ${message}`);
@@ -290,16 +302,336 @@ function evalStatic(node, scope) {
290
302
  const ARITH = new Set(['+', '-', '*', '/', '%']);
291
303
  const COMPARE = new Set(['<', '>', '<=', '>=', '==', '!=', '===', '!==']);
292
304
 
305
+ /**
306
+ * The C helper each whole-number operator lowers to. It saturates at the limit of its type, where C's own
307
+ * signed overflow is undefined behavior; the 64-bit variant appends `64`.
308
+ */
309
+ const CHECKED_OP = {'+': 'app_add', '-': 'app_sub', '*': 'app_mul'};
310
+
311
+ /**
312
+ * `scope` minus every name `env` binds at RUNTIME — locals, state, refs, animated values, and the event /
313
+ * gesture params of the handler being compiled. emitExpr resolves those before env.consts, so a fold
314
+ * that consulted the raw scope would silently swap a module const in for the value the code actually
315
+ * uses. Every env-driven constant fold goes through this; the JSX-side folds keep the same rule by
316
+ * deleting a name from their scope copy when they bind it (see emitComponent / emitDynamicMap).
317
+ */
318
+ function foldScope(env, scope) {
319
+ const bound = new Set([
320
+ ...(env.locals?.keys() ?? []),
321
+ ...(env.state?.keys() ?? []),
322
+ ...(env.refs?.keys() ?? []),
323
+ ...(env.anims?.keys() ?? []),
324
+ ]);
325
+ if (env.event) bound.add(env.event);
326
+ if (env.gesture) bound.add(env.gesture);
327
+ let shadows = false;
328
+ for (const k of bound)
329
+ if (k in scope) {
330
+ shadows = true;
331
+ break;
332
+ }
333
+ if (!shadows) return scope;
334
+ return Object.fromEntries(
335
+ Object.entries(scope).filter(([k]) => !bound.has(k)),
336
+ );
337
+ }
338
+
339
+ const withUndefined = scope => Object.assign(Object.create(scope), {undefined});
340
+
341
+ /**
342
+ * `e` used as a C condition. JS treats a string as truthy when it is non-empty; a bare char[] in C tests
343
+ * its ADDRESS, which is always true — and real GCC refuses that under -Werror=address.
344
+ */
345
+ const asCond = e => (e.cType === 'string' ? `(${e.code}[0] != '\\0')` : e.code);
346
+
347
+ /** No state or ref slot widened to 64 bits — the collectors' default. */
348
+ const NO_WIDE = new Set();
349
+
350
+ /** A 64-bit timestamp met a float, which would round it. */
351
+ const mix64Error = () =>
352
+ aotError(
353
+ 'AOT: a 64-bit time value cannot be mixed with a float',
354
+ 'Date.now() and performance.now() are whole milliseconds in a 64-bit integer, and a float would round them. Keep the arithmetic whole — e.g. Math.floor(ms / 1000), not ms * 0.001.',
355
+ );
356
+
357
+ /** A 64-bit timestamp met a boolean in `&&` / `||` / `?:`, where JS would hand back the boolean itself. */
358
+ const bool64Error = what =>
359
+ aotError(
360
+ `AOT: ${what} cannot mix a boolean with a 64-bit time value`,
361
+ 'JS would give back the boolean itself (and false renders as no text), which a 64-bit integer cannot hold. Use a number on both sides, e.g. `on ? Date.now() : 0`.',
362
+ );
363
+
364
+ /** Flow A's lite profile has Date.now() and no Date objects, and so does the AOT. */
365
+ const dateObjectError = () =>
366
+ aotError(
367
+ 'AOT: Date objects are not supported — only Date.now()',
368
+ 'keep time as milliseconds from Date.now() and do the calendar math on the number.',
369
+ );
370
+
371
+ /**
372
+ * The `Date` / `performance` calls whose name is the app's own binding — a const, a param, an import —
373
+ * rather than the global, so they are not the engine clock. Babel's scopes decide, as JS would.
374
+ */
375
+ function findShadowedClockCalls(ast) {
376
+ const calls = new WeakSet();
377
+ traverse(ast, {
378
+ 'CallExpression|NewExpression'(path) {
379
+ const c = path.node.callee;
380
+ const id = c.type === 'MemberExpression' ? c.object : c;
381
+ if (
382
+ id.type === 'Identifier' &&
383
+ (id.name === 'Date' || id.name === 'performance') &&
384
+ path.scope.getBinding(id.name)
385
+ )
386
+ calls.add(path.node);
387
+ },
388
+ });
389
+ return calls;
390
+ }
391
+
392
+ /** `node` as an integer compile-time constant, or null. */
393
+ function staticInt(node, env) {
394
+ try {
395
+ const v = evalStatic(node, foldScope(env, env.consts ?? {}));
396
+ return Number.isInteger(v) ? v : null;
397
+ } catch {
398
+ return null;
399
+ }
400
+ }
401
+
402
+ const INT_MIN = -(2 ** 31);
403
+ const INT_MAX = 2 ** 31 - 1;
404
+
405
+ /**
406
+ * A compile-time number as C. A whole number too big for an int is a 64-bit constant (`lit`), so whole-number
407
+ * math keeps it exact; past 64 bits it is a float.
408
+ */
409
+ function numConst(v) {
410
+ // floatLit refuses NaN and Infinity (a folded `0 / 0`, say), which have no C literal.
411
+ if (!Number.isInteger(v)) return {code: floatLit(v), cType: 'float'};
412
+ if (v < -(2 ** 63) || v >= 2 ** 63)
413
+ return {code: floatLit(v), cType: 'float'};
414
+ if (v < INT_MIN || v > INT_MAX)
415
+ return {code: i64Lit(v), cType: 'i64', lit: true};
416
+ // `-2147483648` is `-` applied to 2147483648, which does not fit an int.
417
+ return {code: v === INT_MIN ? '(-2147483647 - 1)' : String(v), cType: 'int'};
418
+ }
419
+
420
+ /**
421
+ * A whole number in the int64 range as a C literal. `String(v)` is JS's shortest spelling that reads back as the
422
+ * same double, which past 2^53 is not the number itself: 4611686018427387904 prints as 4611686018427388000.
423
+ */
424
+ function i64Lit(v) {
425
+ // `-9223372036854775808` is `-` applied to 9223372036854775808, which fits no signed type.
426
+ return v === -(2 ** 63) ? '(-9223372036854775807 - 1)' : BigInt(v).toString();
427
+ }
428
+
429
+ /** `+ - *` or a unary `-`: the operators that can overflow a whole number. */
430
+ const isIntArith = n =>
431
+ (n.type === 'BinaryExpression' && Boolean(CHECKED_OP[n.operator])) ||
432
+ (n.type === 'UnaryExpression' && n.operator === '-');
433
+
434
+ /** The Math functions that keep a whole number whole. */
435
+ const WHOLE_MATH = new Set([
436
+ 'floor',
437
+ 'ceil',
438
+ 'round',
439
+ 'trunc',
440
+ 'abs',
441
+ 'min',
442
+ 'max',
443
+ ]);
444
+
445
+ /**
446
+ * Whole-number math JS would not cut to 32 bits: `+ - *`, negation, `%`, and the Math functions that keep a
447
+ * whole number whole. Beside a 64-bit value all of it is worked out in 64 bits, however deep it sits.
448
+ */
449
+ const keepsMath64 = n =>
450
+ isIntArith(n) ||
451
+ (n.type === 'BinaryExpression' && n.operator === '%') ||
452
+ (n.type === 'CallExpression' &&
453
+ n.callee.type === 'MemberExpression' &&
454
+ !n.callee.computed &&
455
+ n.callee.object.type === 'Identifier' &&
456
+ n.callee.object.name === 'Math' &&
457
+ WHOLE_MATH.has(n.callee.property.name));
458
+
459
+ /**
460
+ * A 64-bit value computed at runtime from a timestamp, as opposed to a 64-bit constant (`lit`) or whole-number
461
+ * math widened to 64 bits beside one (`wide`).
462
+ */
463
+ const isTime64 = e => e.cType === 'i64' && !e.lit && !e.wide;
464
+
465
+ /** Beside a float, a 64-bit constant is an ordinary number that converts, as in JS; only a timestamp refuses. */
466
+ const litPeers = (...es) =>
467
+ es.some(e => e.cType === 'float')
468
+ ? es.map(e => (e.lit ? {code: `((float)${e.code})`, cType: 'float'} : e))
469
+ : es;
470
+
471
+ /**
472
+ * The divisor of a timestamp's `%` or Math.floor / ceil / round / trunc(a / b), which has to be a constant; for
473
+ * one from state, an app reduces the timestamp first. A constant 0 gives JS's answer as the int math converts it:
474
+ * a remainder of 0, or a quotient saturated by the dividend's sign.
475
+ */
476
+ function constDivisor(node, env) {
477
+ const m = staticInt(node, env);
478
+ if (m !== null) return m;
479
+ const e = aotError(
480
+ 'AOT: a 64-bit time value can only be divided by a constant',
481
+ 'the divisor must be known at compile time — e.g. `ms % 1000`, `Math.floor(ms / 60000)`. For a divisor from state, reduce the timestamp first: `(ms % 86400000) / period`.',
482
+ );
483
+ if (node.loc) e.aotLoc = node.loc.start;
484
+ throw e;
485
+ }
486
+
487
+ /**
488
+ * `+ - * %` with a 64-bit value on either side, kept whole. `+ - *` saturate at the int64 limits. With a
489
+ * timestamp in it, `%` takes a constant; whole-number math widened beside one takes any divisor, as the
490
+ * int `%` does. The result narrows back to int when the divisor or the dividend fits one, so `ms % 1000` is an
491
+ * ordinary number again. `/` is refused: JS would give a fraction, and the whole-number division is written
492
+ * Math.floor(a / b).
493
+ */
494
+ function emitArith64(node, l, r, env) {
495
+ if (l.cType === 'float' || r.cType === 'float') throw mix64Error();
496
+ if (node.operator === '/')
497
+ throw aotError(
498
+ 'AOT: `/` on a 64-bit time value is not supported',
499
+ 'JS division gives a fraction, which a 64-bit integer cannot hold. Use Math.floor(a / b) for whole units — e.g. Math.floor(ms / 1000) for seconds.',
500
+ );
501
+ const wide = !isTime64(l) && !isTime64(r);
502
+ if (node.operator === '%') {
503
+ const k = staticInt(node.right, env);
504
+ // JS gives NaN for a zero divisor, which is 0 here, as the int `%` has it.
505
+ if (k === 0) return {code: '0', cType: 'int'};
506
+ if (wide && k === null)
507
+ return {
508
+ code: `app_mod64(${l.code}, ${r.code})`,
509
+ cType: 'i64',
510
+ wide: true,
511
+ };
512
+ const m = constDivisor(node.right, env);
513
+ // ±1 leaves no remainder, and INT64_MIN % -1 overflows in C.
514
+ if (m === 1 || m === -1) return {code: '0', cType: 'int'};
515
+ if (Math.abs(m) <= 0x7fffffff || l.cType === 'int')
516
+ return {code: `((int)(${l.code} % ${r.code}))`, cType: 'int'};
517
+ return {code: `(${l.code} % ${r.code})`, cType: 'i64', wide};
518
+ }
519
+ return {
520
+ code: `${CHECKED_OP[node.operator]}64(${l.code}, ${r.code})`,
521
+ cType: 'i64',
522
+ wide,
523
+ };
524
+ }
525
+
526
+ /**
527
+ * Math.floor / ceil / round / trunc over `a / b` with a 64-bit timestamp on either side, as exact integer division
528
+ * by a constant (see constDivisor); a zero one saturates by the dividend's sign, as JS's ±Infinity converts. Null
529
+ * when neither side is a timestamp, which leaves it to the whole-number or float path.
530
+ */
531
+ function emitTimeRoundDiv(fn, args, env) {
532
+ const arg = args[0];
533
+ if (
534
+ !INT_ROUND_DIV.has(fn) ||
535
+ args.length !== 1 ||
536
+ arg.type !== 'BinaryExpression' ||
537
+ arg.operator !== '/'
538
+ )
539
+ return null;
540
+ const l = emitExprWide(arg.left, env);
541
+ const r = emitExprWide(arg.right, env);
542
+ if (!isTime64(l) && !isTime64(r)) return null;
543
+ if (l.cType === 'float' || r.cType === 'float') throw mix64Error();
544
+ if (l.cType === 'string' || r.cType === 'string') return null;
545
+ // Dividing by -1 is a negation, which saturates; C's `/` would overflow on INT64_MIN / -1.
546
+ if (constDivisor(arg.right, env) === -1)
547
+ return {code: `app_neg64(${l.code})`, cType: 'i64'};
548
+ return {
549
+ code: `${INT_ROUND_DIV.get(fn)}64(${l.code}, ${r.code})`,
550
+ cType: 'i64',
551
+ };
552
+ }
553
+
554
+ /** The helper that rounds `a / b` for two ints the way each Math function does. */
555
+ const INT_ROUND_DIV = new Map([
556
+ ['floor', 'app_floordiv'],
557
+ ['ceil', 'app_ceildiv'],
558
+ ['round', 'app_rounddiv'],
559
+ ['trunc', 'app_div'],
560
+ ]);
561
+
562
+ /**
563
+ * Math.floor / ceil / round / trunc over `a / b` with two whole numbers, as exact integer division: the float
564
+ * path rounds an operand past 2^24, so Math.floor(16777217 / 1) came out 16777216. A zero divisor keeps JS's
565
+ * answer as app_f2i converts it (±Infinity saturates by the dividend's sign, 0 / 0 is 0), and INT_MIN / -1
566
+ * saturates too. Beside a 64-bit value, or with a 64-bit operand that is not a timestamp (a constant past the int
567
+ * range, or math already widened), it divides in 64 bits, since JS would not cut the operands to 32. Null for
568
+ * anything else, which leaves it to the float path.
569
+ */
570
+ function emitIntRoundDiv(fn, args, env) {
571
+ const arg = args[0];
572
+ if (
573
+ !INT_ROUND_DIV.has(fn) ||
574
+ args.length !== 1 ||
575
+ arg.type !== 'BinaryExpression' ||
576
+ arg.operator !== '/'
577
+ )
578
+ return null;
579
+ const l = emitExprWide(arg.left, env);
580
+ const r = emitExprWide(arg.right, env);
581
+ if (env.math64 || l.cType === 'i64' || r.cType === 'i64') {
582
+ const whole = e => e.cType === 'int' || (e.cType === 'i64' && !isTime64(e));
583
+ if (!whole(l) || !whole(r)) return null;
584
+ return {
585
+ code: `${INT_ROUND_DIV.get(fn)}64(${l.code}, ${r.code})`,
586
+ cType: 'i64',
587
+ wide: true,
588
+ };
589
+ }
590
+ if (l.cType !== 'int' || r.cType !== 'int') return null;
591
+ return {
592
+ code: `${INT_ROUND_DIV.get(fn)}(${l.code}, ${r.code})`,
593
+ cType: 'int',
594
+ };
595
+ }
596
+
597
+ /** Math.* over a 64-bit timestamp: only what stays exact in whole numbers. */
598
+ function emitMath64(fn, a) {
599
+ if (a.some(x => x.cType === 'float')) throw mix64Error();
600
+ if (a.every(x => x.cType === 'int' || x.cType === 'i64')) {
601
+ // Whole-number math with no timestamp in it stays whole-number math.
602
+ const wide = !a.some(isTime64);
603
+ // A timestamp is already whole, so rounding leaves it as it is.
604
+ if (
605
+ (fn === 'floor' || fn === 'round' || fn === 'ceil' || fn === 'trunc') &&
606
+ a.length === 1
607
+ )
608
+ return {code: a[0].code, cType: 'i64', wide};
609
+ if (fn === 'abs' && a.length === 1)
610
+ return {code: `app_abs64(${a[0].code})`, cType: 'i64', wide};
611
+ if ((fn === 'min' || fn === 'max') && a.length === 2)
612
+ return {
613
+ code: `app_${fn}64(${a[0].code}, ${a[1].code})`,
614
+ cType: 'i64',
615
+ wide,
616
+ };
617
+ }
618
+ throw aotError(
619
+ `AOT: Math.${fn}(...) on a 64-bit time value is not supported`,
620
+ 'Math.floor / round / ceil / trunc / abs / min / max keep a timestamp exact; for anything else, reduce it to a small number first, e.g. `ms % 1000`.',
621
+ );
622
+ }
623
+
293
624
  function emitExprImpl(node, env) {
625
+ // 64-bit int math reaches only through whole-number math (keepsMath64); any other node under it is typed as
626
+ // usual.
627
+ if (env.math64 && !keepsMath64(node)) env = {...env, math64: false};
294
628
  switch (node.type) {
295
629
  case 'NumericLiteral':
296
- return Number.isInteger(node.value)
297
- ? {code: String(node.value), cType: 'int'}
298
- : {code: `${node.value}f`, cType: 'float'};
630
+ return numConst(node.value);
299
631
  case 'StringLiteral':
300
632
  return {code: cstr(node.value), cType: 'string'};
301
633
  case 'BooleanLiteral':
302
- return {code: node.value ? '1' : '0', cType: 'int'};
634
+ return {code: node.value ? '1' : '0', cType: 'int', isBool: true};
303
635
  case 'Identifier': {
304
636
  if (env.locals.has(node.name)) return env.locals.get(node.name);
305
637
  if (env.state.has(node.name)) {
@@ -308,38 +640,101 @@ function emitExprImpl(node, env) {
308
640
  throw new Error(
309
641
  `AOT: a list state ("${node.name}") can only be used via .length or .map`,
310
642
  );
311
- return {code: s.cMember, cType: s.cType};
643
+ return {code: s.cMember, cType: s.cType, isBool: s.isBool};
312
644
  }
313
645
  if (node.name in env.consts) {
314
646
  const v = env.consts[node.name];
315
- if (typeof v === 'number')
316
- return Number.isInteger(v)
317
- ? {code: String(v), cType: 'int'}
318
- : {code: `${v}f`, cType: 'float'};
647
+ if (typeof v === 'number') return numConst(v);
319
648
  if (typeof v === 'string') return {code: cstr(v), cType: 'string'};
649
+ if (typeof v === 'boolean')
650
+ return {code: v ? '1' : '0', cType: 'int', isBool: true};
320
651
  }
321
652
  throw new Error(
322
653
  `AOT: cannot resolve identifier "${node.name}" in a dynamic expression`,
323
654
  );
324
655
  }
325
656
  case 'UnaryExpression': {
326
- const a = emitExpr(node.argument, env);
327
- // Parenthesize the operand so `-` on a negative literal emits `(-(-135))`, not `(--135)` (a decrement).
657
+ // A constant is negated here, so `-A` is its value and -2147483648 is not an int overflow.
658
+ const neg = node.operator === '-' ? staticInt(node.argument, env) : null;
659
+ if (neg !== null) return numConst(-neg);
660
+ const a = emitExprWide(node.argument, env);
661
+ if (
662
+ (node.operator === '-' || node.operator === '+') &&
663
+ a.cType === 'string'
664
+ )
665
+ throw aotError(
666
+ `AOT: unary "${node.operator}" on a string is not supported`,
667
+ 'JS would coerce the string to a number; C has no such coercion. Keep the operand numeric.',
668
+ );
669
+ // Negating the minimum overflows, so a whole number saturates the way `+ - *` do.
670
+ if (node.operator === '-' && (a.cType === 'int' || a.cType === 'i64')) {
671
+ const w = a.cType === 'i64' || env.math64;
672
+ return w
673
+ ? {code: `app_neg64(${a.code})`, cType: 'i64', wide: !isTime64(a)}
674
+ : {code: `app_neg(${a.code})`, cType: 'int'};
675
+ }
676
+ // Parenthesize the operand so `-` on a negative operand emits `(-(-x))`, not `(--x)` (a decrement).
328
677
  if (
329
678
  node.operator === '-' ||
330
679
  node.operator === '+' ||
331
680
  node.operator === '!'
332
681
  )
682
+ // Only `!` yields a boolean. Unary +/- are numeric coercions — `+flag` is 0 or 1 in JS, so the
683
+ // operand's boolean-ness must not survive them.
333
684
  return {
334
- code: `(${node.operator}(${a.code}))`,
685
+ code: `(${node.operator}(${node.operator === '!' ? asCond(a) : a.code}))`,
335
686
  cType: node.operator === '!' ? 'int' : a.cType,
687
+ isBool: node.operator === '!',
336
688
  };
337
689
  throw new Error(`AOT: unsupported unary operator "${node.operator}"`);
338
690
  }
339
691
  case 'BinaryExpression': {
340
- const l = emitExpr(node.left, env);
341
- const r = emitExpr(node.right, env);
692
+ // `+ - *` over two whole-number constants is worked out here, as JS would, so a product too big for an
693
+ // int (30 * DAY_MS) is an exact 64-bit constant rather than an overflow.
694
+ const lk = CHECKED_OP[node.operator] ? staticInt(node.left, env) : null;
695
+ const rk = lk === null ? null : staticInt(node.right, env);
696
+ if (rk !== null)
697
+ return numConst(
698
+ node.operator === '+'
699
+ ? lk + rk
700
+ : node.operator === '-'
701
+ ? lk - rk
702
+ : lk * rk,
703
+ );
704
+ let l = emitExprWide(node.left, env);
705
+ let r = emitExprWide(node.right, env);
706
+ // Beside a 64-bit value, whole-number int math is worked out in 64 bits too: JS would not have cut it to 32.
707
+ if (l.cType === 'i64' || r.cType === 'i64') {
708
+ if (l.cType === 'int' && keepsMath64(node.left))
709
+ l = emitExprWide(node.left, {...env, math64: true});
710
+ if (r.cType === 'int' && keepsMath64(node.right))
711
+ r = emitExprWide(node.right, {...env, math64: true});
712
+ }
713
+ [l, r] = litPeers(l, r);
342
714
  if (ARITH.has(node.operator)) {
715
+ if (l.cType === 'string' || r.cType === 'string') {
716
+ // `+` over a string builds text, which C cannot express as one value. Where the destination is
717
+ // a char buffer the caller lowers it with emitFormat(); anywhere else there is nothing to lower
718
+ // to.
719
+ if (node.operator === '+')
720
+ throw aotError(
721
+ 'AOT: string concatenation is not supported in this position',
722
+ 'a `+` chain over strings lowers to a printf format, which only works where the value lands in a text buffer: a <Text> body, a string useState setter, or a <TextInput value>.',
723
+ );
724
+ // JS would coerce the string to a number; C would do pointer arithmetic or refuse to compile.
725
+ throw aotError(
726
+ `AOT: "${node.operator}" on a string is not supported`,
727
+ 'keep both operands numeric — a string cannot be coerced to a number here.',
728
+ );
729
+ }
730
+ // `/` takes a 64-bit constant as an ordinary C number; only a runtime 64-bit value is refused it.
731
+ if (
732
+ isTime64(l) ||
733
+ isTime64(r) ||
734
+ ((l.cType === 'i64' || r.cType === 'i64') &&
735
+ (CHECKED_OP[node.operator] || node.operator === '%'))
736
+ )
737
+ return emitArith64(node, l, r, env);
343
738
  if (node.operator === '/')
344
739
  return {
345
740
  code: `((float)(${l.code}) / (float)(${r.code}))`,
@@ -347,28 +742,96 @@ function emitExprImpl(node, env) {
347
742
  };
348
743
  const cType =
349
744
  l.cType === 'float' || r.cType === 'float' ? 'float' : 'int';
745
+ const fn = cType === 'int' && CHECKED_OP[node.operator];
746
+ if (fn)
747
+ return env.math64
748
+ ? {code: `${fn}64(${l.code}, ${r.code})`, cType: 'i64', wide: true}
749
+ : {code: `${fn}(${l.code}, ${r.code})`, cType: 'int'};
750
+ // JS gives NaN for `x % 0` (0 here, as a float would convert), and C overflows on INT_MIN % -1, whose
751
+ // answer is 0. A constant divisor other than those two needs no check.
752
+ if (cType === 'int' && node.operator === '%') {
753
+ const k = staticInt(node.right, env);
754
+ if (k === 0 || k === -1) return {code: '0', cType: 'int'};
755
+ if (k === null)
756
+ return {code: `app_mod(${l.code}, ${r.code})`, cType: 'int'};
757
+ }
758
+ // C has no `%` on floats. fmodf is JS's `%` exactly: the dividend's sign, NaN for a zero divisor, and
759
+ // the dividend itself for an infinite one.
760
+ if (cType === 'float' && node.operator === '%')
761
+ return {
762
+ code: `fmodf((float)(${l.code}), (float)(${r.code}))`,
763
+ cType: 'float',
764
+ };
350
765
  return {code: `(${l.code} ${node.operator} ${r.code})`, cType};
351
766
  }
352
767
  if (COMPARE.has(node.operator)) {
353
- const eqOp =
354
- node.operator === '===' || node.operator === '=='
355
- ? '=='
356
- : node.operator === '!==' || node.operator === '!='
357
- ? '!='
358
- : null;
359
- // String (in)equality → strcmp; the generated C already includes <string.h>.
360
- if (eqOp && (l.cType === 'string' || r.cType === 'string'))
361
- return {
362
- code: `(strcmp(${l.code}, ${r.code}) ${eqOp} 0)`,
363
- cType: 'int',
364
- };
365
768
  const op =
366
769
  node.operator === '==='
367
770
  ? '=='
368
771
  : node.operator === '!=='
369
772
  ? '!='
370
773
  : node.operator;
371
- return {code: `(${l.code} ${op} ${r.code})`, cType: 'int'};
774
+ if (l.cType === 'string' || r.cType === 'string') {
775
+ if (l.cType !== r.cType) {
776
+ // A strict comparison never coerces, so a string against a number is decided statically.
777
+ if (node.operator === '===' || node.operator === '!==')
778
+ return {
779
+ code: node.operator === '===' ? '0' : '1',
780
+ cType: 'int',
781
+ isBool: true,
782
+ };
783
+ throw aotError(
784
+ 'AOT: a string cannot be compared with a number',
785
+ `\`${node.operator}\` coerces the string to a number in JS, which C cannot reproduce. Compare like with like, or use === / !== (which never coerce).`,
786
+ );
787
+ }
788
+ // Equality is byte-exact, which for UTF-8 is exactly JS string equality. Ordering is not: JS
789
+ // orders by UTF-16 code unit and strcmp by UTF-8 byte, and the two disagree once a character
790
+ // lies outside the Basic Multilingual Plane. Refuse rather than silently pick the other branch.
791
+ // (A bare `<` on two char* would compare addresses — real GCC rejects that under -Werror=address.)
792
+ if (op !== '==' && op !== '!=')
793
+ throw aotError(
794
+ `AOT: ordering strings with "${node.operator}" is not supported`,
795
+ 'JS orders strings by UTF-16 code unit but the device holds UTF-8, so the order can differ. Use === / !==, or compare numbers.',
796
+ );
797
+ return {
798
+ code: `(strcmp(${l.code}, ${r.code}) ${op} 0)`,
799
+ cType: 'int',
800
+ isBool: true,
801
+ };
802
+ }
803
+ // A boolean and a number share an int slot, so C would hold `true === 1`; a strict comparison never
804
+ // coerces, so JS never does. Decided only when the other side is surely a number.
805
+ if (
806
+ (l.cType === 'i64' || r.cType === 'i64') &&
807
+ (l.cType === 'float' || r.cType === 'float')
808
+ )
809
+ throw mix64Error();
810
+ const surelyNum = (n, x) =>
811
+ !x.isBool &&
812
+ (x.cType === 'float' ||
813
+ x.cType === 'i64' ||
814
+ n.type === 'NumericLiteral' ||
815
+ (n.type === 'UnaryExpression' &&
816
+ n.argument.type === 'NumericLiteral') ||
817
+ (n.type === 'Identifier' &&
818
+ !env.locals.has(n.name) &&
819
+ env.state.get(n.name)?.isBool === false));
820
+ if (
821
+ (node.operator === '===' || node.operator === '!==') &&
822
+ ((l.isBool && surelyNum(node.right, r)) ||
823
+ (r.isBool && surelyNum(node.left, l)))
824
+ )
825
+ return {
826
+ code: node.operator === '===' ? '0' : '1',
827
+ cType: 'int',
828
+ isBool: true,
829
+ };
830
+ return {
831
+ code: `(${l.code} ${op} ${r.code})`,
832
+ cType: 'int',
833
+ isBool: true,
834
+ };
372
835
  }
373
836
  throw new Error(`AOT: unsupported binary operator "${node.operator}"`);
374
837
  }
@@ -377,32 +840,74 @@ function emitExprImpl(node, env) {
377
840
  node.operator === '&&' || node.operator === '||' ? node.operator : null;
378
841
  if (!op)
379
842
  throw new Error(`AOT: unsupported logical operator "${node.operator}"`);
380
- const l = emitExpr(node.left, env);
381
- const r = emitExpr(node.right, env);
382
- return {code: `(${l.code} ${op} ${r.code})`, cType: 'int'};
843
+ const [l, r] = litPeers(
844
+ emitExprWide(node.left, env),
845
+ emitExprWide(node.right, env),
846
+ );
847
+ // JS gives back one of the operands, not true/false. The 0/1 below is only its truth, which would
848
+ // store `1` in place of a timestamp — so with a 64-bit side, keep the operand's value.
849
+ if (l.cType === 'i64' || r.cType === 'i64') {
850
+ if (l.cType === 'float' || r.cType === 'float') throw mix64Error();
851
+ if (l.cType === 'string' || r.cType === 'string')
852
+ throw aotError(
853
+ `AOT: "${op}" cannot mix a 64-bit time value with a string`,
854
+ 'keep both sides numbers, or write the branch out: {ms ? ms : 0}.',
855
+ );
856
+ if (l.isBool || r.isBool) throw bool64Error(`"${op}"`);
857
+ // `l` is read twice, which is safe: AOT expressions have no side effects, and the engine clock only
858
+ // moves in er_tick(), so a second Date.now() in the same expression reads the same value.
859
+ return {
860
+ code:
861
+ op === '||'
862
+ ? `(${l.code} ? ${l.code} : ${r.code})`
863
+ : `(${l.code} ? ${r.code} : ${l.code})`,
864
+ cType: 'i64',
865
+ };
866
+ }
867
+ return {
868
+ code: `(${asCond(l)} ${op} ${asCond(r)})`,
869
+ cType: 'int',
870
+ isBool: Boolean(l.isBool && r.isBool),
871
+ };
383
872
  }
384
873
  case 'ConditionalExpression': {
385
- const t = emitExpr(node.test, env);
386
- const c = emitExpr(node.consequent, env);
387
- const a = emitExpr(node.alternate, env);
388
- const cType =
389
- c.cType === 'float' || a.cType === 'float'
390
- ? 'float'
874
+ const t = emitExprWide(node.test, env);
875
+ const [c, a] = litPeers(
876
+ emitExprWide(node.consequent, env),
877
+ emitExprWide(node.alternate, env),
878
+ );
879
+ // `(ok ? 1 : "none")` is ill-typed C (int vs char*) and has no single printf spec either, so it
880
+ // has to be refused here rather than handed to the host compiler.
881
+ if ((c.cType === 'string') !== (a.cType === 'string'))
882
+ throw aotError(
883
+ 'AOT: a ternary cannot mix a string branch with a numeric one',
884
+ "both branches must be the same kind — quote the number to keep it text, e.g. {ok ? '1' : 'none'}.",
885
+ );
886
+ const either = k => c.cType === k || a.cType === k;
887
+ if (either('i64') && either('float')) throw mix64Error();
888
+ if (either('i64') && (c.isBool || a.isBool))
889
+ throw bool64Error('a ternary');
890
+ const cType = either('float')
891
+ ? 'float'
892
+ : either('i64')
893
+ ? 'i64'
391
894
  : c.cType === a.cType
392
895
  ? c.cType
393
896
  : 'int';
394
- return {code: `(${t.code} ? ${c.code} : ${a.code})`, cType};
897
+ return {
898
+ code: `(${asCond(t)} ? ${c.code} : ${a.code})`,
899
+ cType,
900
+ isBool: Boolean(c.isBool && a.isBool),
901
+ };
395
902
  }
396
903
  case 'MemberExpression': {
397
904
  // Static fold: member access that resolves to a compile-time constant (e.g. a .map item's `.key`).
398
905
  try {
399
- const v = evalStatic(node, env.consts ?? {});
400
- if (typeof v === 'number')
401
- return Number.isInteger(v)
402
- ? {code: String(v), cType: 'int'}
403
- : {code: `${v}f`, cType: 'float'};
906
+ const v = evalStatic(node, foldScope(env, env.consts ?? {}));
907
+ if (typeof v === 'number') return numConst(v);
404
908
  if (typeof v === 'string') return {code: cstr(v), cType: 'string'};
405
- if (typeof v === 'boolean') return {code: v ? '1' : '0', cType: 'int'};
909
+ if (typeof v === 'boolean')
910
+ return {code: v ? '1' : '0', cType: 'int', isBool: true};
406
911
  } catch {
407
912
  /* not static — fall through to the dynamic member forms below */
408
913
  }
@@ -486,26 +991,76 @@ function emitExprImpl(node, env) {
486
991
  );
487
992
  }
488
993
  case 'CallExpression': {
489
- // Math.* helpers → libm (the generated C includes <math.h> when these appear).
490
994
  const c = node.callee;
995
+ // Date.now() / performance.now() → the engine clock, as 64-bit whole milliseconds.
996
+ if (
997
+ c.type === 'MemberExpression' &&
998
+ !c.computed &&
999
+ c.object.type === 'Identifier' &&
1000
+ (c.object.name === 'Date' || c.object.name === 'performance') &&
1001
+ !env.shadowedClock?.has(node)
1002
+ ) {
1003
+ if (c.property.name === 'now')
1004
+ return {
1005
+ code:
1006
+ c.object.name === 'Date' ? 'app_date_now()' : 'app_perf_now()',
1007
+ cType: 'i64',
1008
+ };
1009
+ if (c.object.name === 'Date') throw dateObjectError();
1010
+ }
1011
+ if (
1012
+ c.type === 'Identifier' &&
1013
+ c.name === 'Date' &&
1014
+ !env.shadowedClock?.has(node)
1015
+ )
1016
+ throw dateObjectError();
1017
+ // Math.* helpers → libm (the generated C includes <math.h> when these appear).
491
1018
  if (c.type === 'MemberExpression' && c.object.name === 'Math') {
492
1019
  const fn = c.property.name;
493
- const a = node.arguments.map(x => emitExpr(x, env));
1020
+ const timeDiv = emitTimeRoundDiv(fn, node.arguments, env);
1021
+ if (timeDiv) return timeDiv;
1022
+ const intDiv = emitIntRoundDiv(fn, node.arguments, env);
1023
+ if (intDiv) return intDiv;
1024
+ const a = litPeers(...node.arguments.map(x => emitExprWide(x, env)));
1025
+ if (a.some(x => x.cType === 'i64')) return emitMath64(fn, a);
1026
+ // Math.abs / min / max of ints stay whole, as rounding one does: through a float they rounded past 2^24
1027
+ // and printed as %g. Beside a 64-bit value |INT_MIN| is kept, as JS keeps it.
1028
+ if (a.length && a.every(x => x.cType === 'int')) {
1029
+ if (fn === 'abs' && a.length === 1)
1030
+ return env.math64
1031
+ ? {code: `app_abs64(${a[0].code})`, cType: 'i64', wide: true}
1032
+ : {code: `app_abs(${a[0].code})`, cType: 'int'};
1033
+ if ((fn === 'min' || fn === 'max') && a.length === 2)
1034
+ return {
1035
+ code: `app_${fn}(${a[0].code}, ${a[1].code})`,
1036
+ cType: 'int',
1037
+ };
1038
+ }
1039
+ // An int is already whole; app_f2i truncates a float toward zero, with NaN as 0 and the int range
1040
+ // saturated, which is Math.trunc kept as an int.
1041
+ if (fn === 'trunc' && a.length === 1)
1042
+ return a[0].cType === 'int'
1043
+ ? {code: a[0].code, cType: 'int'}
1044
+ : {code: `app_f2i((float)(${a[0].code}))`, cType: 'int'};
494
1045
  const UNARY = {
495
1046
  sin: 'sinf',
496
1047
  cos: 'cosf',
497
1048
  tan: 'tanf',
498
1049
  sqrt: 'sqrtf',
499
1050
  abs: 'fabsf',
500
- round: 'roundf',
1051
+ round: 'app_roundf',
501
1052
  floor: 'floorf',
502
1053
  ceil: 'ceilf',
503
1054
  };
504
1055
  if (UNARY[fn] && a.length === 1) {
1056
+ const whole = fn === 'round' || fn === 'floor' || fn === 'ceil';
1057
+ // An int is already whole, so rounding leaves it as it is; a float round trip would lose digits.
1058
+ if (whole && a[0].cType === 'int')
1059
+ return {code: a[0].code, cType: 'int'};
505
1060
  const inner = `${UNARY[fn]}((float)(${a[0].code}))`;
506
- // round/floor/ceil yield a whole number — cast to int so %d / int assignments are correct.
507
- return fn === 'round' || fn === 'floor' || fn === 'ceil'
508
- ? {code: `((int)${inner})`, cType: 'int'}
1061
+ // round/floor/ceil yield a whole number, kept as an int so %d / int assignments are correct.
1062
+ return whole
1063
+ ? {code: `app_f2i(${inner})`, cType: 'int'}
509
1064
  : {code: inner, cType: 'float'};
510
1065
  }
511
1066
  const BINARY = {
@@ -525,15 +1080,67 @@ function emitExprImpl(node, env) {
525
1080
  'AOT: unsupported call expression in a dynamic expression',
526
1081
  );
527
1082
  }
1083
+ case 'NewExpression':
1084
+ if (
1085
+ node.callee.type === 'Identifier' &&
1086
+ node.callee.name === 'Date' &&
1087
+ !env.shadowedClock?.has(node)
1088
+ )
1089
+ throw dateObjectError();
1090
+ break;
528
1091
  }
529
1092
  throw new Error(
530
1093
  `AOT: unsupported expression "${node.type}" in a dynamic context`,
531
1094
  );
532
1095
  }
533
- const emitExpr = withLoc(emitExprImpl);
1096
+ /** emitExpr for the destinations that can hold a 64-bit timestamp: state, refs, locals, text, conditions. */
1097
+ const emitExprWide = withLoc(emitExprImpl);
1098
+
1099
+ /**
1100
+ * Lowers an expression for a destination that holds an int, a float or a string. C would narrow a 64-bit
1101
+ * value (a Date.now() / performance.now() timestamp, or a whole number past the int range) into one of those
1102
+ * without a warning, so it is refused here; the destinations that hold 64 bits call emitExprWide.
1103
+ */
1104
+ function emitExpr(node, env) {
1105
+ const e = emitExprWide(node, env);
1106
+ if (e.cType !== 'i64') return e;
1107
+ const err = aotError(
1108
+ 'AOT: a 64-bit value (Date.now() / performance.now(), or a whole number past ±2^31) cannot be used here',
1109
+ 'keep it in state, a ref or a local, compare it, or show it in text. Anywhere else, reduce it to a small number first — e.g. `ms % 1000`, or `Math.floor(ms / 1000) % 60`.',
1110
+ );
1111
+ if (node.loc) err.aotLoc = node.loc.start;
1112
+ throw err;
1113
+ }
534
1114
 
535
- const printfSpec = cType =>
536
- cType === 'string' ? '%s' : cType === 'float' ? '%g' : '%d';
1115
+ /** The C type a numeric state, ref or local slot of `cType` is declared with. */
1116
+ function cScalarType(cType) {
1117
+ if (cType === 'int') return 'int';
1118
+ if (cType === 'float') return 'float';
1119
+ if (cType === 'i64') return 'int64_t';
1120
+ throw new Error(`AOT internal: no C scalar type for "${cType}"`);
1121
+ }
1122
+
1123
+ /**
1124
+ * An expression as one printf spec and its argument. `%lld` needs a long long, and int64_t is `long` on 64-bit
1125
+ * Linux. A float goes through app_ftoa, which prints Infinity, -Infinity, NaN and 0 where %g prints inf, -inf,
1126
+ * nan and -0, and anything else as %g, into a buffer the call site lends it: one per float, so two floats in
1127
+ * one snprintf keep their own.
1128
+ */
1129
+ const printfPart = e =>
1130
+ e.cType === 'string'
1131
+ ? {spec: '%s', code: e.code}
1132
+ : e.cType === 'float'
1133
+ ? {spec: '%s', code: `app_ftoa((char[16]){0}, ${e.code})`}
1134
+ : e.cType === 'i64'
1135
+ ? {spec: '%lld', code: `(long long)(${e.code})`}
1136
+ : {spec: '%d', code: e.code};
1137
+
1138
+ /** C source with its string and char literals and its comments blanked, so a scan for a call sees only code. */
1139
+ const stripCLiterals = c =>
1140
+ c.replace(
1141
+ /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,
1142
+ ' ',
1143
+ );
537
1144
  const cTypeOfValue = v =>
538
1145
  typeof v === 'string'
539
1146
  ? 'string'
@@ -541,6 +1148,140 @@ const cTypeOfValue = v =>
541
1148
  ? 'float'
542
1149
  : 'int';
543
1150
 
1151
+ /** An aotError pinned to the expression that cannot be lowered to text (concatParts is not withLoc-wrapped). */
1152
+ function textShapeError(node, message, hint) {
1153
+ const e = aotError(message, hint);
1154
+ if (node.loc) e.aotLoc = node.loc.start;
1155
+ return e;
1156
+ }
1157
+
1158
+ /**
1159
+ * Text a constant renders as a standalone JSX child. React draws nothing for null, undefined or a
1160
+ * boolean (see flattenTextChildren in Flow A), which is not how `+` treats the same values — a
1161
+ * concatenation operand goes through String() instead.
1162
+ */
1163
+ const jsxChildText = v =>
1164
+ v === undefined || v === null || typeof v === 'boolean' ? '' : String(v);
1165
+
1166
+ /**
1167
+ * Splits a string-building `+` chain into printf parts, following JS's own left-to-right typing: a `+`
1168
+ * is a concatenation only once one of its sides is a string, so `n + 1 + ' ms'` still adds before it
1169
+ * appends. Parts are either a `literal` (folded into the format) or a `{spec, code}` pair (a runtime arg).
1170
+ *
1171
+ * @returns {{isString: boolean, parts: Array<{literal?: string, spec?: string, code?: string}>}}
1172
+ */
1173
+ function concatParts(node, env, scope, operand = false) {
1174
+ // The global `undefined` (the name is reserved — see normalizeUndefined) renders as nothing for a
1175
+ // standalone child and as "undefined" when concatenated. It is handled here, the one place it has a
1176
+ // text meaning, rather than in the shared constant fold, where every prop reader would inherit it.
1177
+ if (node.type === 'Identifier' && node.name === 'undefined')
1178
+ return {isString: false, parts: [{literal: operand ? 'undefined' : ''}]};
1179
+ try {
1180
+ const v = evalStatic(node, scope);
1181
+ return {
1182
+ isString: typeof v === 'string',
1183
+ parts: [{literal: operand ? String(v) : jsxChildText(v)}],
1184
+ };
1185
+ } catch {
1186
+ /* not a compile-time constant — split it below */
1187
+ }
1188
+ if (node.type === 'BinaryExpression' && node.operator === '+') {
1189
+ const l = concatParts(node.left, env, scope, true);
1190
+ const r = concatParts(node.right, env, scope, true);
1191
+ if (l.isString || r.isString)
1192
+ return {isString: true, parts: [...l.parts, ...r.parts]};
1193
+ }
1194
+ // A branch or operand that itself concatenates (`on ? 'a' + s : 'b'`, `ok && 'n=' + n`) would need a
1195
+ // format of its own, and one snprintf has one format. Say that here, before emitExpr's generic "not
1196
+ // supported in this position" fires — its hint that text buffers are fine is exactly wrong here.
1197
+ const concatenates = n =>
1198
+ n.type === 'BinaryExpression' &&
1199
+ n.operator === '+' &&
1200
+ concatParts(n, env, scope, true).isString;
1201
+ if (
1202
+ node.type === 'ConditionalExpression' &&
1203
+ (concatenates(node.test) ||
1204
+ concatenates(node.consequent) ||
1205
+ concatenates(node.alternate))
1206
+ )
1207
+ throw textShapeError(
1208
+ node,
1209
+ 'AOT: a ternary in text cannot concatenate inside its test or a branch',
1210
+ "each branch must be a single value — a literal, a state, or a number. Build the joined string first (a string useState set from a handler), or split it: {on ? 'a' : 'b'}{on ? s : ''}.",
1211
+ );
1212
+ if (
1213
+ node.type === 'LogicalExpression' &&
1214
+ (concatenates(node.left) || concatenates(node.right))
1215
+ )
1216
+ throw textShapeError(
1217
+ node,
1218
+ `AOT: "${node.operator}" in text cannot concatenate inside an operand`,
1219
+ "write it with plain values — {ok ? 'n=' : ''}{ok ? n : ''} — or build the joined string first in a string useState.",
1220
+ );
1221
+ const e = emitExprWide(node, env);
1222
+ // JS `&&`/`||` evaluate to one of their OPERANDS, and a ternary to one of its BRANCHES. The generated C
1223
+ // collapses a logical to 0/1 and gives a ternary a single slot, so text can only reproduce JS when the
1224
+ // operands agree in kind. Refuse rather than print a value the app never computed.
1225
+ if (node.type === 'LogicalExpression' && !e.isBool)
1226
+ throw textShapeError(
1227
+ node,
1228
+ `AOT: "${node.operator}" in text evaluates to one of its operands, not to true/false`,
1229
+ `\`a ${node.operator} b\` is a or b unless both sides are already booleans — the generated C only has 0/1. Write the branch out instead: {cond ? 'yes' : ''}.`,
1230
+ );
1231
+ if (
1232
+ node.type === 'ConditionalExpression' &&
1233
+ Boolean(emitExprWide(node.consequent, env).isBool) !==
1234
+ Boolean(emitExprWide(node.alternate, env).isBool)
1235
+ )
1236
+ throw textShapeError(
1237
+ node,
1238
+ 'AOT: a ternary in text mixes a boolean branch with a non-boolean one',
1239
+ 'JS renders those differently (`cond ? true : 5` is "true" or "5") but they share one C slot here. Make both branches the same kind.',
1240
+ );
1241
+ // A boolean draws nothing as a child but stringifies as an operand — same split as the constants above.
1242
+ // isString stays FALSE either way: a boolean is not a string in JS, so it must not by itself put an
1243
+ // enclosing `+` into concatenation mode (`on + n` adds, giving 0, and only then does `+ 'x'` append).
1244
+ // The %s form below is picked up only when some other operand of that `+` really is a string.
1245
+ if (e.isBool)
1246
+ return operand
1247
+ ? {
1248
+ isString: false,
1249
+ parts: [{spec: '%s', code: `((${e.code}) ? "true" : "false")`}],
1250
+ }
1251
+ : {isString: false, parts: [{literal: ''}]};
1252
+ return {
1253
+ isString: e.cType === 'string',
1254
+ parts: [printfPart(e)],
1255
+ };
1256
+ }
1257
+
1258
+ /**
1259
+ * Lowers an expression to a printf format + args for a char-buffer destination (a <Text> body, a string
1260
+ * state slot, a <TextInput value>). A string-building `+` chain becomes one spec per dynamic part with
1261
+ * the literals folded into the format; anything else is a single spec over its own value.
1262
+ *
1263
+ * @returns {{format: string, args: string[]}} `format` already has literal `%` escaped as `%%`.
1264
+ */
1265
+ function emitFormat(node, env, scope = env.consts ?? {}) {
1266
+ const visible = foldScope(env, scope);
1267
+ let format = '';
1268
+ const args = [];
1269
+ for (const part of concatParts(node, env, visible).parts) {
1270
+ if (part.literal !== undefined) format += part.literal.replace(/%/g, '%%');
1271
+ else {
1272
+ format += part.spec;
1273
+ args.push(part.code);
1274
+ }
1275
+ }
1276
+ return {format, args};
1277
+ }
1278
+
1279
+ /** Renders an emitFormat() result as snprintf's trailing arguments (a constant string keeps its `%s` form). */
1280
+ const formatArgs = ({format, args}) =>
1281
+ args.length
1282
+ ? `${cstr(format)}, ${args.join(', ')}`
1283
+ : `"%s", ${cstr(format.replace(/%%/g, '%'))}`;
1284
+
544
1285
  // ---------------------------------------------------------------------------------------------------
545
1286
  // AST helpers + collection passes — small predicates (isFn, fnReturnsJSX, …) and the up-front scans
546
1287
  // that walk the component body ONCE to gather what later emission needs: the module scope, useState,
@@ -577,6 +1318,29 @@ const SCREEN_FROM_ENV =
577
1318
  Number(process.env.ER_AOT_SCREEN_W) > 0 &&
578
1319
  Number(process.env.ER_AOT_SCREEN_H) > 0;
579
1320
 
1321
+ /**
1322
+ * Every name a variable declaration directly in `body` binds, destructuring included. In JS each one
1323
+ * shadows a module binding of that name for the whole function body, not only from its declaration on.
1324
+ */
1325
+ function declaredNames(body) {
1326
+ const names = [];
1327
+ const walk = p => {
1328
+ if (!p) return;
1329
+ if (p.type === 'Identifier') names.push(p.name);
1330
+ else if (p.type === 'ArrayPattern') p.elements.forEach(walk);
1331
+ else if (p.type === 'ObjectPattern')
1332
+ p.properties.forEach(q =>
1333
+ walk(q.type === 'RestElement' ? q.argument : q.value),
1334
+ );
1335
+ else if (p.type === 'AssignmentPattern') walk(p.left);
1336
+ else if (p.type === 'RestElement') walk(p.argument);
1337
+ };
1338
+ for (const stmt of body)
1339
+ if (stmt.type === 'VariableDeclaration')
1340
+ for (const d of stmt.declarations) walk(d.id);
1341
+ return names;
1342
+ }
1343
+
580
1344
  function moduleScope(program, screen, seed = {}) {
581
1345
  // `seed` pre-populates the scope (e.g. image imports as their asset-name strings) BEFORE module consts are
582
1346
  // folded, so a const that references one — `const DAYS = [{ icon: wxSun }]` — folds correctly.
@@ -593,7 +1357,7 @@ function moduleScope(program, screen, seed = {}) {
593
1357
  )
594
1358
  continue;
595
1359
  try {
596
- scope[decl.id.name] = evalStatic(decl.init, scope);
1360
+ scope[decl.id.name] = evalStatic(decl.init, withUndefined(scope));
597
1361
  } catch {
598
1362
  /* not a static const — skip */
599
1363
  }
@@ -647,7 +1411,7 @@ function inferItemStruct(items, name) {
647
1411
  * lookup keys stay the bare JS names (`count`), but the C field / array / count derive from `cField`
648
1412
  * (`<prefix>count`). prefix='' (the App) leaves storage names exactly as the JS names — backward compatible.
649
1413
  */
650
- function collectState(fnBody, scope, prefix = '') {
1414
+ function collectState(fnBody, scope, prefix = '', wide = NO_WIDE) {
651
1415
  const byName = new Map();
652
1416
  const bySetter = new Map();
653
1417
  for (const stmt of fnBody.body) {
@@ -716,7 +1480,24 @@ function collectState(fnBody, scope, prefix = '') {
716
1480
  `AOT: useHostValue("${name}") must be a number — its initial value evaluated to ${JSON.stringify(initVal)}`,
717
1481
  'useHostValue(0) / useHostValue(0.0) — the host feeds an int or float; booleans, strings, and objects are not supported.',
718
1482
  );
1483
+ // A scalar slot is an int, float, string or boolean. `null` or NaN would otherwise fold into an
1484
+ // initializer like `.value = NaN` — invalid C, with no location.
1485
+ if (
1486
+ initVal === undefined ||
1487
+ initVal === null ||
1488
+ (typeof initVal === 'number' && !Number.isFinite(initVal))
1489
+ ) {
1490
+ const e = aotError(
1491
+ `AOT: the initial value of state "${name}" is ${initVal === undefined ? 'undefined' : String(initVal)}`,
1492
+ "give it a concrete starting value: useState(0), useState(''), useState(false).",
1493
+ );
1494
+ if (initArg?.loc) e.aotLoc = initArg.loc.start;
1495
+ throw e;
1496
+ }
719
1497
  let cType = cTypeOfValue(initVal);
1498
+ // JS prints a boolean as "true"/"false" and React renders one as nothing, so text lowering has
1499
+ // to tell useState(false) from useState(0) — cTypeOfValue funnels both to 'int'.
1500
+ const isBool = typeof initVal === 'boolean';
720
1501
  // A numeric literal written with a decimal point or exponent (e.g. useState(70.0)) forces a FLOAT
721
1502
  // slot even though the value is integral — lets the state hold sub-integer values (a smooth drag)
722
1503
  // while the UI shows Math.round(value). (70.0 === 70 in JS, so we read the raw source to tell them apart.)
@@ -728,19 +1509,24 @@ function collectState(fnBody, scope, prefix = '') {
728
1509
  ) {
729
1510
  cType = 'float';
730
1511
  }
1512
+ // A setter stores a timestamp in it, so it holds 64 bits (see compileWidened).
1513
+ if (cType === 'int' && !isBool && wide.has(cField)) cType = 'i64';
731
1514
  // String scalar → a fixed char buffer in ErAppState; setters snprintf into it (see scalarAssign).
732
1515
  const initCode =
733
1516
  cType === 'string'
734
1517
  ? cstr(String(initVal))
735
1518
  : cType === 'float'
736
1519
  ? floatLit(initVal)
737
- : String(Number(initVal));
1520
+ : cType === 'i64'
1521
+ ? i64Lit(Number(initVal))
1522
+ : String(Number(initVal));
738
1523
  rec = {
739
1524
  name,
740
1525
  cField,
741
1526
  setter,
742
1527
  kind: 'scalar',
743
1528
  cType,
1529
+ isBool,
744
1530
  cMember: `s_state.${cField}`,
745
1531
  initCode,
746
1532
  host: isHost, // host-fed → also emit a public er_app_set_<name>() setter
@@ -1083,8 +1869,23 @@ function collectAnims(fnBody, scope, prefix = '') {
1083
1869
  decl.id.type === 'Identifier'
1084
1870
  ) {
1085
1871
  const initVal = init.arguments[0]
1086
- ? evalStatic(init.arguments[0], scope)
1872
+ ? evalStaticOrThrow(
1873
+ init.arguments[0],
1874
+ scope,
1875
+ `AOT: the initial value of useAnimatedValue "${decl.id.name}" must be a compile-time constant`,
1876
+ 'give it a finite starting number: useAnimatedValue(0).',
1877
+ )
1087
1878
  : 0;
1879
+ // An animated value is a float slot; null or a non-finite number would reach C as `NaNf`.
1880
+ // Refuse here, at the declaration, with its location.
1881
+ if (typeof initVal !== 'number' || !Number.isFinite(initVal)) {
1882
+ const e = aotError(
1883
+ `AOT: the initial value of useAnimatedValue "${decl.id.name}" is ${initVal === undefined ? 'undefined' : String(initVal)}`,
1884
+ 'give it a finite starting number: useAnimatedValue(0).',
1885
+ );
1886
+ if (init.arguments[0]?.loc) e.aotLoc = init.arguments[0].loc.start;
1887
+ throw e;
1888
+ }
1088
1889
  anims.set(decl.id.name, {
1089
1890
  cVar: `s_av_${prefix}${decl.id.name}`,
1090
1891
  initCode: floatLit(initVal),
@@ -1102,7 +1903,7 @@ function collectAnims(fnBody, scope, prefix = '') {
1102
1903
  * - NODE ref (`useRef()` / `useRef(null)`): holds an `ERNode*`, captured by `ref={r}` on an element and
1103
1904
  * used as the target of imperative calls like updateVector(r, …). kind === 'node'.
1104
1905
  */
1105
- function collectRefs(fnBody, scope, prefix = '') {
1906
+ function collectRefs(fnBody, scope, prefix = '', wide = NO_WIDE) {
1106
1907
  const refs = new Map();
1107
1908
  if (fnBody.type !== 'BlockStatement') return refs;
1108
1909
  for (const stmt of fnBody.body) {
@@ -1127,16 +1928,35 @@ function collectRefs(fnBody, scope, prefix = '') {
1127
1928
  });
1128
1929
  continue;
1129
1930
  }
1130
- const v = evalStatic(arg, scope);
1131
- if (typeof v !== 'number')
1132
- throw new Error(
1931
+ const v = evalStaticOrThrow(
1932
+ arg,
1933
+ scope,
1934
+ `AOT: useRef initial for "${decl.id.name}" must be a number (value ref) or null/empty (node ref)`,
1935
+ 'a value ref needs a compile-time number: useRef(0).',
1936
+ );
1937
+ if (typeof v !== 'number' || !Number.isFinite(v)) {
1938
+ const e = aotError(
1133
1939
  `AOT: useRef initial for "${decl.id.name}" must be a number (value ref) or null/empty (node ref)`,
1940
+ `got ${v === undefined ? 'undefined' : String(v)}.`,
1134
1941
  );
1135
- const cType = Number.isInteger(v) ? 'int' : 'float';
1942
+ if (arg.loc) e.aotLoc = arg.loc.start;
1943
+ throw e;
1944
+ }
1945
+ // A ref a timestamp is written to holds 64 bits (see compileWidened).
1946
+ const cType = !Number.isInteger(v)
1947
+ ? 'float'
1948
+ : wide.has(cVar)
1949
+ ? 'i64'
1950
+ : 'int';
1136
1951
  refs.set(decl.id.name, {
1137
1952
  cVar,
1138
1953
  cType,
1139
- initCode: cType === 'float' ? `${v}f` : String(v),
1954
+ initCode:
1955
+ cType === 'float'
1956
+ ? floatLit(v)
1957
+ : cType === 'i64'
1958
+ ? i64Lit(v)
1959
+ : String(v),
1140
1960
  kind: 'value',
1141
1961
  used: false,
1142
1962
  });
@@ -1174,7 +1994,25 @@ const ANIM_TRANSFORM_PROPS = {
1174
1994
  /** Formats a number as a valid C float literal (`1` → `1.0f`, not `1f` which doesn't compile). */
1175
1995
  function floatLit(n) {
1176
1996
  const v = Number(n);
1177
- return Number.isInteger(v) ? `${v}.0f` : `${v}f`;
1997
+ // `NaNf` / `Infinityf` / `undefinedf` are not C. Every numeric-literal path funnels through here, so a
1998
+ // value that slipped past its own boundary check still fails at generate time, never in the host compiler.
1999
+ if (!Number.isFinite(v))
2000
+ throw aotError(
2001
+ `AOT: a numeric constant folded to ${n === undefined ? 'undefined' : String(n)}, which has no C form`,
2002
+ 'the value must be a finite number.',
2003
+ );
2004
+ // Past about 3.4e38 a float literal overflows to Infinity, which C compilers warn about, so it is refused
2005
+ // as Infinity is. One too small for a float, which they also warn about, is written as the 0 it rounds to.
2006
+ const f = Math.fround(v);
2007
+ if (!Number.isFinite(f))
2008
+ throw aotError(
2009
+ `AOT: the numeric constant ${v} is past the float range`,
2010
+ 'a float holds up to about 3.4e38.',
2011
+ );
2012
+ if (f === 0 && v !== 0) return v < 0 ? '-0.0f' : '0.0f';
2013
+ // An exponent (`1e+21`) already makes a float literal; `.0` after one would not be C.
2014
+ const s = String(v);
2015
+ return /[.e]/.test(s) ? `${s}f` : `${s}.0f`;
1178
2016
  }
1179
2017
 
1180
2018
  /** The polynomial family of an `Easing.quad` / `Easing.cubic` node, for in/out/inOut composition. */
@@ -1311,12 +2149,12 @@ function argbLiteral(value) {
1311
2149
  function emitColorExpr(node, env) {
1312
2150
  if (node.type === 'StringLiteral') return colorLiteral(node.value);
1313
2151
  if (node.type === 'ConditionalExpression') {
1314
- const t = emitExpr(node.test, env).code;
2152
+ const t = asCond(emitExpr(node.test, env));
1315
2153
  return `((${t}) ? ${emitColorExpr(node.consequent, env)} : ${emitColorExpr(node.alternate, env)})`;
1316
2154
  }
1317
2155
  // A statically-resolvable color (a const string, or a theme token like `theme.card`) folds to a literal.
1318
2156
  try {
1319
- const s = evalStatic(node, env.consts ?? {});
2157
+ const s = evalStatic(node, foldScope(env, env.consts ?? {}));
1320
2158
  if (typeof s === 'string') return colorLiteral(s);
1321
2159
  } catch {
1322
2160
  /* not static — fall through to the error below */
@@ -1339,12 +2177,12 @@ function emitEnumExpr(node, table, env) {
1339
2177
  return c;
1340
2178
  }
1341
2179
  if (node.type === 'ConditionalExpression') {
1342
- const t = emitExpr(node.test, env).code;
2180
+ const t = asCond(emitExpr(node.test, env));
1343
2181
  return `((${t}) ? ${emitEnumExpr(node.consequent, table, env)} : ${emitEnumExpr(node.alternate, table, env)})`;
1344
2182
  }
1345
2183
  // A statically resolvable enum (a const string) folds to its constant.
1346
2184
  try {
1347
- const s = evalStatic(node, env.consts ?? {});
2185
+ const s = evalStatic(node, foldScope(env, env.consts ?? {}));
1348
2186
  if (typeof s === 'string' && table[s]) return table[s];
1349
2187
  } catch {
1350
2188
  /* not static — fall through */
@@ -1355,9 +2193,41 @@ function emitEnumExpr(node, table, env) {
1355
2193
  );
1356
2194
  }
1357
2195
 
2196
+ /** The diagnostic for a style key the AOT has no lowering for, static or dynamic. */
2197
+ const unknownStyleKey = key =>
2198
+ aotError(
2199
+ `AOT: style "${key}" is not supported by the AOT (no ERProps lowering)`,
2200
+ `Flow A may accept it; Flow B lowers these: ${STYLE_KEYS.join(', ')}.`,
2201
+ );
2202
+
2203
+ /**
2204
+ * Lowers one STATIC style key/value, telling the two failures apart: a key the AOT has no lowering for
2205
+ * at all, and a known key whose value it rejects. Both used to be indistinguishable from a state-driven
2206
+ * value, because a single `try` covered the constant fold and the lowering together.
2207
+ */
2208
+ function lowerStyleChecked(key, value) {
2209
+ // `{transform: undefined}` is a no-op in Flow A and in lowerStyle itself; the key is only judged when
2210
+ // there is a value to lower.
2211
+ if (value === undefined || value === null) return [];
2212
+ if (!isStyleKey(key)) throw unknownStyleKey(key);
2213
+ try {
2214
+ return lowerStyle({[key]: value});
2215
+ } catch (e) {
2216
+ // style-map's own value errors already name the key in some cases — don't say it twice.
2217
+ const msg = String(e.message);
2218
+ const why = msg.startsWith(`${key}: `) ? msg.slice(key.length + 2) : msg;
2219
+ throw aotError(`AOT: unsupported value for style "${key}": ${why}`);
2220
+ }
2221
+ }
2222
+
1358
2223
  /** Lowers one dynamic inline-style value to ERProps field assignment(s) (C expressions). */
1359
2224
  function lowerDynamicStyleValue(key, valueNode, env) {
1360
- const meta = DYN_FIELDS[key];
2225
+ // Own-property only: `DYN_FIELDS.toString` would otherwise hand back Object.prototype's method, look
2226
+ // like a known key, and emit `p.undefined = ...`.
2227
+ const meta = Object.hasOwn(DYN_FIELDS, key) ? DYN_FIELDS[key] : undefined;
2228
+ // An unknown key is unsupported outright — telling the author to "make it static" would only move
2229
+ // them on to the unknown-key error.
2230
+ if (!meta && !isStyleKey(key)) throw unknownStyleKey(key);
1361
2231
  if (!meta)
1362
2232
  throw aotError(
1363
2233
  `AOT: a state-driven value for style "${key}" is not supported (static only)`,
@@ -1365,23 +2235,23 @@ function lowerDynamicStyleValue(key, valueNode, env) {
1365
2235
  );
1366
2236
  if (meta.kind === 'color')
1367
2237
  return [{field: meta.field, code: emitColorExpr(valueNode, env)}];
1368
- if (meta.kind === 'opacity')
1369
- return [
1370
- {
1371
- field: meta.field,
1372
- code: `(uint8_t)((${emitExpr(valueNode, env).code}) * 255.0f)`,
1373
- },
1374
- ];
1375
2238
  if (meta.kind === 'enum')
1376
2239
  return [
1377
2240
  {field: meta.field, code: emitEnumExpr(valueNode, meta.table, env)},
1378
2241
  ];
1379
- return [
1380
- {
1381
- field: meta.field,
1382
- code: `app_round_dim(${emitExpr(valueNode, env).code})`,
1383
- },
1384
- ]; /* num */
2242
+ // Opacity and every size are numbers; C would take a char[] here as its address, or refuse it.
2243
+ const e = emitExpr(valueNode, env);
2244
+ if (e.cType === 'string') {
2245
+ const err = aotError(
2246
+ `AOT: style "${key}" needs a number, but the value is a string`,
2247
+ "JS would coerce the string; C cannot. Keep the state numeric — useState(10), not useState('10').",
2248
+ );
2249
+ if (valueNode.loc) err.aotLoc = valueNode.loc.start;
2250
+ throw err;
2251
+ }
2252
+ if (meta.kind === 'opacity')
2253
+ return [{field: meta.field, code: `app_opacity(${e.code})`}];
2254
+ return [{field: meta.field, code: `app_round_dim(${e.code})`}]; /* num */
1385
2255
  }
1386
2256
 
1387
2257
  /**
@@ -1431,6 +2301,8 @@ function collectStyleAssigns(openingElement, scope, env) {
1431
2301
  return null;
1432
2302
  };
1433
2303
  const apply = expr => {
2304
+ // RN ignores an undefined style or style-array entry; so does Flow A's flattenStyle.
2305
+ if (expr.type === 'Identifier' && expr.name === 'undefined') return;
1434
2306
  if (expr.type === 'ArrayExpression') {
1435
2307
  for (const e of expr.elements) if (e) apply(e);
1436
2308
  return;
@@ -1444,6 +2316,9 @@ function collectStyleAssigns(openingElement, scope, env) {
1444
2316
  const key = prop.computed
1445
2317
  ? evalStatic(prop.key, scope)
1446
2318
  : (prop.key.name ?? prop.key.value);
2319
+ // `{transform: undefined}` is a no-op in RN and Flow A.
2320
+ if (prop.value.type === 'Identifier' && prop.value.name === 'undefined')
2321
+ continue;
1447
2322
 
1448
2323
  // Animated value bound directly to a prop (opacity / backgroundColor / color), optionally through
1449
2324
  // an .interpolate({ inputRange, outputRange }) mapping.
@@ -1484,19 +2359,35 @@ function collectStyleAssigns(openingElement, scope, env) {
1484
2359
  if (handled) continue;
1485
2360
  }
1486
2361
 
2362
+ // Only the FOLD may fall back to the dynamic path. Letting lowerStyle's own failure fall
2363
+ // through too made an unknown style key surface as "state-driven value ... (static only)",
2364
+ // which sends the author looking for state that isn't there.
2365
+ let staticValue;
1487
2366
  try {
1488
- for (const a of lowerStyle({[key]: evalStatic(prop.value, scope)}))
1489
- fields.set(a.field, {dynamic: false, code: a.expr});
2367
+ staticValue = {v: evalStatic(prop.value, withUndefined(scope))};
1490
2368
  } catch {
2369
+ staticValue = null; // references state — lower it as a dynamic value
2370
+ }
2371
+ if (staticValue) {
2372
+ for (const a of lowerStyleChecked(key, staticValue.v))
2373
+ fields.set(a.field, {dynamic: false, code: a.expr});
2374
+ } else {
1491
2375
  for (const a of lowerDynamicStyleValue(key, prop.value, env))
1492
2376
  fields.set(a.field, {dynamic: true, code: a.code});
1493
2377
  }
1494
2378
  }
1495
2379
  return;
1496
2380
  }
1497
- // A StyleSheet reference / identifier resolving to a static style object.
1498
- for (const a of lowerStyle(evalStatic(expr, scope)))
1499
- fields.set(a.field, {dynamic: false, code: a.expr});
2381
+ // A StyleSheet reference / identifier resolving to a static style object. `style={null}` and a false
2382
+ // `cond && s` are valid RN and mean no style — Object.entries would throw on null.
2383
+ const resolved = evalStatic(expr, withUndefined(scope));
2384
+ if (resolved === null || resolved === undefined || resolved === false)
2385
+ return;
2386
+ for (const [k, v] of Object.entries(resolved)) {
2387
+ if (v === undefined || v === null) continue;
2388
+ for (const a of lowerStyleChecked(k, v))
2389
+ fields.set(a.field, {dynamic: false, code: a.expr});
2390
+ }
1500
2391
  };
1501
2392
  for (const attr of openingElement.attributes) {
1502
2393
  if (attr.type !== 'JSXAttribute' || attr.name.name !== 'style') continue;
@@ -1542,18 +2433,11 @@ function buildText(children, scope, env) {
1542
2433
  format += t.replace(/%/g, '%%');
1543
2434
  } else if (child.type === 'JSXExpressionContainer') {
1544
2435
  if (child.expression.type === 'JSXEmptyExpression') continue;
1545
- try {
1546
- const v = evalStatic(child.expression, scope); // constant → fold in
1547
- format += (v === undefined || v === null ? '' : String(v)).replace(
1548
- /%/g,
1549
- '%%',
1550
- );
1551
- } catch {
1552
- const e = emitExpr(child.expression, env); // references state → dynamic
1553
- format += printfSpec(e.cType);
1554
- args.push(e.code);
1555
- dynamic = true;
1556
- }
2436
+ // Constants fold into the literal; anything referencing state contributes a spec + arg.
2437
+ const f = emitFormat(child.expression, env, scope);
2438
+ format += f.format;
2439
+ args.push(...f.args);
2440
+ if (f.args.length) dynamic = true;
1557
2441
  } else if (child.type === 'JSXElement') {
1558
2442
  throw new Error(
1559
2443
  'AOT: nested <Text> / element children inside <Text> not yet supported (spans)',
@@ -1589,7 +2473,7 @@ function staticTextContent(children, scope) {
1589
2473
  c.expression.type !== 'JSXEmptyExpression'
1590
2474
  ) {
1591
2475
  const v = evalStatic(c.expression, scope); // throws if it references state
1592
- if (v !== undefined && v !== null) s += String(v);
2476
+ s += jsxChildText(v);
1593
2477
  } else if (c.type === 'JSXElement')
1594
2478
  throw aotError(
1595
2479
  'AOT: a nested <Text> span may not itself contain another <Text> (one level of spans only)',
@@ -1637,7 +2521,8 @@ function collectTextSpans(children, scope, env) {
1637
2521
  'spans must be static; keep dynamic text in its own single <Text> (no nested <Text> siblings).',
1638
2522
  );
1639
2523
  }
1640
- if (v !== undefined && v !== null)
2524
+ // React draws nothing for null, undefined, or a boolean child.
2525
+ if (v !== undefined && v !== null && typeof v !== 'boolean')
1641
2526
  spans.push(inheritSpan(cstr(String(v))));
1642
2527
  } else if (
1643
2528
  c.type === 'JSXElement' &&
@@ -1705,36 +2590,49 @@ function compileListOp(rec, arg, env) {
1705
2590
  for (const f of struct.fields) {
1706
2591
  const valNode = props.get(f.key);
1707
2592
  if (!valNode) continue;
1708
- const e = emitExpr(valNode, env);
1709
2593
  if (f.kind === 'string')
1710
2594
  lines.push(
1711
- ` snprintf(${arr}[${cnt}].${f.key}, sizeof(${arr}[${cnt}].${f.key}), "${printfSpec(e.cType)}", ${e.code});`,
2595
+ ` snprintf(${arr}[${cnt}].${f.key}, sizeof(${arr}[${cnt}].${f.key}), ${formatArgs(emitFormat(valNode, env))});`,
2596
+ );
2597
+ else
2598
+ lines.push(
2599
+ ` ${arr}[${cnt}].${f.key} = ${storeCode(emitExpr(valNode, env), f.kind)};`,
1712
2600
  );
1713
- else lines.push(` ${arr}[${cnt}].${f.key} = ${e.code};`);
1714
2601
  }
1715
2602
  lines.push(` ${cnt}++;`, ' }');
1716
2603
  }
1717
2604
  return lines;
1718
2605
  }
1719
- // setItems(items.slice(0, X)) — slice(0,-1) pops the last; slice(0,n) truncates to n.
2606
+ // setItems(items.slice(0, end)) keeps the first items, counted as JS counts them: a negative end counts back
2607
+ // from the length and stops at 0, and an end past the length (or none) keeps every item.
1720
2608
  if (
1721
2609
  arg.type === 'CallExpression' &&
1722
2610
  arg.callee.type === 'MemberExpression' &&
1723
2611
  arg.callee.object.name === rec.name &&
1724
2612
  arg.callee.property.name === 'slice'
1725
2613
  ) {
1726
- const end = arg.arguments[1];
1727
- if (
1728
- end?.type === 'UnaryExpression' &&
1729
- end.operator === '-' &&
1730
- end.argument.value === 1
1731
- )
1732
- return [` if (${cnt} > 0) ${cnt}--;`];
1733
- const e = emitExpr(end, env);
1734
- return [` ${cnt} = (${cnt} < (${e.code})) ? ${cnt} : (${e.code});`];
2614
+ const [start, end] = arg.arguments;
2615
+ if (start && staticInt(start, env) !== 0)
2616
+ throw aotError(
2617
+ `AOT: only ${rec.name}.slice(0, end) is supported on a list`,
2618
+ `a list is a fixed C array and a count, so a slice can only drop items from the end — e.g. ${rec.name}.slice(0, -1) drops the last one.`,
2619
+ );
2620
+ if (!end) return [];
2621
+ // A constant end is settled here. Past the capacity it keeps every item either way, so it is clamped
2622
+ // there and never needs 64-bit math.
2623
+ const k = staticInt(end, env);
2624
+ if (k !== null) {
2625
+ const kk = Math.max(-cap, Math.min(cap, k));
2626
+ if (kk === -1) return [` if (${cnt} > 0) ${cnt}--;`];
2627
+ if (kk >= 0) return [` ${cnt} = (${cnt} < ${kk}) ? ${cnt} : ${kk};`];
2628
+ return [` ${cnt} = app_slice_len(${cnt}, ${kk});`];
2629
+ }
2630
+ return [
2631
+ ` ${cnt} = app_slice_len(${cnt}, ${asInt(emitExpr(end, env))});`,
2632
+ ];
1735
2633
  }
1736
2634
  throw new Error(
1737
- `AOT: unsupported list operation on "${rec.name}" (use [...${rec.name}, item], ${rec.name}.slice(0, -1), or [])`,
2635
+ `AOT: unsupported list operation on "${rec.name}" (use [...${rec.name}, item], ${rec.name}.slice(0, n), or [])`,
1738
2636
  );
1739
2637
  }
1740
2638
 
@@ -1985,7 +2883,7 @@ function emitCompletionCb(fnNode, env, state, ctx) {
1985
2883
  : [{type: 'ExpressionStatement', expression: body}];
1986
2884
  const cctx = {stateChanged: false, animIdx: 0, out: ctx.out};
1987
2885
  const lines = compileStmts(list, {...env, locals}, state, cctx, ' ');
1988
- if (cctx.stateChanged) lines.push(' app_update();');
2886
+ if (cctx.stateChanged) lines.push(APP_UPDATE_CALL);
1989
2887
  ctx.out.animCbs.push({name, body: lines});
1990
2888
  return name;
1991
2889
  }
@@ -2028,7 +2926,7 @@ function compileAnimateStart(expr, env, state, ctx) {
2028
2926
  function evalStaticOr(node, env, dflt) {
2029
2927
  if (!node) return dflt;
2030
2928
  try {
2031
- return evalStatic(node, env.consts ?? {});
2929
+ return evalStatic(node, foldScope(env, env.consts ?? {}));
2032
2930
  } catch {
2033
2931
  return dflt;
2034
2932
  }
@@ -2039,11 +2937,78 @@ function blockList(node) {
2039
2937
  return node.type === 'BlockStatement' ? node.body : [node];
2040
2938
  }
2041
2939
 
2042
- /** Emits C to write a value into a scalar state slot: snprintf for a string buffer, plain assign else. */
2043
- function scalarAssign(rec, e, indent) {
2044
- if (rec.cType === 'string')
2045
- return `${indent}snprintf(${rec.cMember}, sizeof(${rec.cMember}), "${printfSpec(e.cType)}", ${e.code});`;
2046
- return `${indent}${rec.cMember} = ${e.code};`;
2940
+ /** Matches `<member>` as a whole C lvalue, so `s_state.label` does not also match `s_state.label2`. */
2941
+ const readsMember = member =>
2942
+ new RegExp(`(^|[^\\w.])${member.replace(/\./g, '\\.')}(?![\\w])`);
2943
+
2944
+ /**
2945
+ * Checks a value written to a numeric state or ref slot, whose C type came from its initial value. A 64-bit
2946
+ * timestamp written to an int slot is recorded in env.found, and compileWidened compiles again with that
2947
+ * slot widened to int64_t. It cannot go into a float or boolean slot (a 64-bit constant can go into a float
2948
+ * one), and a widened slot takes no floats.
2949
+ */
2950
+ function storeCheck(e, slotType, isBool, key, what, env) {
2951
+ if (e.cType === 'i64' && slotType !== 'i64') {
2952
+ if (slotType === 'int' && !isBool) {
2953
+ env.found.add(key);
2954
+ return;
2955
+ }
2956
+ if (e.lit && slotType === 'float') return;
2957
+ throw aotError(
2958
+ `AOT: a 64-bit time value cannot be stored in ${what}`,
2959
+ 'give it a whole-number initial value — useState(0) or useRef(0) — and it widens to hold the timestamp.',
2960
+ );
2961
+ }
2962
+ if (slotType === 'i64' && e.cType === 'float') throw mix64Error();
2963
+ }
2964
+
2965
+ /**
2966
+ * `e` as C for an int destination. A float goes through app_f2i: C's own conversion is undefined behavior
2967
+ * for NaN or a value past the int range.
2968
+ */
2969
+ const asInt = e => (e.cType === 'float' ? `app_f2i(${e.code})` : e.code);
2970
+
2971
+ /** `e` as C for a slot of `slotType`: an int slot takes a float the way asInt does. */
2972
+ const storeCode = (e, slotType) => (slotType === 'int' ? asInt(e) : e.code);
2973
+
2974
+ /**
2975
+ * The call a body that set state ends with, to re-apply what reads it. Whether anything reads state is known
2976
+ * only once the whole app is emitted, so the call is dropped then if nothing does.
2977
+ */
2978
+ const APP_UPDATE_CALL = ' app_update();';
2979
+
2980
+ /** Emits C to write an expression into a scalar state slot: snprintf for a string buffer (so a `+` chain
2981
+ * becomes a format + args), plain assign otherwise. */
2982
+ function scalarAssign(rec, node, env, indent) {
2983
+ if (rec.cType !== 'string') {
2984
+ // A 64-bit slot takes int `+ - *` worked out in 64 bits.
2985
+ const e = emitExprWide(
2986
+ node,
2987
+ rec.cType === 'i64' ? {...env, math64: true} : env,
2988
+ );
2989
+ storeCheck(
2990
+ e,
2991
+ rec.cType,
2992
+ rec.isBool,
2993
+ rec.cField,
2994
+ `state "${rec.name}"`,
2995
+ env,
2996
+ );
2997
+ return `${indent}${rec.cMember} = ${storeCode(e, rec.cType)};`;
2998
+ }
2999
+ const f = emitFormat(node, env);
3000
+ // snprintf's source and destination may not overlap (C11 7.21.6.6), and `setLabel(label + '!')` feeds
3001
+ // the slot its own contents. Build the new value in a temporary first — some embedded libcs write the
3002
+ // destination as they go, which would read back what they just overwrote.
3003
+ if (f.args.some(a => readsMember(rec.cMember).test(a)))
3004
+ return [
3005
+ `${indent}{`,
3006
+ `${indent} char next[sizeof(${rec.cMember})];`,
3007
+ `${indent} snprintf(next, sizeof(next), ${formatArgs(f)});`,
3008
+ `${indent} memcpy(${rec.cMember}, next, strlen(next) + 1);`,
3009
+ `${indent}}`,
3010
+ ].join('\n');
3011
+ return `${indent}snprintf(${rec.cMember}, sizeof(${rec.cMember}), ${formatArgs(f)});`;
2047
3012
  }
2048
3013
 
2049
3014
  /** True if `node` is a `<ref>.current` member access on a known value ref. */
@@ -2171,9 +3136,16 @@ function compileUpdateVector(expr, env, ctx, indent) {
2171
3136
  throw new Error(
2172
3137
  'AOT: updateVector dirtyRect must be a [x, y, w, h] array literal',
2173
3138
  );
2174
- const [x, y, w, h] = dirtyArg.elements.map(el => emitExpr(el, env).code);
3139
+ const rect = dirtyArg.elements.slice(0, 4).map(el => emitExpr(el, env));
3140
+ // A float edge can be NaN (a 0/0), which app_vector_dirty turns into no hint at all, so the engine's own
3141
+ // damage applies (what changed in the tape, or the whole node), where a zero-width hint would paint nothing:
3142
+ // the engine damages exactly the hinted rect. An int edge goes straight to the engine, which clips the
3143
+ // rect's corners to the int16 range it keeps them in.
3144
+ const fn = rect.some(e => e.cType === 'float')
3145
+ ? 'app_vector_dirty'
3146
+ : 'er_node_set_vector_dirty_rect';
2175
3147
  lines.push(
2176
- `${indent}er_node_set_vector_dirty_rect(${ref.cVar}, ${x}, ${y}, ${w}, ${h});`,
3148
+ `${indent}${fn}(${ref.cVar}, ${rect.map(e => e.code).join(', ')});`,
2177
3149
  );
2178
3150
  }
2179
3151
  return lines;
@@ -2188,7 +3160,16 @@ function compileTimerAdd(expr, env, state, ctx) {
2188
3160
  'AOT: a setInterval/setTimeout callback must be an inline function',
2189
3161
  'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).',
2190
3162
  );
2191
- const ms = expr.arguments[1] ? emitExpr(expr.arguments[1], env).code : '0';
3163
+ // A delay computed from a timestamp or a float goes through ToInt32 and a floor at 0, as Flow A's setTimeout
3164
+ // does.
3165
+ const delay = expr.arguments[1] ? emitExprWide(expr.arguments[1], env) : null;
3166
+ const ms = !delay
3167
+ ? '0'
3168
+ : delay.cType === 'i64'
3169
+ ? `app_delay_ms64(${delay.code})`
3170
+ : delay.cType === 'float'
3171
+ ? `app_delay_msf(${delay.code})`
3172
+ : delay.code;
2192
3173
  const repeat = expr.callee.name === 'setInterval';
2193
3174
  const slot = ctx.out.timerFns.length;
2194
3175
  const name = `er_timer_fn_${slot}`;
@@ -2215,8 +3196,13 @@ function inlineHelperCall(name, fn, args, env, state, ctx, indent) {
2215
3196
  'a helper called from a handler must use plain positional params (e.g. `(a, b) => …`) — destructuring or default params in the signature are not supported.',
2216
3197
  );
2217
3198
  if (args[i]) {
2218
- const e = emitExpr(args[i], env);
2219
- locals.set(p.name, {code: e.code, cType: e.cType});
3199
+ const e = emitExprWide(args[i], env);
3200
+ locals.set(p.name, {
3201
+ code: e.code,
3202
+ cType: e.cType,
3203
+ isBool: e.isBool,
3204
+ lit: e.lit,
3205
+ });
2220
3206
  }
2221
3207
  });
2222
3208
  const body = fn.body;
@@ -2224,10 +3210,18 @@ function inlineHelperCall(name, fn, args, env, state, ctx, indent) {
2224
3210
  body.type === 'BlockStatement'
2225
3211
  ? body.body
2226
3212
  : [{type: 'ExpressionStatement', expression: body}];
3213
+ // The helper's statements are spliced into the CALLER, so its `return` is not the caller's return —
3214
+ // reject it here even when the caller is an effect body, where a `return` would otherwise be allowed.
3215
+ // Both marks are scoped to this call, so they unwind with it rather than outliving a thrown error.
3216
+ const outerAllowReturn = ctx.allowReturn;
2227
3217
  ctx.inlining.add(name);
2228
- const lines = compileStmts(list, {...env, locals}, state, ctx, indent);
2229
- ctx.inlining.delete(name);
2230
- return lines;
3218
+ ctx.allowReturn = false;
3219
+ try {
3220
+ return compileStmts(list, {...env, locals}, state, ctx, indent);
3221
+ } finally {
3222
+ ctx.allowReturn = outerAllowReturn;
3223
+ ctx.inlining.delete(name);
3224
+ }
2231
3225
  }
2232
3226
 
2233
3227
  function compileHandlerExprImpl(expr, env, state, ctx, indent) {
@@ -2255,7 +3249,7 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
2255
3249
  expr.callee.name === 'clearTimeout')
2256
3250
  ) {
2257
3251
  return [
2258
- `${indent}er_timer_clear(${emitExpr(expr.arguments[0], env).code});`,
3252
+ `${indent}er_timer_clear(${asInt(emitExpr(expr.arguments[0], env))});`,
2259
3253
  ];
2260
3254
  }
2261
3255
  // `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
@@ -2265,17 +3259,80 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
2265
3259
  throw new Error(
2266
3260
  'AOT: the only assignment allowed in a handler is `ref.current = ...`',
2267
3261
  );
3262
+ const refEnv = r.cType === 'i64' ? {...env, math64: true} : env;
3263
+ const e = emitExprWide(expr.right, refEnv);
3264
+ if (expr.operator === '/=' && (r.cType === 'i64' || isTime64(e)))
3265
+ throw aotError(
3266
+ 'AOT: `/=` on a 64-bit time value is not supported',
3267
+ 'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.',
3268
+ );
3269
+ const m =
3270
+ expr.operator === '%=' && (r.cType === 'i64' || isTime64(e))
3271
+ ? constDivisor(expr.right, env)
3272
+ : null;
3273
+ storeCheck(
3274
+ e,
3275
+ r.cType,
3276
+ false,
3277
+ r.cVar,
3278
+ `ref "${expr.left.object.name}"`,
3279
+ env,
3280
+ );
3281
+ const whole = r.cType === 'int' || r.cType === 'i64';
3282
+ // `+= -= *=` on a whole-number ref go through the same checked math as `+ - *`, `/=` by a float divides
3283
+ // as floats, and `%=` over a float goes through fmodf as `%` does; a float result is stored the way any
3284
+ // int slot stores one.
3285
+ const step = {'+=': '+', '-=': '-', '*=': '*'}[expr.operator];
3286
+ const floatMod =
3287
+ expr.operator === '%=' && (r.cType === 'float' || e.cType === 'float');
3288
+ if (
3289
+ (whole && (step || (expr.operator === '/=' && e.cType === 'float'))) ||
3290
+ floatMod
3291
+ ) {
3292
+ const v = emitExprWide(
3293
+ {
3294
+ type: 'BinaryExpression',
3295
+ operator: step ?? expr.operator.slice(0, -1),
3296
+ left: expr.left,
3297
+ right: expr.right,
3298
+ loc: expr.loc,
3299
+ },
3300
+ refEnv,
3301
+ );
3302
+ return [`${indent}${r.cVar} = ${storeCode(v, r.cType)};`];
3303
+ }
3304
+ // `/=` and `%=` on an int ref by an int give JS's answer, kept whole (app_div / app_mod). A constant
3305
+ // divisor other than 0 and -1 needs no check.
3306
+ if (
3307
+ r.cType === 'int' &&
3308
+ e.cType === 'int' &&
3309
+ (expr.operator === '/=' || expr.operator === '%=')
3310
+ ) {
3311
+ const k = staticInt(expr.right, env);
3312
+ if (expr.operator === '/=' && (k === null || k === 0 || k === -1))
3313
+ return [`${indent}${r.cVar} = app_div(${r.cVar}, ${e.code});`];
3314
+ if (expr.operator === '%=' && (k === 0 || k === -1))
3315
+ return [`${indent}${r.cVar} = 0;`];
3316
+ if (expr.operator === '%=' && k === null)
3317
+ return [`${indent}${r.cVar} = app_mod(${r.cVar}, ${e.code});`];
3318
+ }
3319
+ // ±1 leaves no remainder, 0 is JS's NaN, which is 0 here, and INT64_MIN % -1 overflows in C.
3320
+ if (m === 0 || m === 1 || m === -1) return [`${indent}${r.cVar} = 0;`];
2268
3321
  return [
2269
- `${indent}${r.cVar} ${expr.operator} ${emitExpr(expr.right, env).code};`,
3322
+ `${indent}${r.cVar} ${expr.operator} ${expr.operator === '=' ? storeCode(e, r.cType) : e.code};`,
2270
3323
  ];
2271
3324
  }
2272
- // `ref.current++` / `ref.current--`.
3325
+ // `ref.current++` / `ref.current--`; a whole-number ref steps through the checked `+ 1` / `- 1`.
2273
3326
  if (expr.type === 'UpdateExpression') {
2274
3327
  const r = refTarget(expr.argument, env);
2275
3328
  if (!r)
2276
3329
  throw new Error(
2277
3330
  'AOT: the only ++/-- allowed in a handler is on `ref.current`',
2278
3331
  );
3332
+ if (r.cType === 'int' || r.cType === 'i64')
3333
+ return [
3334
+ `${indent}${r.cVar} = ${CHECKED_OP[expr.operator[0]]}${r.cType === 'i64' ? '64' : ''}(${r.cVar}, 1);`,
3335
+ ];
2279
3336
  return [`${indent}${r.cVar}${expr.operator};`];
2280
3337
  }
2281
3338
  // Animated.*(…).start() — single timing/spring/decay OR a sequence/parallel/stagger/delay/loop
@@ -2327,20 +3384,23 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
2327
3384
  throw new Error(
2328
3385
  'AOT: updater function must be a single expression (for now)',
2329
3386
  );
2330
- return [scalarAssign(rec, emitExpr(arg.body, {...env, locals}), indent)];
3387
+ return [scalarAssign(rec, arg.body, {...env, locals}, indent)];
2331
3388
  }
2332
- return [scalarAssign(rec, emitExpr(arg, env), indent)];
3389
+ return [scalarAssign(rec, arg, env, indent)];
2333
3390
  }
2334
3391
  const compileHandlerExpr = withLoc(compileHandlerExprImpl);
2335
3392
 
2336
3393
  /**
2337
3394
  * Compiles a list of handler statements to C lines. Supports: `const x = expr` (a C local, visible to
2338
3395
  * later statements), `if (cond) {...} else {...}`, state setters, and Animated.*(...).start(). `ctx`
2339
- * accumulates `stateChanged` (→ trailing app_update) and `animIdx` (unique ERAnimConfig locals).
3396
+ * accumulates `stateChanged` (→ trailing app_update), `animIdx` (unique ERAnimConfig locals) and
3397
+ * `usedReturn` (an early `return` was lowered, so the body needs a C function of its own). `ctx.allowReturn`
3398
+ * and `ctx.bodyList` mark which body a `return` may exit and which statement of it is the tail.
2340
3399
  */
2341
3400
  function compileStmts(list, env, state, ctx, indent) {
2342
3401
  const lines = [];
2343
- for (const st of list) {
3402
+ for (let si = 0; si < list.length; si++) {
3403
+ const st = list[si];
2344
3404
  if (st.type === 'VariableDeclaration') {
2345
3405
  for (const decl of st.declarations) {
2346
3406
  if (decl.id.type !== 'Identifier')
@@ -2349,7 +3409,12 @@ function compileStmts(list, env, state, ctx, indent) {
2349
3409
  );
2350
3410
  if (!decl.init)
2351
3411
  throw new Error('AOT: a handler local must have an initializer');
2352
- const cName = `l_${decl.id.name}`;
3412
+ // A cleanup closure outlives the call that created it, so when one is emitted (a dep-driven
3413
+ // effect) the body's own locals become file-scope slots instead of C locals.
3414
+ const hoist = ctx.hoist && list === ctx.bodyList;
3415
+ const cName = hoist
3416
+ ? `${ctx.hoist.prefix}${decl.id.name}`
3417
+ : `l_${decl.id.name}`;
2353
3418
  // `const id = setInterval/setTimeout(…)` → an int timer-id local (so a later clearInterval(id) resolves).
2354
3419
  if (
2355
3420
  decl.init.type === 'CallExpression' &&
@@ -2358,8 +3423,9 @@ function compileStmts(list, env, state, ctx, indent) {
2358
3423
  decl.init.callee.name === 'setTimeout')
2359
3424
  ) {
2360
3425
  // The id is only needed for a later clear*(); a mount effect drops its cleanup, so mark it used.
3426
+ if (hoist) ctx.hoist.decls.push(`static int ${cName};`);
2361
3427
  lines.push(
2362
- `${indent}int ${cName} = ${compileTimerAdd(decl.init, env, state, ctx)};`,
3428
+ `${indent}${hoist ? '' : 'int '}${cName} = ${compileTimerAdd(decl.init, env, state, ctx)};`,
2363
3429
  `${indent}(void)${cName};`,
2364
3430
  );
2365
3431
  env = {
@@ -2371,28 +3437,79 @@ function compileStmts(list, env, state, ctx, indent) {
2371
3437
  };
2372
3438
  continue;
2373
3439
  }
2374
- const e = emitExpr(decl.init, env);
2375
- lines.push(
2376
- `${indent}${e.cType === 'float' ? 'float' : 'int'} ${cName} = ${e.code};`,
2377
- );
3440
+ const e = emitExprWide(decl.init, env);
3441
+ if (e.cType === 'string') {
3442
+ // A string local gets a buffer of its own rather than a char* into a state slot: a pointer alias
3443
+ // would let `setLabel(t + '!')` read and write the same bytes behind readsMember's back — and
3444
+ // `int l_t = s_state.label` was never valid C to begin with.
3445
+ if (hoist)
3446
+ ctx.hoist.decls.push(`static char ${cName}[${LIST_STR_CAP}];`);
3447
+ else lines.push(`${indent}char ${cName}[${LIST_STR_CAP}];`);
3448
+ lines.push(
3449
+ `${indent}snprintf(${cName}, sizeof(${cName}), "%s", ${e.code});`,
3450
+ );
3451
+ } else {
3452
+ if (e.cType !== 'int' && e.cType !== 'float' && e.cType !== 'i64')
3453
+ throw aotError(
3454
+ 'AOT: a handler local must hold a number, a boolean or a string',
3455
+ 'bind the value itself — e.g. `const id = item.id` — rather than a list item or a node ref.',
3456
+ );
3457
+ const cType = cScalarType(e.cType);
3458
+ if (hoist) ctx.hoist.decls.push(`static ${cType} ${cName};`);
3459
+ lines.push(
3460
+ `${indent}${hoist ? '' : cType + ' '}${cName} = ${e.code};`,
3461
+ );
3462
+ }
2378
3463
  env = {
2379
3464
  ...env,
2380
3465
  locals: new Map(env.locals).set(decl.id.name, {
2381
3466
  code: cName,
2382
3467
  cType: e.cType,
3468
+ isBool: e.isBool,
2383
3469
  }),
2384
3470
  };
2385
3471
  }
2386
3472
  continue;
2387
3473
  }
2388
- // An effect's cleanup `return () => …` — not run on an MCU (the app never unmounts), so drop it. (A
2389
- // dep-driven effect that needs cleanup on re-run isn't supported yet; mount-only effects use this.)
3474
+ // A `return` in an effect body. The LAST statement of the body is the cleanup `return () => …` (or a
3475
+ // bare `return`). A mount effect drops it — the app never unmounts, so it would never run. A dep-driven
3476
+ // effect re-runs, and React runs the previous cleanup first, so `ctx.cleanup` compiles it into a
3477
+ // companion C function and arms it here. Any EARLIER return is a guard that has to actually exit — it
3478
+ // emits `return;` and flags the body so compileEffect gives it a C function of its own.
2390
3479
  if (st.type === 'ReturnStatement') {
2391
- if (ctx.allowReturn) continue;
2392
- throw new Error('AOT: `return` is only allowed as an effect cleanup');
3480
+ if (!ctx.allowReturn) {
3481
+ const e = aotError(
3482
+ 'AOT: `return` is only supported inside a useEffect body',
3483
+ 'a handler, timer, animation or inlined-helper body cannot return early — flatten the logic into if/else.',
3484
+ );
3485
+ if (st.loc) e.aotLoc = st.loc.start;
3486
+ throw e;
3487
+ }
3488
+ const isTail = list === ctx.bodyList && si === list.length - 1;
3489
+ if (ctx.depDriven && isFn(st.argument) && !isTail) {
3490
+ const e = aotError(
3491
+ 'AOT: a useEffect cleanup must be the last statement of the effect body',
3492
+ 'a cleanup returned from inside an `if` would be dropped. Return `undefined` from the guard and put the single `return () => …` at the end of the body.',
3493
+ );
3494
+ if (st.loc) e.aotLoc = st.loc.start;
3495
+ throw e;
3496
+ }
3497
+ if (isTail) {
3498
+ if (ctx.cleanup && isFn(st.argument)) {
3499
+ ctx.cleanup.emit(st.argument, env);
3500
+ lines.push(`${indent}${ctx.cleanup.armed} = 1;`);
3501
+ }
3502
+ continue;
3503
+ }
3504
+ ctx.usedReturn = true;
3505
+ lines.push(`${indent}return;`);
3506
+ continue;
2393
3507
  }
2394
3508
  if (st.type === 'IfStatement') {
2395
- lines.push(`${indent}if (${emitExpr(st.test, env).code})`, `${indent}{`);
3509
+ lines.push(
3510
+ `${indent}if (${asCond(emitExprWide(st.test, env))})`,
3511
+ `${indent}{`,
3512
+ );
2396
3513
  lines.push(
2397
3514
  ...compileStmts(
2398
3515
  blockList(st.consequent),
@@ -2421,7 +3538,7 @@ function compileStmts(list, env, state, ctx, indent) {
2421
3538
  if (st.type !== 'ExpressionStatement')
2422
3539
  throw aotError(
2423
3540
  `AOT: unsupported statement "${st.type}" in event handler`,
2424
- 'a handler supports only `const x = …` locals, `if (…) { … } else { … }`, and expression statements (setters / ref writes / updateVector / Animated…start). Loops (for/while), switch, try/catch, and early return are not lowered — precompute values or flatten the logic into if/else.',
3541
+ 'a handler supports only `const x = …` locals, `if (…) { … } else { … }`, and expression statements (setters / ref writes / updateVector / Animated…start). Loops (for/while), switch and try/catch are not lowered — precompute values or flatten the logic into if/else.',
2425
3542
  );
2426
3543
  lines.push(...compileHandlerExpr(st.expression, env, state, ctx, indent));
2427
3544
  }
@@ -2435,6 +3552,7 @@ function compileStmts(list, env, state, ctx, indent) {
2435
3552
  * then again from app_update whenever a SCALAR dep changes (compared against a stored prev). The body is
2436
3553
  * compiled WITHOUT a trailing app_update — it runs INSIDE app_update / at mount, so re-applying state it
2437
3554
  * sets happens on the next app_update (one-frame), and it can never re-enter app_update (no infinite loop).
3555
+ * A dep-driven `return () => …` becomes `er_effect_N_cleanup()`, run at the top of the next re-run.
2438
3556
  */
2439
3557
  function compileEffect(eff, env, state, out) {
2440
3558
  const body = eff.fn.body;
@@ -2446,10 +3564,26 @@ function compileEffect(eff, env, state, out) {
2446
3564
  !eff.deps ||
2447
3565
  (eff.deps.type === 'ArrayExpression' && eff.deps.elements.length === 0);
2448
3566
  if (isMount) {
2449
- const ctx = {stateChanged: false, animIdx: 0, out, allowReturn: true};
3567
+ const ctx = {
3568
+ stateChanged: false,
3569
+ animIdx: 0,
3570
+ out,
3571
+ allowReturn: true,
3572
+ bodyList: stmts,
3573
+ };
2450
3574
  const lines = compileStmts(stmts, env, state, ctx, ' ');
2451
- if (ctx.stateChanged) lines.push(' app_update();');
2452
- out.mountEffects.push(...lines);
3575
+ if (!ctx.usedReturn) {
3576
+ if (ctx.stateChanged) lines.push(APP_UPDATE_CALL);
3577
+ out.mountEffects.push(...lines);
3578
+ return;
3579
+ }
3580
+ // A mount body is normally inlined into er_app_build, where a `return` would skip every later mount
3581
+ // effect — so one with an early return gets a C function of its own, and the app_update it may owe
3582
+ // moves to the call site (past the return, it would otherwise be dead code).
3583
+ const name = `er_effect_${out.effN++}`;
3584
+ out.effectFns.push({name, body: lines});
3585
+ out.mountEffects.push(` ${name}();`);
3586
+ if (ctx.stateChanged) out.mountEffects.push(APP_UPDATE_CALL);
2453
3587
  return;
2454
3588
  }
2455
3589
  if (eff.deps.type !== 'ArrayExpression')
@@ -2461,25 +3595,67 @@ function compileEffect(eff, env, state, out) {
2461
3595
  const name = `er_effect_${id}`;
2462
3596
  const deps = eff.deps.elements.map(d => {
2463
3597
  if (!d) throw aotError('AOT: a useEffect dependency must be an expression');
2464
- const e = emitExpr(d, env);
2465
- if (e.cType !== 'int' && e.cType !== 'float' && e.cType !== 'string')
3598
+ const e = emitExprWide(d, env);
3599
+ if (!['int', 'float', 'i64', 'string'].includes(e.cType))
2466
3600
  throw aotError(
2467
3601
  'AOT: useEffect dependencies must be scalar (number / bool / string)',
2468
3602
  'depend on scalar state values; object/array dependencies are not yet supported.',
2469
3603
  );
2470
3604
  return e;
2471
3605
  });
2472
- const ctx = {stateChanged: false, animIdx: 0, out, allowReturn: true};
3606
+ // React runs the previous cleanup before re-running a dep-driven effect. The cleanup closes over the
3607
+ // body's locals, which have to outlive the call, so they become file-scope slots; an `armed` flag says
3608
+ // whether the last run actually reached its `return () => …` (a guarded run that returned early did not).
3609
+ const tail = stmts[stmts.length - 1];
3610
+ const hasCleanup = tail?.type === 'ReturnStatement' && isFn(tail.argument);
3611
+ const armed = `s_eff${id}_armed`;
3612
+ const ctx = {
3613
+ stateChanged: false,
3614
+ animIdx: 0,
3615
+ out,
3616
+ allowReturn: true,
3617
+ bodyList: stmts,
3618
+ depDriven: true,
3619
+ };
3620
+ if (hasCleanup) {
3621
+ ctx.hoist = {prefix: `s_eff${id}_l_`, decls: out.effectDecls};
3622
+ ctx.cleanup = {
3623
+ armed,
3624
+ emit: (fn, cenv) => {
3625
+ const cbody = fn.body;
3626
+ const clist =
3627
+ cbody.type === 'BlockStatement'
3628
+ ? cbody.body
3629
+ : [{type: 'ExpressionStatement', expression: cbody}];
3630
+ const cctx = {stateChanged: false, animIdx: 0, out};
3631
+ out.effectFns.push({
3632
+ name: `${name}_cleanup`,
3633
+ body: compileStmts(clist, cenv, state, cctx, ' '),
3634
+ });
3635
+ },
3636
+ };
3637
+ out.effectDecls.push(`static int ${armed};`);
3638
+ }
3639
+ const bodyLines = compileStmts(stmts, env, state, ctx, ' ');
2473
3640
  out.effectFns.push({
2474
3641
  name,
2475
- body: compileStmts(stmts, env, state, ctx, ' '),
3642
+ body: hasCleanup
3643
+ ? [
3644
+ ` if (${armed})`,
3645
+ ' {',
3646
+ ` ${armed} = 0;`,
3647
+ ` ${name}_cleanup();`,
3648
+ ' }',
3649
+ ...bodyLines,
3650
+ ]
3651
+ : bodyLines,
2476
3652
  });
2477
3653
  // A static "previous value" per dep; snapshot at mount, then app_update detects changes against it.
2478
3654
  deps.forEach((d, j) =>
2479
3655
  out.effectDecls.push(
2480
3656
  d.cType === 'string'
2481
3657
  ? `static char s_eff${id}_d${j}[${LIST_STR_CAP}];`
2482
- : `static ${d.cType === 'float' ? 'float' : 'int'} s_eff${id}_d${j};`,
3658
+ : `static ${cScalarType(d.cType)} s_eff${id}_d${j};`,
2483
3659
  ),
2484
3660
  );
2485
3661
  const snap = (j, d) =>
@@ -2497,7 +3673,7 @@ function compileEffect(eff, env, state, out) {
2497
3673
  ` if (strcmp(s_eff${id}_d${j}, ${d.code}) != 0) { ${snap(j, d)}; er_changed = 1; }`,
2498
3674
  );
2499
3675
  else {
2500
- const t = d.cType === 'float' ? 'float' : 'int';
3676
+ const t = cScalarType(d.cType);
2501
3677
  check.push(
2502
3678
  ` ${t} er_d${j} = ${d.code}; if (er_d${j} != s_eff${id}_d${j}) { s_eff${id}_d${j} = er_d${j}; er_changed = 1; }`,
2503
3679
  );
@@ -2526,7 +3702,7 @@ function compileHandler(fnNode, env, state, out, pan = null) {
2526
3702
  if (gestureParam) henv = {...henv, gesture: gestureParam, pan};
2527
3703
  const ctx = {stateChanged: false, animIdx: 0, out};
2528
3704
  const stmts = compileStmts(list, henv, state, ctx, ' ');
2529
- if (ctx.stateChanged) stmts.push(' app_update();'); // re-apply state-dependent props once
3705
+ if (ctx.stateChanged) stmts.push(APP_UPDATE_CALL); // re-apply state-dependent props once
2530
3706
  return stmts;
2531
3707
  }
2532
3708
 
@@ -2926,7 +4102,7 @@ function extractProps(openingElement, scope, env) {
2926
4102
  try {
2927
4103
  props[attr.name.name] = {static: true, value: evalStatic(node, scope)};
2928
4104
  } catch {
2929
- props[attr.name.name] = {static: false, ...emitExpr(node, env)};
4105
+ props[attr.name.name] = {static: false, ...emitExprWide(node, env)};
2930
4106
  }
2931
4107
  }
2932
4108
  return props;
@@ -3009,8 +4185,14 @@ function emitComponent(el, scope, out, env, state, opts) {
3009
4185
  childrenRef = {kind: 'props', name: param.name};
3010
4186
  }
3011
4187
 
3012
- const childScope = {...scope};
3013
- const childLocals = new Map(env.locals);
4188
+ // A child component is a module-level function: its body resolves names against MODULE scope, not the
4189
+ // caller's locals. Copying the caller's scope here would let an App-local const shadow a module one
4190
+ // inside the child, which JavaScript never does.
4191
+ const childScope = {...(env.moduleConsts ?? scope)};
4192
+ // A child is a module-level function: it closes over module scope and receives everything else
4193
+ // through props. Starting from the caller's locals let App's memos and dynamic consts leak in —
4194
+ // and then masked the child's own `const` of the same name.
4195
+ const childLocals = new Map();
3014
4196
  // Callback props bound here resolve to the CALLER's function (node + caller env/state) so the child can
3015
4197
  // use them as event handlers (onPress={onTap}); inherit any the caller itself received (forwarding).
3016
4198
  const fnProps = new Map(env.fnProps);
@@ -3026,8 +4208,18 @@ function emitComponent(el, scope, out, env, state, opts) {
3026
4208
  state: d.state ?? state,
3027
4209
  });
3028
4210
  else if (d.static) childScope[name] = d.value;
3029
- else
3030
- childLocals.set(name, {code: d.code, cType: d.cType, struct: d.struct});
4211
+ else {
4212
+ childLocals.set(name, {
4213
+ code: d.code,
4214
+ cType: d.cType,
4215
+ struct: d.struct,
4216
+ isBool: d.isBool, // keep boolean-ness across the prop boundary (extractProps supplies it)
4217
+ });
4218
+ // A dynamic prop is a RUNTIME binding. Every constant fold in the child (styles, colors, enums,
4219
+ // svg attrs, text) consults childScope first, so a module const of the same name must not be
4220
+ // left there to win — the fold would silently emit the module value instead of the prop.
4221
+ delete childScope[name];
4222
+ }
3031
4223
  }
3032
4224
  const children = childNodes.length
3033
4225
  ? {nodes: childNodes, scope, env, ref: childrenRef}
@@ -3039,16 +4231,47 @@ function emitComponent(el, scope, out, env, state, opts) {
3039
4231
  // exactly like a React component — it receives everything else through props. All initials/values fold
3040
4232
  // against the child's static-prop scope. prefix is per-instance; the App keeps the bare (unprefixed) names.
3041
4233
  const prefix = `c${out.instN++}_`;
4234
+ // Fold the child's own statically-derived body consts, the way compileSourceImpl does for App. Without
4235
+ // this a `const L = …` in a child body either failed to resolve or, when a module const shared the
4236
+ // name, silently rendered the MODULE value — the child's declaration must shadow it.
4237
+ if (fn.body.type === 'BlockStatement') {
4238
+ // As in App: the body's own names, hook bindings included, shadow module ones before anything folds.
4239
+ for (const name of declaredNames(fn.body.body)) delete childScope[name];
4240
+ for (const stmt of fn.body.body) {
4241
+ if (stmt.type !== 'VariableDeclaration' || stmt.kind !== 'const')
4242
+ continue;
4243
+ for (const decl of stmt.declarations) {
4244
+ if (decl.id.type !== 'Identifier' || !decl.init) continue;
4245
+ if (childLocals.has(decl.id.name)) continue; // a dynamic prop of that name is already bound
4246
+ try {
4247
+ childScope[decl.id.name] = evalStatic(
4248
+ decl.init,
4249
+ withUndefined(childScope),
4250
+ );
4251
+ } catch {
4252
+ // Dynamic (state-derived, useMemo, …): the child's binding shadows any module const of the
4253
+ // same name, so that const must not stay visible — a hook initializer or text reading it would
4254
+ // silently get the module value. A memo re-binds it below; anything else is an unresolved name.
4255
+ delete childScope[decl.id.name];
4256
+ }
4257
+ }
4258
+ }
4259
+ }
4260
+
3042
4261
  const childAnims = collectAnims(fn.body, childScope, prefix);
3043
- const childRefs = collectRefs(fn.body, childScope, prefix);
4262
+ const childRefs = collectRefs(fn.body, childScope, prefix, env.wide);
3044
4263
  const childPans = collectPanResponders(fn.body, prefix);
3045
4264
  const childCallbacks = collectCallbacks(fn.body);
3046
4265
  const childMemos = collectMemos(fn.body);
3047
4266
  let childState = state;
3048
4267
  if (usesState(fn)) {
3049
- childState = collectState(fn.body, childScope, prefix);
4268
+ childState = collectState(fn.body, childScope, prefix, env.wide);
3050
4269
  out.childStateRecords.push(...childState.byName.values());
4270
+ for (const name of childState.byName.keys()) delete childScope[name];
3051
4271
  }
4272
+ // The child's own refs and animated values are runtime bindings too (see compileSourceImpl).
4273
+ for (const name of [...childAnims.keys(), ...childRefs.keys()])
4274
+ delete childScope[name];
3052
4275
  out.childRefs.push(...childRefs.values());
3053
4276
  out.childAnims.push(...childAnims.values());
3054
4277
 
@@ -3073,8 +4296,13 @@ function emitComponent(el, scope, out, env, state, opts) {
3073
4296
  try {
3074
4297
  childScope[name] = evalStatic(expr, childScope);
3075
4298
  } catch {
3076
- const e = emitExpr(expr, childEnv);
3077
- childLocals.set(name, {code: `(${e.code})`, cType: e.cType});
4299
+ const e = emitExprWide(expr, childEnv);
4300
+ childLocals.set(name, {
4301
+ code: `(${e.code})`,
4302
+ cType: e.cType,
4303
+ isBool: e.isBool,
4304
+ });
4305
+ delete childScope[name]; // a runtime binding beats a module const of its name in every fold
3078
4306
  }
3079
4307
  }
3080
4308
  for (const eff of collectEffects(fn.body)) {
@@ -3126,12 +4354,42 @@ function emitMap(call, parentVar, scope, out, env, state) {
3126
4354
  parentVar,
3127
4355
  iterScope,
3128
4356
  out,
3129
- {...env, consts: iterScope},
4357
+ rowEnv(env, [itemName, idxName], iterScope),
3130
4358
  state,
3131
4359
  );
3132
4360
  });
3133
4361
  }
3134
4362
 
4363
+ /**
4364
+ * The env for one `.map` row. Its callback params (item, index) shadow every outer binding of the same
4365
+ * name — a JS arrow parameter always does — so those names leave every name-keyed map (state, locals,
4366
+ * callbacks, helpers, …) and the row's own binding wins: in `consts`, or in `ownLocals` for a pooled
4367
+ * row's struct item.
4368
+ */
4369
+ function rowEnv(env, params, consts, ownLocals = null) {
4370
+ const names = params.filter(Boolean);
4371
+ const drop = m => {
4372
+ if (!m || !names.some(n => m.has(n))) return m;
4373
+ const c = new Map(m);
4374
+ for (const n of names) c.delete(n);
4375
+ return c;
4376
+ };
4377
+ return {
4378
+ ...env,
4379
+ consts,
4380
+ state: drop(env.state),
4381
+ refs: drop(env.refs),
4382
+ anims: drop(env.anims),
4383
+ locals: ownLocals ?? drop(env.locals),
4384
+ callbacks: drop(env.callbacks),
4385
+ fnProps: drop(env.fnProps),
4386
+ pans: drop(env.pans),
4387
+ helpers: drop(env.helpers),
4388
+ svgImports: drop(env.svgImports),
4389
+ children: names.includes(env.children?.ref?.name) ? null : env.children,
4390
+ };
4391
+ }
4392
+
3135
4393
  /**
3136
4394
  * `{listState.map((item, i) => <Row/>)}` over a STATE array of variable length. Pre-allocates a fixed
3137
4395
  * pool of `cap` rows (no runtime malloc); each row k binds `item` to `s_<name>[k]` (a struct local) and
@@ -3146,8 +4404,12 @@ function emitDynamicMap(call, rec, parentVar, scope, out, env, state) {
3146
4404
  const retJSX = componentReturnJSX(cb);
3147
4405
  for (let k = 0; k < rec.cap; k++) {
3148
4406
  const iterScope = {...scope};
4407
+ // The item is a runtime local (a struct slot), so a same-named module const must not shadow it
4408
+ // in any fold inside the row — see the dynamic-prop note in emitComponent.
4409
+ if (itemName) delete iterScope[itemName];
3149
4410
  if (idxName) iterScope[idxName] = k; // the index is a compile-time literal per pooled row
3150
4411
  const locals = new Map(env.locals);
4412
+ if (idxName) locals.delete(idxName); // the index is a per-row literal in iterScope
3151
4413
  if (itemName)
3152
4414
  locals.set(itemName, {
3153
4415
  code: `${rec.arrayName}[${k}]`,
@@ -3158,7 +4420,7 @@ function emitDynamicMap(call, rec, parentVar, scope, out, env, state) {
3158
4420
  parentVar,
3159
4421
  iterScope,
3160
4422
  out,
3161
- {...env, consts: iterScope, locals},
4423
+ rowEnv(env, [itemName, idxName], iterScope, locals),
3162
4424
  state,
3163
4425
  {
3164
4426
  displayCode: `(${k} < ${rec.countMember})`,
@@ -3196,7 +4458,7 @@ function emitChildren(children, parentVar, scope, out, env, state) {
3196
4458
  if (cond)
3197
4459
  emitElementInto(expr.right, parentVar, scope, out, env, state);
3198
4460
  } catch {
3199
- const code = emitExpr(expr.left, env).code;
4461
+ const code = asCond(emitExpr(expr.left, env));
3200
4462
  emitElementInto(expr.right, parentVar, scope, out, env, state, {
3201
4463
  displayCode: code,
3202
4464
  });
@@ -3219,7 +4481,7 @@ function emitChildren(children, parentVar, scope, out, env, state) {
3219
4481
  state,
3220
4482
  );
3221
4483
  } catch {
3222
- const code = emitExpr(expr.test, env).code;
4484
+ const code = asCond(emitExpr(expr.test, env));
3223
4485
  if (expr.consequent.type === 'JSXElement')
3224
4486
  emitElementInto(
3225
4487
  expr.consequent,
@@ -3388,8 +4650,15 @@ function svgAttrs(openingElement, scope, env) {
3388
4650
  else if (vn.type === 'StringLiteral') out[name] = vn.value;
3389
4651
  else if (vn.type === 'JSXExpressionContainer') {
3390
4652
  try {
3391
- out[name] = evalStatic(vn.expression, scope);
4653
+ out[name] = evalStatic(vn.expression, withUndefined(scope));
3392
4654
  } catch {
4655
+ // A state-driven `d` is unsupported whatever it is built from, and pathEntries carries the
4656
+ // diagnostic that names the fix (use Arc/Circle/Rect/Line). Emitting it first would replace that
4657
+ // with whatever generic reason the expression itself fails for.
4658
+ if (name === 'd') {
4659
+ out[name] = {dyn: null, node: vn.expression};
4660
+ continue;
4661
+ }
3393
4662
  // Keep the raw expression node too: color paint attrs (fill/stroke) lower via emitColorExpr (→ ARGB),
3394
4663
  // not the generic numeric `dyn` code, so a dynamic color resolves to a uint, not a char*.
3395
4664
  out[name] = {
@@ -3502,13 +4771,13 @@ function gradAttr(v, scope, env, what) {
3502
4771
  node.consequent.type === 'ObjectExpression' &&
3503
4772
  nullish(node.alternate)
3504
4773
  ) {
3505
- cond = emitExpr(node.test, env).code;
4774
+ cond = asCond(emitExpr(node.test, env));
3506
4775
  node = node.consequent;
3507
4776
  } else if (
3508
4777
  node.alternate.type === 'ObjectExpression' &&
3509
4778
  nullish(node.consequent)
3510
4779
  ) {
3511
- cond = `!(${emitExpr(node.test, env).code})`;
4780
+ cond = `!(${asCond(emitExpr(node.test, env))})`;
3512
4781
  node = node.alternate;
3513
4782
  } else
3514
4783
  throw new Error(
@@ -3519,7 +4788,7 @@ function gradAttr(v, scope, env, what) {
3519
4788
  node.operator === '&&' &&
3520
4789
  node.right.type === 'ObjectExpression'
3521
4790
  ) {
3522
- cond = emitExpr(node.left, env).code;
4791
+ cond = asCond(emitExpr(node.left, env));
3523
4792
  node = node.right;
3524
4793
  }
3525
4794
  const spec = gradSpec(node, scope, env, what);
@@ -4163,11 +5432,13 @@ function compileValueHandler(
4163
5432
  out,
4164
5433
  cType = 'int',
4165
5434
  valueCode2 = null,
5435
+ isBool = false,
4166
5436
  ) {
4167
5437
  const param =
4168
5438
  fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
4169
5439
  const locals = new Map(env.locals);
4170
- if (param) locals.set(param, {code: valueCode, cType});
5440
+ // A <Switch> hands its callback a boolean; carry that so `'on=' + v` prints true/false, not 1/0.
5441
+ if (param) locals.set(param, {code: valueCode, cType, isBool});
4171
5442
  // A second parameter (a RANGE <Dial>'s low end) binds the same way, so `onChange={(hi, lo) => …}`
4172
5443
  // lowers to data->value / data->value_start with no object allocated on device.
4173
5444
  const param2 =
@@ -4180,7 +5451,7 @@ function compileValueHandler(
4180
5451
  ? body.body
4181
5452
  : [{type: 'ExpressionStatement', expression: body}];
4182
5453
  const stmts = compileStmts(list, {...env, locals}, state, ctx, ' ');
4183
- if (ctx.stateChanged) stmts.push(' app_update();');
5454
+ if (ctx.stateChanged) stmts.push(APP_UPDATE_CALL);
4184
5455
  return stmts;
4185
5456
  }
4186
5457
 
@@ -4536,7 +5807,7 @@ function emitSwitch(el, scope, out, env, state) {
4536
5807
  } catch {
4537
5808
  dynAssigns.push({
4538
5809
  field: 'switch_value',
4539
- code: `(uint8_t)((${emitExpr(valueNode, env).code}) ? 1 : 0)`,
5810
+ code: `(uint8_t)((${asCond(emitExpr(valueNode, env))}) ? 1 : 0)`,
4540
5811
  });
4541
5812
  }
4542
5813
  }
@@ -4566,10 +5837,19 @@ function emitSwitch(el, scope, out, env, state) {
4566
5837
  'controlled switch: <Switch value={on} onValueChange={(v) => setOn(v)} />',
4567
5838
  );
4568
5839
  const handlerName = `er_handler_${out.handlers.length}`;
4569
- const toggled = `(!(${emitExpr(valueNode, env).code}))`; // the engine toggles on press → param is !value
5840
+ const toggled = `(!(${asCond(emitExpr(valueNode, env))}))`; // the engine toggles on press → param is !value
4570
5841
  out.handlers.push({
4571
5842
  name: handlerName,
4572
- body: compileValueHandler(onChangeFn, toggled, env, state, out),
5843
+ body: compileValueHandler(
5844
+ onChangeFn,
5845
+ toggled,
5846
+ env,
5847
+ state,
5848
+ out,
5849
+ 'int',
5850
+ null,
5851
+ true,
5852
+ ),
4573
5853
  });
4574
5854
  out.build.push(
4575
5855
  ` er_event_set(${v}, ER_EVENT_PRESS, ${handlerName}, NULL);`,
@@ -4617,15 +5897,16 @@ function emitTextInput(el, scope, out, env, state) {
4617
5897
  field: 'cursor_color',
4618
5898
  expr: colorLiteral(String(evalStatic(node, scope))),
4619
5899
  });
4620
- else if (name === 'editable') {
5900
+ else if (name === 'editable' || name === 'secureTextEntry') {
5901
+ const field = name === 'editable' ? 'editable' : 'secure_text_entry';
4621
5902
  try {
4622
5903
  staticAssigns.push({
4623
- field: 'editable',
5904
+ field,
4624
5905
  expr: evalStatic(node, scope) ? '1' : '0',
4625
5906
  });
4626
5907
  } catch {
4627
5908
  dynAssigns.push({
4628
- field: 'editable',
5909
+ field,
4629
5910
  code: `(uint8_t)((${emitExpr(node, env).code}) ? 1 : 0)`,
4630
5911
  });
4631
5912
  }
@@ -4633,7 +5914,6 @@ function emitTextInput(el, scope, out, env, state) {
4633
5914
  [
4634
5915
  'autoFocus',
4635
5916
  'keyboardType',
4636
- 'secureTextEntry',
4637
5917
  'maxLength',
4638
5918
  'multiline',
4639
5919
  'autoCapitalize',
@@ -4648,7 +5928,7 @@ function emitTextInput(el, scope, out, env, state) {
4648
5928
  } else
4649
5929
  throw aotError(
4650
5930
  `AOT: <TextInput> prop "${name}" is not supported`,
4651
- 'supported props: value, onChangeText, placeholder, placeholderTextColor, cursorColor, editable, style.',
5931
+ 'supported props: value, onChangeText, placeholder, placeholderTextColor, cursorColor, editable, secureTextEntry, style.',
4652
5932
  );
4653
5933
  }
4654
5934
 
@@ -4656,17 +5936,8 @@ function emitTextInput(el, scope, out, env, state) {
4656
5936
  // state-driven value re-synced each app_update.
4657
5937
  let text = null;
4658
5938
  if (valueNode) {
4659
- try {
4660
- const cv = evalStatic(valueNode, scope);
4661
- text = {
4662
- dynamic: false,
4663
- format: (cv == null ? '' : String(cv)).replace(/%/g, '%%'),
4664
- args: [],
4665
- };
4666
- } catch {
4667
- const e = emitExpr(valueNode, env);
4668
- text = {dynamic: true, format: printfSpec(e.cType), args: [e.code]};
4669
- }
5939
+ const f = emitFormat(valueNode, env, scope);
5940
+ text = {dynamic: f.args.length > 0, format: f.format, args: f.args};
4670
5941
  }
4671
5942
 
4672
5943
  const isDynamic = dynAssigns.length > 0 || (text && text.dynamic);
@@ -5221,6 +6492,7 @@ function touchablePressFades(
5221
6492
  }
5222
6493
 
5223
6494
  function emitNodeImpl(el, scope, out, env, state, opts = {}) {
6495
+ el = omitUndefinedAttrs(el, scope, env);
5224
6496
  const tag = resolveTag(el.openingElement);
5225
6497
  if (tag === 'Svg') return emitSvg(el, scope, out, env, state, opts);
5226
6498
  if (tag === 'Switch') return emitSwitch(el, scope, out, env, state);
@@ -5513,6 +6785,34 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
5513
6785
  if (tag !== 'Text') emitChildren(el.children, v, scope, out, env, state);
5514
6786
  return v;
5515
6787
  }
6788
+ /**
6789
+ * `el` without the attributes whose value folds to `undefined` in this scope — typically a prop a child
6790
+ * component was never given. Flow A omits an undefined prop, so every reader has to see it as absent;
6791
+ * read as a value, `visible` hid the node and `placeholder` printed the word "undefined". This is the one
6792
+ * place that rule lives: every element reaches its reader through here. A copy is returned only when
6793
+ * something is dropped, because the same JSX node is emitted once per scope (each .map row, each
6794
+ * component instance) and one scope's answer must not leak into another's.
6795
+ */
6796
+ function omitUndefinedAttrs(el, scope, env) {
6797
+ const attrs = el.openingElement.attributes;
6798
+ // Built on first use: the runtime-aware scope, plus the global `undefined` (a reserved name — see
6799
+ // normalizeUndefined), so `SHOW ? true : undefined` with SHOW false folds too.
6800
+ let fold = null;
6801
+ const kept = attrs.filter(a => {
6802
+ if (a.type !== 'JSXAttribute' || a.value?.type !== 'JSXExpressionContainer')
6803
+ return true;
6804
+ fold ??= Object.assign(Object.create(foldScope(env, scope)), {undefined});
6805
+ try {
6806
+ return evalStatic(a.value.expression, fold) !== undefined;
6807
+ } catch {
6808
+ return true; // not a compile-time value — its reader decides
6809
+ }
6810
+ });
6811
+ return kept.length === attrs.length
6812
+ ? el
6813
+ : {...el, openingElement: {...el.openingElement, attributes: kept}};
6814
+ }
6815
+
5516
6816
  const emitNode = withLoc(emitNodeImpl);
5517
6817
 
5518
6818
  // ---------------------------------------------------------------------------------------------------
@@ -5742,6 +7042,93 @@ function stripTypeScript(root) {
5742
7042
  return root;
5743
7043
  }
5744
7044
 
7045
+ /**
7046
+ * One pass over the parsed program that fixes what `undefined` means before anything is compiled.
7047
+ *
7048
+ * - A JSX attribute whose value is `{undefined}` is DROPPED. Flow A's buildProps omits an undefined prop
7049
+ * (`props[k] !== undefined`), so the node keeps its default — `visible={undefined}` stays visible. Doing
7050
+ * it here gives the twenty-odd prop readers that view at once, instead of each deciding what an
7051
+ * undefined value means (one hid the node, one crashed on Object.entries(undefined)).
7052
+ * A value that only becomes undefined in some scope — a prop a child was never given — is dropped per
7053
+ * emission by omitUndefinedAttrs. This literal pass still matters for <Svg> shapes, which bypass it.
7054
+ * - A BINDING named `undefined` is refused. JS allows shadowing the global, but Flow B gives `undefined`
7055
+ * a meaning of its own (an omitted prop, empty text), and a shadowing local would silently lose to it.
7056
+ */
7057
+ function normalizeUndefined(ast) {
7058
+ const reserved = id => {
7059
+ if (id?.type !== 'Identifier' || id.name !== 'undefined') return;
7060
+ const e = aotError(
7061
+ 'AOT: `undefined` cannot be used as a name',
7062
+ 'Flow B reads `undefined` as the global everywhere — an omitted prop, or empty text — so a binding with that name would never be read. Rename it.',
7063
+ );
7064
+ if (id.loc) e.aotLoc = id.loc.start;
7065
+ throw e;
7066
+ };
7067
+ const pattern = p => {
7068
+ if (!p) return;
7069
+ if (p.type === 'Identifier') reserved(p);
7070
+ else if (p.type === 'ArrayPattern') p.elements.forEach(pattern);
7071
+ else if (p.type === 'ObjectPattern')
7072
+ p.properties.forEach(q =>
7073
+ pattern(q.type === 'RestElement' ? q.argument : q.value),
7074
+ );
7075
+ else if (p.type === 'AssignmentPattern') pattern(p.left);
7076
+ else if (p.type === 'RestElement') pattern(p.argument);
7077
+ };
7078
+ const isUndefinedAttr = a =>
7079
+ a.type === 'JSXAttribute' &&
7080
+ a.value?.type === 'JSXExpressionContainer' &&
7081
+ a.value.expression.type === 'Identifier' &&
7082
+ a.value.expression.name === 'undefined';
7083
+ const SKIP = new Set([
7084
+ 'loc',
7085
+ 'start',
7086
+ 'end',
7087
+ 'extra',
7088
+ 'leadingComments',
7089
+ 'trailingComments',
7090
+ 'innerComments',
7091
+ ]);
7092
+ const visit = node => {
7093
+ if (!node || typeof node.type !== 'string') return;
7094
+ switch (node.type) {
7095
+ case 'VariableDeclarator':
7096
+ pattern(node.id);
7097
+ break;
7098
+ case 'FunctionDeclaration':
7099
+ case 'FunctionExpression':
7100
+ case 'ArrowFunctionExpression':
7101
+ case 'ObjectMethod':
7102
+ case 'ClassMethod':
7103
+ if (node.id) reserved(node.id);
7104
+ node.params.forEach(pattern);
7105
+ break;
7106
+ case 'CatchClause':
7107
+ pattern(node.param);
7108
+ break;
7109
+ case 'ClassDeclaration':
7110
+ case 'ClassExpression':
7111
+ if (node.id) reserved(node.id);
7112
+ break;
7113
+ case 'ImportSpecifier':
7114
+ case 'ImportDefaultSpecifier':
7115
+ case 'ImportNamespaceSpecifier':
7116
+ reserved(node.local);
7117
+ break;
7118
+ case 'JSXOpeningElement':
7119
+ node.attributes = node.attributes.filter(a => !isUndefinedAttr(a));
7120
+ break;
7121
+ }
7122
+ for (const key of Object.keys(node)) {
7123
+ if (SKIP.has(key)) continue;
7124
+ const v = node[key];
7125
+ if (Array.isArray(v)) v.forEach(visit);
7126
+ else if (v && typeof v.type === 'string') visit(v);
7127
+ }
7128
+ };
7129
+ visit(ast);
7130
+ }
7131
+
5745
7132
  /** Parse an app entry to a JS+JSX AST, transparently stripping TypeScript when the entry is .ts/.tsx. */
5746
7133
  function parseApp(src, opts = {}) {
5747
7134
  const ts = isTsEntry(opts);
@@ -5754,10 +7141,15 @@ function parseApp(src, opts = {}) {
5754
7141
  * Compiles a Flow B app's JSX (or TSX) source to C.
5755
7142
  * @param {string} src The App.jsx/App.tsx source text.
5756
7143
  * @param {string} demo Demo name (only used in the generated-by header comment).
7144
+ * @param {object} opts compileSource's options.
7145
+ * @param {Set<string>} wide State/ref slots to declare 64-bit (see compileWidened).
7146
+ * @param {Set<string>} found Collects the int slots a 64-bit timestamp was stored in.
5757
7147
  * @returns {{c: string, h: string, nodes: number, state: number, handlers: number, updates: number}}
5758
7148
  */
5759
- function compileSourceImpl(src, demo = 'app', opts = {}) {
7149
+ function compileSourceImpl(src, demo, opts, wide, found) {
5760
7150
  const ast = parseApp(src, opts);
7151
+ normalizeUndefined(ast);
7152
+ const shadowedClock = findShadowedClockCalls(ast);
5761
7153
 
5762
7154
  const screen = opts.screen ?? {width: SCREEN_W, height: SCREEN_H};
5763
7155
  // Image imports first, so their asset-name strings seed the module scope BEFORE its consts fold (a const
@@ -5768,27 +7160,37 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5768
7160
  [...imageImports].map(([local, imp]) => [local, imp.name]),
5769
7161
  );
5770
7162
  const scope = moduleScope(ast.program, screen, imageSeed);
7163
+ // Module bindings ALONE, before App's own consts are folded in below. A child component is declared at
7164
+ // module level, so its body closes over these — not over whatever App happens to have shadowed.
7165
+ const moduleConsts = {...scope};
5771
7166
  const component = findComponent(ast.program);
5772
7167
  // Fold statically-derived component-local consts (e.g. `const compact = screen.width < 400`) into the
5773
7168
  // const scope, so responsive `if` branches and styles can switch on them at compile time. Dynamic consts
5774
7169
  // (state-derived, useMemo, etc.) throw here and are skipped — they're handled later by memos/emitExpr.
7170
+ // Every name the body declares — a hook's destructured state included — shadows the module binding
7171
+ // before any local folds, or `const copy = r` would capture a module `r` that state `r` hides.
7172
+ for (const name of declaredNames(component.body.body)) delete scope[name];
5775
7173
  for (const stmt of component.body.body) {
5776
7174
  if (stmt.type !== 'VariableDeclaration' || stmt.kind !== 'const') continue;
5777
7175
  for (const decl of stmt.declarations) {
5778
- if (decl.id.type !== 'Identifier' || !decl.init || decl.id.name in scope)
5779
- continue;
7176
+ if (decl.id.type !== 'Identifier' || !decl.init) continue;
5780
7177
  try {
5781
- scope[decl.id.name] = evalStatic(decl.init, scope);
7178
+ scope[decl.id.name] = evalStatic(decl.init, withUndefined(scope));
5782
7179
  } catch {
5783
- /* dynamic const — resolved later */
7180
+ // Dynamic (state-derived, useMemo, …). A memo is re-bound below and a plain derived const is not
7181
+ // supported — either way a same-named module const must not stay visible to the folds, or the
7182
+ // JSX quietly renders the module value. Mirrors the child-component path.
7183
+ delete scope[decl.id.name];
5784
7184
  }
5785
7185
  }
5786
7186
  }
5787
- const state = collectState(component.body, scope);
7187
+ const state = collectState(component.body, scope, '', wide);
7188
+ for (const name of state.byName.keys()) delete scope[name];
5788
7189
  const rootJSX = findReturnJSX(component.body, scope);
5789
7190
 
5790
7191
  const anims = collectAnims(component.body, scope);
5791
- const refs = collectRefs(component.body, scope);
7192
+ const refs = collectRefs(component.body, scope, '', wide);
7193
+ for (const name of [...anims.keys(), ...refs.keys()]) delete scope[name];
5792
7194
  const pans = collectPanResponders(component.body);
5793
7195
  const callbacks = collectCallbacks(component.body);
5794
7196
  const memos = collectMemos(component.body);
@@ -5800,6 +7202,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5800
7202
  state: state.byName,
5801
7203
  locals: new Map(),
5802
7204
  consts: scope,
7205
+ moduleConsts, // what an inlined child component sees (see emitComponent)
5803
7206
  anims,
5804
7207
  refs,
5805
7208
  pans,
@@ -5808,6 +7211,9 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5808
7211
  imageNames,
5809
7212
  svgImports,
5810
7213
  svgArtifacts: opts.svgArtifacts || {},
7214
+ wide,
7215
+ found,
7216
+ shadowedClock,
5811
7217
  };
5812
7218
  // Resolve memos in declaration order: constant-fold into the const scope when possible, else register a
5813
7219
  // derived C expression in locals so each reference inlines it (the AOT has no per-render cache — the dep
@@ -5816,8 +7222,13 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5816
7222
  try {
5817
7223
  scope[name] = evalStatic(expr, scope);
5818
7224
  } catch {
5819
- const e = emitExpr(expr, env);
5820
- env.locals.set(name, {code: `(${e.code})`, cType: e.cType});
7225
+ const e = emitExprWide(expr, env);
7226
+ env.locals.set(name, {
7227
+ code: `(${e.code})`,
7228
+ cType: e.cType,
7229
+ isBool: e.isBool,
7230
+ });
7231
+ delete scope[name]; // a runtime binding beats a module const of its name in every fold
5821
7232
  }
5822
7233
  }
5823
7234
  const out = {
@@ -5883,7 +7294,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5883
7294
  ? ` char ${f.key}[${LIST_STR_CAP}];`
5884
7295
  : ` ${f.kind} ${f.key};`;
5885
7296
  const itemInit = (item, struct) =>
5886
- `{ ${struct.fields.map(f => (f.kind === 'string' ? cstr(String(item[f.key] ?? '')) : f.kind === 'float' ? `${Number(item[f.key]) || 0}f` : String(Math.round(Number(item[f.key]) || 0)))).join(', ')} }`;
7297
+ `{ ${struct.fields.map(f => (f.kind === 'string' ? cstr(String(item[f.key] ?? '')) : f.kind === 'float' ? floatLit(Number(item[f.key]) || 0) : String(Math.round(Number(item[f.key]) || 0)))).join(', ')} }`;
5887
7298
  const listBlocks = listRecords
5888
7299
  .map(
5889
7300
  s =>
@@ -5895,7 +7306,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5895
7306
  const scalarFieldDecl = s =>
5896
7307
  s.cType === 'string'
5897
7308
  ? ` char ${s.cField}[${LIST_STR_CAP}];`
5898
- : ` ${s.cType === 'float' ? 'float' : 'int'} ${s.cField};`;
7309
+ : ` ${cScalarType(s.cType)} ${s.cField};`;
5899
7310
  const scalarBlock = scalarRecords.length
5900
7311
  ? `typedef struct\n{\n${scalarRecords.map(scalarFieldDecl).join('\n')}\n} ErAppState;\n\nstatic ErAppState s_state = {${scalarRecords.map(s => ` .${s.cField} = ${s.initCode}`).join(',')} };\n`
5901
7312
  : '';
@@ -5908,7 +7319,10 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5908
7319
  // so consumer builds don't warn about an unused static.
5909
7320
  const refDecls = [...refs.values(), ...out.childRefs]
5910
7321
  .filter(r => r.used)
5911
- .map(r => `static ${r.cType} ${r.cVar} = ${r.initCode};`)
7322
+ .map(
7323
+ r =>
7324
+ `static ${r.kind === 'value' ? cScalarType(r.cType) : r.cType} ${r.cVar} = ${r.initCode};`,
7325
+ )
5912
7326
  .join('\n');
5913
7327
 
5914
7328
  // Baked vector op-tapes + paint tables (static <Svg> geometry), emitted at file scope.
@@ -5929,6 +7343,18 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5929
7343
  out.updates.length > 0 ||
5930
7344
  out.svgUpdates.length > 0 ||
5931
7345
  out.depEffects.length > 0;
7346
+ // With nothing to re-apply there is no app_update, so the calls queued by setters go too.
7347
+ if (!hasUpdate) {
7348
+ const dropUpdate = lines => lines.filter(l => l !== APP_UPDATE_CALL);
7349
+ for (const f of [
7350
+ ...out.handlers,
7351
+ ...out.timerFns,
7352
+ ...out.animCbs,
7353
+ ...out.effectFns,
7354
+ ])
7355
+ f.body = dropUpdate(f.body);
7356
+ out.mountEffects = dropUpdate(out.mountEffects);
7357
+ }
5932
7358
  const updateBlock = (() => {
5933
7359
  if (!hasUpdate) return '';
5934
7360
  const lines = ['static void app_update(void)', '{'];
@@ -5999,8 +7425,9 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
5999
7425
  .join('\n\n');
6000
7426
 
6001
7427
  // setInterval/setTimeout → a small fixed timer table advanced by er_app_tick(dt) (the host calls it each
6002
- // frame). The table + helpers are emitted only when timers are used; er_app_tick is always defined (a no-op
6003
- // otherwise) so a host can call it unconditionally. Timer callbacks become parameterless C functions.
7428
+ // frame). The table + er_timer_add are emitted only when timers are used (er_timer_clear only when
7429
+ // something calls it — see timerClearBlock); er_app_tick is always defined (a no-op otherwise) so a host
7430
+ // can call it unconditionally. Timer callbacks become parameterless C functions.
6004
7431
  const timerTableBlock = out.usesTimers
6005
7432
  ? `#include <stdbool.h>
6006
7433
 
@@ -6012,12 +7439,15 @@ typedef struct
6012
7439
  {
6013
7440
  int interval_ms;
6014
7441
  int remaining_ms;
7442
+ int gen;
6015
7443
  bool repeat;
6016
7444
  bool active;
6017
7445
  void (*fn)(void);
6018
7446
  } ErTimer;
6019
7447
  static ErTimer s_timers[ER_AOT_MAX_TIMERS];
6020
7448
 
7449
+ /* An id carries the slot AND the generation that owns it, so clearing an id whose timer has already
7450
+ finished (a one-shot, or an earlier clear) cannot kill whatever took the slot next. */
6021
7451
  static int er_timer_add(int ms, bool repeat, void (*fn)(void))
6022
7452
  {
6023
7453
  for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
@@ -6026,21 +7456,14 @@ static int er_timer_add(int ms, bool repeat, void (*fn)(void))
6026
7456
  {
6027
7457
  s_timers[i].interval_ms = ms < 1 ? 1 : ms;
6028
7458
  s_timers[i].remaining_ms = s_timers[i].interval_ms;
7459
+ s_timers[i].gen = (s_timers[i].gen + 1) & 0xFFFF;
6029
7460
  s_timers[i].repeat = repeat;
6030
7461
  s_timers[i].active = true;
6031
7462
  s_timers[i].fn = fn;
6032
- return i;
7463
+ return (s_timers[i].gen * ER_AOT_MAX_TIMERS) + i;
6033
7464
  }
6034
7465
  }
6035
7466
  return -1; /* table full (raise ER_AOT_MAX_TIMERS) */
6036
- }
6037
-
6038
- static void er_timer_clear(int id)
6039
- {
6040
- if (id >= 0 && id < ER_AOT_MAX_TIMERS)
6041
- {
6042
- s_timers[id].active = false;
6043
- }
6044
7467
  }`
6045
7468
  : '';
6046
7469
 
@@ -6066,10 +7489,15 @@ static void er_timer_clear(int id)
6066
7489
  )
6067
7490
  .join('\n\n');
6068
7491
 
7492
+ // A wall-clock change is applied here, on the app loop, rather than in the setter: the host may set the
7493
+ // time before er_app_build(), when there is nothing to update yet.
7494
+ const wallClockRefresh = hasUpdate
7495
+ ? ' if (s_wall_clock_changed)\n {\n s_wall_clock_changed = 0;\n app_update();\n }\n'
7496
+ : '';
6069
7497
  const appTickFn = out.usesTimers
6070
7498
  ? `void er_app_tick(int dt_ms)
6071
7499
  {
6072
- for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
7500
+ ${wallClockRefresh} for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
6073
7501
  {
6074
7502
  if (!s_timers[i].active)
6075
7503
  {
@@ -6098,7 +7526,7 @@ static void er_timer_clear(int id)
6098
7526
  }
6099
7527
  }
6100
7528
  }`
6101
- : `void er_app_tick(int dt_ms)\n{\n (void)dt_ms;\n}`;
7529
+ : `void er_app_tick(int dt_ms)\n{\n (void)dt_ms;\n${wallClockRefresh}}`;
6102
7530
 
6103
7531
  const mountEffectsBlock = out.mountEffects.length
6104
7532
  ? '\n /* useEffect(fn, []) — run once on mount. */\n' +
@@ -6147,10 +7575,11 @@ static int16_t app_round_dim(double v)
6147
7575
  `
6148
7576
  : '';
6149
7577
 
6150
- // <math.h> when any libm symbol appears (Svg arc trig, or Math.* in expressions/handlers/timer callbacks).
7578
+ // <math.h> when any libm symbol appears (Svg arc trig, or Math.* in expressions/handlers/timer callbacks), or
7579
+ // a call to a helper whose body uses one.
6151
7580
  const usesMath =
6152
7581
  out.needsMath ||
6153
- /\b(sinf|cosf|tanf|sqrtf|fabsf|roundf|floorf|ceilf|fminf|fmaxf|atan2f|powf|M_PI)\b/.test(
7582
+ /\b(sinf|cosf|tanf|sqrtf|fabsf|roundf|floorf|ceilf|fminf|fmaxf|atan2f|powf|fmodf|isfinite|app_roundf|app_ftoa|app_vector_dirty|M_PI)\b/.test(
6154
7583
  [
6155
7584
  stateBlock,
6156
7585
  refDecls,
@@ -6168,19 +7597,322 @@ static int16_t app_round_dim(double v)
6168
7597
  // dependent nodes via app_update() (which the host also gets for free — it is the same refresh a JS
6169
7598
  // setter would trigger). The host calls e.g. er_app_set_steps(count) once per frame.
6170
7599
  const hostRecords = scalarRecords.filter(s => s.host);
7600
+ if (hostRecords.some(s => s.name === 'wall_clock'))
7601
+ throw aotError(
7602
+ 'AOT: useHostValue("wall_clock") would collide with er_app_set_wall_clock()',
7603
+ 'rename the host value — every app exports er_app_set_wall_clock() for Date.now().',
7604
+ );
6171
7605
  const hostSettersBlock = hostRecords
6172
7606
  .map(
6173
7607
  s =>
6174
- `void er_app_set_${s.name}(${s.cType === 'float' ? 'float' : 'int'} v)\n{\n ${s.cMember} = v;\n${hasUpdate ? ' app_update();\n' : ''}}`,
7608
+ `void er_app_set_${s.name}(${cScalarType(s.cType)} v)\n{\n ${s.cMember} = v;\n${hasUpdate ? ' app_update();\n' : ''}}`,
6175
7609
  )
6176
7610
  .join('\n\n');
6177
7611
  const hostSetterProtos = hostRecords
6178
7612
  .map(
6179
7613
  s =>
6180
- `/** @brief Host-fed input '${s.name}' (useHostValue): set its value and refresh the display. */\nvoid er_app_set_${s.name}(${s.cType === 'float' ? 'float' : 'int'} v);`,
7614
+ `/** @brief Host-fed input '${s.name}' (useHostValue): set its value and refresh the display. */\nvoid er_app_set_${s.name}(${cScalarType(s.cType)} v);`,
6181
7615
  )
6182
7616
  .join('\n\n');
6183
7617
 
7618
+ // Date.now() / performance.now() read the engine clock as 64-bit whole milliseconds. The offset and its
7619
+ // setter are always emitted, so a host can set the time whether or not the app reads it; the readers, the
7620
+ // checked whole-number math and the 64-bit Math helpers only when something calls them.
7621
+ const APP_HELPERS = [
7622
+ [
7623
+ 'app_perf_now',
7624
+ 'static int64_t app_perf_now(void)\n{\n return (int64_t)er_now_ms64();\n}',
7625
+ ],
7626
+ [
7627
+ 'app_date_now',
7628
+ 'static int64_t app_date_now(void)\n{\n return s_wall_offset_ms + (int64_t)er_now_ms64();\n}',
7629
+ ],
7630
+ ...Object.entries(CHECKED_OP).map(([op, name]) => [
7631
+ name,
7632
+ `/* a ${op} b, saturated to the int range: C leaves a signed overflow undefined. */\n` +
7633
+ `static int ${name}(int a, int b)\n{\n const int64_t v = (int64_t)a ${op} b;\n` +
7634
+ ' return v > INT_MAX ? INT_MAX : v < INT_MIN ? INT_MIN : (int)v;\n}',
7635
+ ]),
7636
+ [
7637
+ 'app_neg',
7638
+ '/* -a, saturated: -INT_MIN does not fit an int. */\n' +
7639
+ 'static int app_neg(int a)\n{\n return a == INT_MIN ? INT_MAX : -a;\n}',
7640
+ ],
7641
+ [
7642
+ 'app_mod',
7643
+ "/* a % b as JS computes it, kept whole: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
7644
+ ' for b == 0, which is 0 here, and INT_MIN % -1 is 0, where C would overflow. */\n' +
7645
+ 'static int app_mod(int a, int b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
7646
+ ],
7647
+ [
7648
+ 'app_abs',
7649
+ '/* Math.abs of an int, saturated: -INT_MIN does not fit an int. */\n' +
7650
+ 'static int app_abs(int v)\n{\n return v >= 0 ? v : v == INT_MIN ? INT_MAX : -v;\n}',
7651
+ ],
7652
+ [
7653
+ 'app_min',
7654
+ 'static int app_min(int a, int b)\n{\n return a < b ? a : b;\n}',
7655
+ ],
7656
+ [
7657
+ 'app_max',
7658
+ 'static int app_max(int a, int b)\n{\n return a > b ? a : b;\n}',
7659
+ ],
7660
+ [
7661
+ 'app_div',
7662
+ '/* a / b as JS computes it, kept whole: truncated toward zero, and saturated where JS gives +-Infinity\n' +
7663
+ ' (b == 0) or a result past the int range (INT_MIN / -1). 0 / 0 is NaN, which is 0. */\n' +
7664
+ 'static int app_div(int a, int b)\n{\n' +
7665
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
7666
+ ' if (b == -1)\n {\n return a == INT_MIN ? INT_MAX : -a;\n }\n' +
7667
+ ' return a / b;\n}',
7668
+ ],
7669
+ [
7670
+ 'app_floordiv',
7671
+ "/* Math.floor(a / b) for two ints, exactly: C's `/` rounds toward zero where floor rounds down, and a float\n" +
7672
+ ' quotient would round an operand past 2^24. JS gives +-Infinity for b == 0, which saturates by the sign\n' +
7673
+ ' of a (0 / 0 is NaN, which is 0); INT_MIN / -1 saturates too, so the quotient is taken in 64 bits. */\n' +
7674
+ 'static int app_floordiv(int a, int b)\n{\n' +
7675
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
7676
+ ' const int64_t q = (int64_t)a / b;\n' +
7677
+ ' const int64_t f = ((int64_t)a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n' +
7678
+ ' return f > INT_MAX ? INT_MAX : (int)f;\n}',
7679
+ ],
7680
+ [
7681
+ 'app_ceildiv',
7682
+ '/* Math.ceil(a / b) for two ints, exactly, with the zero divisor and INT_MIN / -1 as app_floordiv has them. */\n' +
7683
+ 'static int app_ceildiv(int a, int b)\n{\n' +
7684
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
7685
+ ' const int64_t q = (int64_t)a / b;\n' +
7686
+ ' const int64_t c = ((int64_t)a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n' +
7687
+ ' return c > INT_MAX ? INT_MAX : (int)c;\n}',
7688
+ ],
7689
+ [
7690
+ 'app_rounddiv',
7691
+ '/* Math.round(a / b) for two ints, exactly: floor(a / b + 1/2), halves up as JS rounds, which is\n' +
7692
+ ' floor((2a + b) / 2b) once b is made positive. The zero divisor and the range go as in app_floordiv. */\n' +
7693
+ 'static int app_rounddiv(int a, int b)\n{\n' +
7694
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
7695
+ ' const int64_t n = b < 0 ? -(int64_t)a : a;\n' +
7696
+ ' const int64_t d = b < 0 ? -(int64_t)b : b;\n' +
7697
+ ' const int64_t num = 2 * n + d, den = 2 * d;\n' +
7698
+ ' const int64_t q = num / den;\n' +
7699
+ ' const int64_t r = (num % den != 0 && num < 0) ? q - 1 : q;\n' +
7700
+ ' return r > INT_MAX ? INT_MAX : r < INT_MIN ? INT_MIN : (int)r;\n}',
7701
+ ],
7702
+ [
7703
+ 'app_f2i',
7704
+ '/* A float kept as an int: truncated toward zero like a C cast, but saturated at the int range and NaN as\n' +
7705
+ ' 0, where the cast would be undefined behavior. */\n' +
7706
+ 'static int app_f2i(float v)\n{\n' +
7707
+ ' if (v != v)\n {\n return 0;\n }\n' +
7708
+ ' if (v >= 2147483648.0f)\n {\n return INT_MAX;\n }\n' +
7709
+ ' if (v <= -2147483648.0f)\n {\n return INT_MIN;\n }\n' +
7710
+ ' return (int)v;\n}',
7711
+ ],
7712
+ [
7713
+ 'app_roundf',
7714
+ "/* Math.round as JS rounds: to the nearest whole number, halves up (toward +Infinity). C's roundf takes\n" +
7715
+ ' halves away from zero, which gives -3 for -2.5 where JS gives -2. */\n' +
7716
+ 'static float app_roundf(float v)\n{\n' +
7717
+ ' const float f = floorf(v);\n return v - f >= 0.5f ? f + 1.0f : f;\n}',
7718
+ ],
7719
+ [
7720
+ 'app_ftoa',
7721
+ "/* A float as JS's String() spells it where %g does not: Infinity, -Infinity and NaN for what %g prints as\n" +
7722
+ ' inf, -inf and nan, and 0 for negative zero, which %g prints as -0. Anything else is %g, into `buf`,\n' +
7723
+ ' which the caller lends (16 chars, room for any float). All ASCII, which every font bakes. */\n' +
7724
+ 'static const char* app_ftoa(char* buf, float v)\n{\n' +
7725
+ ' if (v != v)\n {\n return "NaN";\n }\n' +
7726
+ ' if (isinf(v))\n {\n return v > 0.0f ? "Infinity" : "-Infinity";\n }\n' +
7727
+ ' if (v == 0.0f)\n {\n return "0";\n }\n' +
7728
+ ' snprintf(buf, 16, "%g", (double)v);\n return buf;\n}',
7729
+ ],
7730
+ [
7731
+ 'app_opacity',
7732
+ "/* A state-driven opacity as the engine's 0-255 byte: clamped to 0..1 and rounded, as Flow A's bridge and\n" +
7733
+ ' the compile-time fold do, with NaN as 0. */\n' +
7734
+ 'static uint8_t app_opacity(float v)\n{\n' +
7735
+ ' if (!(v > 0.0f))\n {\n return 0;\n }\n' +
7736
+ ' if (v >= 1.0f)\n {\n return 255;\n }\n' +
7737
+ ' return (uint8_t)(v * 255.0f + 0.5f);\n}',
7738
+ ],
7739
+ [
7740
+ 'app_add64',
7741
+ '/* a + b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
7742
+ 'static int64_t app_add64(int64_t a, int64_t b)\n{\n' +
7743
+ ' if (b > 0 ? a > INT64_MAX - b : a < INT64_MIN - b)\n {\n' +
7744
+ ' return b > 0 ? INT64_MAX : INT64_MIN;\n }\n return a + b;\n}',
7745
+ ],
7746
+ [
7747
+ 'app_sub64',
7748
+ '/* a - b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
7749
+ 'static int64_t app_sub64(int64_t a, int64_t b)\n{\n' +
7750
+ ' if (b < 0 ? a > INT64_MAX + b : a < INT64_MIN + b)\n {\n' +
7751
+ ' return b < 0 ? INT64_MAX : INT64_MIN;\n }\n return a - b;\n}',
7752
+ ],
7753
+ [
7754
+ 'app_mul64',
7755
+ '/* a * b, saturated to the int64 range: C leaves a signed overflow undefined. GCC and Clang test for\n' +
7756
+ ' the overflow with a builtin; anywhere else (MSVC) the limits are checked by division first. */\n' +
7757
+ 'static int64_t app_mul64(int64_t a, int64_t b)\n{\n' +
7758
+ '#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ >= 5)\n' +
7759
+ ' int64_t v;\n if (!__builtin_mul_overflow(a, b, &v))\n {\n return v;\n }\n' +
7760
+ '#else\n' +
7761
+ ' if (a == 0 || b == 0 ||\n' +
7762
+ ' (a > 0 ? (b > 0 ? a <= INT64_MAX / b : b >= INT64_MIN / a)\n' +
7763
+ ' : (b > 0 ? a >= INT64_MIN / b : a >= INT64_MAX / b)))\n {\n' +
7764
+ ' return a * b;\n }\n' +
7765
+ '#endif\n' +
7766
+ ' return (a < 0) == (b < 0) ? INT64_MAX : INT64_MIN;\n}',
7767
+ ],
7768
+ [
7769
+ 'app_neg64',
7770
+ '/* -a, saturated: -INT64_MIN does not fit an int64_t. */\n' +
7771
+ 'static int64_t app_neg64(int64_t a)\n{\n return a == INT64_MIN ? INT64_MAX : -a;\n}',
7772
+ ],
7773
+ [
7774
+ 'app_floordiv64',
7775
+ "/* Math.floor(a / b) in whole numbers: C's `/` rounds toward zero where floor rounds down. JS gives\n" +
7776
+ ' +-Infinity for b == 0, which saturates by the sign of a (0 / 0 is NaN, which is 0), and INT64_MIN / -1\n' +
7777
+ ' is past the range, so it saturates too. */\n' +
7778
+ 'static int64_t app_floordiv64(int64_t a, int64_t b)\n{\n' +
7779
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
7780
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
7781
+ ' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n}',
7782
+ ],
7783
+ [
7784
+ 'app_ceildiv64',
7785
+ '/* Math.ceil(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as app_floordiv64 has them. */\n' +
7786
+ 'static int64_t app_ceildiv64(int64_t a, int64_t b)\n{\n' +
7787
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
7788
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
7789
+ ' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n}',
7790
+ ],
7791
+ [
7792
+ 'app_rounddiv64',
7793
+ '/* Math.round(a / b) in whole numbers, halves up as JS rounds: floor(a / b), plus one when what is left is at\n' +
7794
+ ' least half of b. Nothing is doubled, which could overflow; the zero divisor and INT64_MIN / -1 go as in\n' +
7795
+ ' app_floordiv64. */\n' +
7796
+ 'static int64_t app_rounddiv64(int64_t a, int64_t b)\n{\n' +
7797
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
7798
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
7799
+ ' int64_t q = a / b;\n int64_t r = a % b;\n' +
7800
+ ' if (r != 0 && (r < 0) != (b < 0))\n {\n q -= 1;\n r += b;\n }\n' +
7801
+ ' return (b > 0 ? r >= b - r : r <= b - r) ? q + 1 : q;\n}',
7802
+ ],
7803
+ [
7804
+ 'app_div64',
7805
+ '/* Math.trunc(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as app_floordiv64 has them. */\n' +
7806
+ 'static int64_t app_div64(int64_t a, int64_t b)\n{\n' +
7807
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
7808
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
7809
+ ' return a / b;\n}',
7810
+ ],
7811
+ [
7812
+ 'app_mod64',
7813
+ "/* a % b in whole numbers, as JS computes it: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
7814
+ ' for b == 0, which is 0 here, and INT64_MIN % -1 is 0, where C would overflow. */\n' +
7815
+ 'static int64_t app_mod64(int64_t a, int64_t b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
7816
+ ],
7817
+ [
7818
+ 'app_abs64',
7819
+ '/* |v|, saturated: -INT64_MIN does not fit an int64_t. */\n' +
7820
+ 'static int64_t app_abs64(int64_t v)\n{\n return v >= 0 ? v : v == INT64_MIN ? INT64_MAX : -v;\n}',
7821
+ ],
7822
+ [
7823
+ 'app_min64',
7824
+ 'static int64_t app_min64(int64_t a, int64_t b)\n{\n return a < b ? a : b;\n}',
7825
+ ],
7826
+ [
7827
+ 'app_max64',
7828
+ 'static int64_t app_max64(int64_t a, int64_t b)\n{\n return a > b ? a : b;\n}',
7829
+ ],
7830
+ [
7831
+ 'app_delay_ms64',
7832
+ '/* A timer delay computed from a timestamp: ToInt32 (wrap to 32 bits), then a negative delay is 0 — the\n' +
7833
+ " conversion Flow A's setTimeout applies. */\n" +
7834
+ 'static int app_delay_ms64(int64_t v)\n{\n const uint32_t u = (uint32_t)v;\n return u > 0x7FFFFFFFu ? 0 : (int)u;\n}',
7835
+ ],
7836
+ [
7837
+ 'app_delay_msf',
7838
+ '/* A timer delay computed as a float, converted as app_delay_ms64 converts one: ToInt32 (NaN and +-Infinity\n' +
7839
+ ' are 0), then a negative delay is 0. Past +-2^63 a float is a multiple of 2^32, which ToInt32 takes to 0. */\n' +
7840
+ 'static int app_delay_msf(float v)\n{\n' +
7841
+ ' if (!(v > -9223372036854775808.0f && v < 9223372036854775808.0f))\n {\n return 0;\n }\n' +
7842
+ ' const uint32_t u = (uint32_t)(int64_t)v;\n return u > 0x7FFFFFFFu ? 0 : (int)u;\n}',
7843
+ ],
7844
+ [
7845
+ 'app_slice_len',
7846
+ '/* The length items.slice(0, end) leaves, as JS counts it: a negative end counts back from the length and\n' +
7847
+ ' stops at 0, and an end past the length keeps every item. */\n' +
7848
+ 'static int app_slice_len(int len, int end)\n{\n' +
7849
+ ' if (end < 0)\n {\n return end <= -len ? 0 : len + end;\n }\n' +
7850
+ ' return end < len ? end : len;\n}',
7851
+ ],
7852
+ [
7853
+ 'app_vector_dirty',
7854
+ "/* updateVector's damage hint from float math. A NaN or infinite edge (a 0/0 in app math) gives no hint,\n" +
7855
+ " so the engine's own damage applies (what changed in the tape, or the whole node), where a zero-width\n" +
7856
+ ' one would leave the new drawing unpainted. The rest is rounded out to whole pixels and its edges, not\n' +
7857
+ ' its lengths, are bounded well inside the int range, so a rect reaching past the bound is not cut\n' +
7858
+ " short; the engine clips the rect's corners from there. */\n" +
7859
+ 'static void app_vector_dirty(ERNode* node, float x, float y, float w, float h)\n{\n' +
7860
+ ' if (!(isfinite(x) && isfinite(y) && isfinite(w) && isfinite(h)))\n {\n return;\n }\n' +
7861
+ ' const float e[4] = {floorf(x), floorf(y), ceilf(x + w), ceilf(y + h)};\n int c[4];\n' +
7862
+ ' for (int k = 0; k < 4; k++)\n {\n' +
7863
+ ' c[k] = (int)(e[k] < -1e9f ? -1e9f : (e[k] > 1e9f ? 1e9f : e[k]));\n }\n' +
7864
+ ' er_node_set_vector_dirty_rect(node, c[0], c[1], c[2] - c[0], c[3] - c[1]);\n}',
7865
+ ],
7866
+ ];
7867
+ // The generated code that can call a file-local helper, with literals and comments blanked so a
7868
+ // `<Text>app_date_now(</Text>` is not a call. Each static helper is emitted only when this calls it, since
7869
+ // an unused static function warns under -Wall.
7870
+ const helperCallers = stripCLiterals(
7871
+ [
7872
+ stateBlock,
7873
+ refDecls,
7874
+ vectorBuilderBlock,
7875
+ updateBlock,
7876
+ handlerDefs,
7877
+ queryDefs,
7878
+ effectFnDefs,
7879
+ animCbDefs,
7880
+ timerFnDefs,
7881
+ out.mountEffects.join('\n'),
7882
+ out.build.join('\n'),
7883
+ ].join('\n'),
7884
+ );
7885
+ const clockBlock = [
7886
+ '/* Date.now() is the engine clock plus this offset, so it reads as uptime until the host calls\n' +
7887
+ ' er_app_set_wall_clock(). performance.now() is the engine clock alone. */\n' +
7888
+ 'static int64_t s_wall_offset_ms;' +
7889
+ (hasUpdate
7890
+ ? '\n/* Set by er_app_set_wall_clock(); the next er_app_tick() re-applies what reads the clock. */\n' +
7891
+ 'static int s_wall_clock_changed;'
7892
+ : ''),
7893
+ ...APP_HELPERS.filter(([name]) => helperCallers.includes(`${name}(`)).map(
7894
+ ([, def]) => def,
7895
+ ),
7896
+ ].join('\n\n');
7897
+ const usesLimits = /\bINT_M(?:AX|IN)\b/.test(clockBlock);
7898
+ // A mount effect's cleanup is dropped (the app never unmounts), so an app whose only clearInterval lives
7899
+ // there calls er_timer_clear from nowhere.
7900
+ const timerClearBlock =
7901
+ out.usesTimers && helperCallers.includes('er_timer_clear(')
7902
+ ? `static void er_timer_clear(int id)
7903
+ {
7904
+ if (id < 0)
7905
+ {
7906
+ return;
7907
+ }
7908
+ int i = id % ER_AOT_MAX_TIMERS;
7909
+ if (s_timers[i].active && s_timers[i].gen == id / ER_AOT_MAX_TIMERS)
7910
+ {
7911
+ s_timers[i].active = false;
7912
+ }
7913
+ }`
7914
+ : '';
7915
+
6184
7916
  const body = `/*
6185
7917
  * Generated by the embedded-react Flow B AOT compiler (npm run aot -- ${demo}). DO NOT EDIT.
6186
7918
  * Builds the app's scene graph + state machine directly against er_scene.h — no QuickJS, no JS runtime.
@@ -6193,13 +7925,28 @@ static int16_t app_round_dim(double v)
6193
7925
  #include <stdio.h>
6194
7926
  #include <string.h>
6195
7927
 
7928
+ /* Every string this file writes goes into a FIXED-SIZE slot (a state buffer, ERProps.text), so an
7929
+ over-long value is truncated by design — the app cannot grow the buffer the way JS grows a string.
7930
+ GCC's -Wformat-truncation reports exactly that intent for any format combining %s with anything else,
7931
+ and ESP-IDF compiles with -Werror, so leaving it on would fail the build for ordinary text like
7932
+ {'n=' + name}. Clang does not implement the warning; the guard keeps its "unknown warning group"
7933
+ diagnostic from firing there. */
7934
+ #if defined(__GNUC__) && !defined(__clang__)
7935
+ #pragma GCC diagnostic ignored "-Wformat-truncation"
7936
+ #endif
7937
+
6196
7938
  /* Version-pin: this file was generated by embedded-react ${PKG_VERSION}. The engine ships LOCKSTEP, so its
6197
7939
  headers must be the same major.minor — otherwise these generated er_scene.h calls may not match the ABI.
6198
7940
  A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
6199
7941
  _Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
6200
7942
  "embedded-react version mismatch: app.gen.c was generated by ${PKG_VERSION} but the engine header (er_version.h) is a different major.minor. Regenerate the app with 'npm run aot', or align the engine and npm versions.");
6201
- ${usesMath ? '#include <math.h>\n/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles under -std=c99 / MSVC. */\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n' : ''}${dimRoundBlock}${stateBlock ? '\n' + stateBlock : ''}${refDecls ? '\n' + refDecls + '\n' : ''}${panDeclBlock ? '\n' + panDeclBlock + '\n' : ''}${effectDeclsBlock ? '\n' + effectDeclsBlock + '\n' : ''}${vectorBlock ? '\n' + vectorBlock + '\n' : ''}${vectorBuilderBlock ? '\n' + vectorBuilderBlock + '\n' : ''}${animDecls ? '\n' + animDecls + '\n' : ''}${handleDecls ? '\n' + handleDecls + '\n' : ''}${timerTableBlock ? '\n' + timerTableBlock + '\n' : ''}${effectFwdDecls ? '\n' + effectFwdDecls + '\n' : ''}${updateBlock ? '\n' + updateBlock + '\n' : ''}${timerFnFwdDecls ? '\n' + timerFnFwdDecls + '\n' : ''}${animCbDecls ? '\n' + animCbDecls + '\n' : ''}${handlerDefs ? '\n' + handlerDefs + '\n' : ''}${queryDefs ? '\n' + queryDefs + '\n' : ''}${effectFnDefs ? '\n' + effectFnDefs + '\n' : ''}${animCbDefs ? '\n' + animCbDefs + '\n' : ''}${timerFnDefs ? '\n' + timerFnDefs + '\n' : ''}${out.kbdData ? '\n' + out.kbdData + '\n' : ''}
7943
+ ${usesMath ? '#include <math.h>\n/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles under -std=c99 / MSVC. */\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n' : ''}${usesLimits ? '#include <limits.h>\n' : ''}${dimRoundBlock}\n${clockBlock}\n${stateBlock ? '\n' + stateBlock : ''}${refDecls ? '\n' + refDecls + '\n' : ''}${panDeclBlock ? '\n' + panDeclBlock + '\n' : ''}${effectDeclsBlock ? '\n' + effectDeclsBlock + '\n' : ''}${vectorBlock ? '\n' + vectorBlock + '\n' : ''}${vectorBuilderBlock ? '\n' + vectorBuilderBlock + '\n' : ''}${animDecls ? '\n' + animDecls + '\n' : ''}${handleDecls ? '\n' + handleDecls + '\n' : ''}${timerTableBlock ? '\n' + timerTableBlock + '\n' : ''}${timerClearBlock ? '\n' + timerClearBlock + '\n' : ''}${effectFwdDecls ? '\n' + effectFwdDecls + '\n' : ''}${updateBlock ? '\n' + updateBlock + '\n' : ''}${timerFnFwdDecls ? '\n' + timerFnFwdDecls + '\n' : ''}${animCbDecls ? '\n' + animCbDecls + '\n' : ''}${handlerDefs ? '\n' + handlerDefs + '\n' : ''}${queryDefs ? '\n' + queryDefs + '\n' : ''}${effectFnDefs ? '\n' + effectFnDefs + '\n' : ''}${animCbDefs ? '\n' + animCbDefs + '\n' : ''}${timerFnDefs ? '\n' + timerFnDefs + '\n' : ''}${out.kbdData ? '\n' + out.kbdData + '\n' : ''}
6202
7944
  ${appTickFn}
7945
+
7946
+ void er_app_set_wall_clock(int64_t epoch_ms)
7947
+ {
7948
+ s_wall_offset_ms = epoch_ms - (int64_t)er_now_ms64();${hasUpdate ? '\n s_wall_clock_changed = 1;' : ''}
7949
+ }
6203
7950
  ${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}
6204
7951
  void er_app_build(int screen_w, int screen_h)
6205
7952
  {
@@ -6223,12 +7970,41 @@ ${out.kbdSetup ? out.kbdSetup + ' /* app-supplied on-screen keyboard layout/appe
6223
7970
  #ifndef ER_APP_GEN_H
6224
7971
  #define ER_APP_GEN_H
6225
7972
 
7973
+ #include <stdint.h>
7974
+
7975
+ /*
7976
+ * What this file was generated FOR. er_app_build() takes the screen size at runtime, but a responsive app
7977
+ * folds its \`screen.width\`/\`screen.height\` branching at GENERATE time — so the layout in here is already
7978
+ * committed to these dimensions and no runtime argument can change it.
7979
+ *
7980
+ * Every board example consumes the same dist/app.gen.c, so generating for one board and then building
7981
+ * another produces firmware that compiles, links, boots, and lays out wrong. Boards \`_Static_assert\` these
7982
+ * against their own panel size to turn that into a compile error; see each board example's main.c.
7983
+ *
7984
+ * WHICH demo is recorded the same way, as a marker macro named ER_AOT_DEMO_<demo> with every character
7985
+ * outside [A-Za-z0-9] encoded as _<hex>_ (so \`watch-face\` defines ER_AOT_DEMO_watch_2d_face). The encoding
7986
+ * is one-to-one, so no two app names can ever share a marker. A board that
7987
+ * needs a particular demo's useHostValue setters guards on \`#ifndef\` of its own marker, which names the
7988
+ * mismatch instead of leaving a pile of implicit-declaration errors for those setters.
7989
+ */
7990
+ #define ER_AOT_SCREEN_W ${screen.width}
7991
+ #define ER_AOT_SCREEN_H ${screen.height}
7992
+ #define ER_AOT_DEMO ${cstr(demo)}
7993
+ #define ${demoMarker(demo)} 1
7994
+
6226
7995
  /** @brief Builds the AOT-compiled app's scene graph + state machine (call once after backend init). */
6227
7996
  void er_app_build(int screen_w, int screen_h);
6228
7997
 
6229
7998
  /** @brief Advances app timers (setInterval/setTimeout). Call once per frame with the elapsed ms; a no-op
6230
7999
  * for apps that use no timers, so it is always safe to call. */
6231
8000
  void er_app_tick(int dt_ms);
8001
+
8002
+ /** @brief Tells the app the current time, which Date.now() counts on from. Until it is called Date.now()
8003
+ * reads as uptime; a later call re-anchors it, the next er_app_tick() re-applies what reads the
8004
+ * clock, and performance.now() never moves with it. Call it from the loop that calls
8005
+ * er_app_tick(), before or after er_app_build(); safe whether or not the app reads the clock.
8006
+ * @param[in] epoch_ms Current time, in milliseconds since the Unix epoch. */
8007
+ void er_app_set_wall_clock(int64_t epoch_ms);
6232
8008
  ${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
6233
8009
  #endif
6234
8010
  `;
@@ -6250,11 +8026,37 @@ ${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
6250
8026
  };
6251
8027
  }
6252
8028
 
8029
+ /**
8030
+ * A state or ref slot is typed from its initial value, so `useState(0)` is an int until a setter stores
8031
+ * Date.now() in it. A compile reports such slots (env.found); this compiles again with them widened to
8032
+ * int64_t until none are new, so every read of a slot sees its final type.
8033
+ */
8034
+ function compileWidened(src, demo, opts) {
8035
+ const wide = new Set();
8036
+ for (;;) {
8037
+ const found = new Set();
8038
+ let result;
8039
+ let error;
8040
+ try {
8041
+ result = compileSourceImpl(src, demo, opts, wide, found);
8042
+ } catch (e) {
8043
+ error = e;
8044
+ }
8045
+ const fresh = [...found].filter(key => !wide.has(key));
8046
+ // A failed pass that still had slots to widen may have failed on the narrow type, so retry it first.
8047
+ if (!fresh.length) {
8048
+ if (error) throw error;
8049
+ return result;
8050
+ }
8051
+ for (const key of fresh) wide.add(key);
8052
+ }
8053
+ }
8054
+
6253
8055
  /** Public entry: compile JSX source → { c, h, ... }. On an AOT error, annotate it with file:line:col + a
6254
8056
  * source code-frame (+ hint) so the failure points at the exact unsupported construct. */
6255
8057
  export function compileSource(src, demo = 'app', opts = {}) {
6256
8058
  try {
6257
- return compileSourceImpl(src, demo, opts);
8059
+ return compileWidened(src, demo, opts);
6258
8060
  } catch (e) {
6259
8061
  if (e && typeof e.message === 'string' && e.message.startsWith('AOT:')) {
6260
8062
  throw formatAotError(e, src, opts.filename || `demos/${demo}/App.jsx`);
@@ -6273,12 +8075,12 @@ if (
6273
8075
  ) {
6274
8076
  const demo = process.argv[2] || process.env.DEMO || 'thermostat';
6275
8077
  const appPath = resolve(demosDir, demo, 'App.jsx');
8078
+ const avail = existsSync(demosDir)
8079
+ ? readdirSync(demosDir, {withFileTypes: true})
8080
+ .filter(d => d.isDirectory())
8081
+ .map(d => d.name)
8082
+ : [];
6276
8083
  if (!existsSync(appPath)) {
6277
- const avail = existsSync(demosDir)
6278
- ? readdirSync(demosDir, {withFileTypes: true})
6279
- .filter(d => d.isDirectory())
6280
- .map(d => d.name)
6281
- : [];
6282
8084
  console.error(
6283
8085
  `AOT: demo "${demo}" not found (expected ${appPath}). Available: ${avail.join(', ') || '(none)'}`,
6284
8086
  );