embedded-react 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/aot/compiler/animations.mjs +102 -34
  2. package/aot/compiler/assemble.mjs +169 -31
  3. package/aot/compiler/boot.mjs +441 -0
  4. package/aot/compiler/branch-merge.mjs +315 -0
  5. package/aot/compiler/c/animations.mjs +90 -16
  6. package/aot/compiler/c/boot.mjs +127 -0
  7. package/aot/compiler/c/expressions.mjs +63 -8
  8. package/aot/compiler/c/nodes.mjs +34 -13
  9. package/aot/compiler/c/statements.mjs +92 -15
  10. package/aot/compiler/check.mjs +32 -3
  11. package/aot/compiler/collect.mjs +95 -9
  12. package/aot/compiler/control-flow.mjs +43 -18
  13. package/aot/compiler/diagnostics.mjs +33 -0
  14. package/aot/compiler/elements/dial.mjs +8 -7
  15. package/aot/compiler/elements/props.mjs +19 -9
  16. package/aot/compiler/elements/text-input.mjs +7 -2
  17. package/aot/compiler/expressions.mjs +132 -10
  18. package/aot/compiler/handlers.mjs +62 -24
  19. package/aot/compiler/ir/boot.mjs +16 -0
  20. package/aot/compiler/ir/nodes.mjs +28 -4
  21. package/aot/compiler/ir/reads.mjs +351 -0
  22. package/aot/compiler/keyboard.mjs +35 -21
  23. package/aot/compiler/lower.mjs +40 -11
  24. package/aot/compiler/nodes.mjs +22 -9
  25. package/aot/compiler/options.mjs +63 -12
  26. package/aot/compiler/static-eval.mjs +314 -56
  27. package/aot/compiler/style-text.mjs +201 -19
  28. package/aot/compiler/svg.mjs +7 -3
  29. package/aot/style-map.mjs +9 -11
  30. package/assets/bake-svg.mjs +3 -2
  31. package/package.json +1 -1
  32. package/sim/embedded-react.wasm +0 -0
  33. package/src/embedded-react/Animated.js +41 -0
  34. package/src/embedded-react/Button.js +3 -4
  35. package/src/embedded-react/Pressable.js +59 -0
  36. package/src/embedded-react/TouchableOpacity.js +6 -9
  37. package/src/embedded-react/index.d.ts +118 -30
  38. package/src/embedded-react/index.js +1 -1
  39. package/src/embedded-react/named-colors.js +37 -0
  40. package/src/embedded-react/svg-ops.js +13 -16
  41. package/src/host-config.js +50 -8
@@ -23,9 +23,12 @@ import { INT_MAX, lowerExpr } from './expressions.mjs';
23
23
  import { NO_WIDE, isFn, wideInitial } from './collect.mjs';
24
24
  import { lowerStmts } from './handlers.mjs';
25
25
  import { isPanCreate } from './pan-responder.mjs';
26
+ import { parseColorValue } from '../style-map.mjs';
26
27
  /*----------------------------------------------------------------------------------------------------------------------
27
28
  - Constants
28
29
  ---------------------------------------------------------------------------------------------------------------------*/
30
+ /** The style keys an animated value drives only through an interpolation onto colors. */
31
+ export const ANIM_COLOR_KEYS = new Set(['backgroundColor', 'color']);
29
32
  /** Style key → the ERAnimProp(s) an animated value binds to. */
30
33
  export const ANIM_STYLE_PROPS = {
31
34
  opacity: ['ER_PROP_OPACITY'],
@@ -275,17 +278,33 @@ export function parseInterp(cfgNode, env) {
275
278
  // Read a named property from the interpolation config, accepting both identifier and string-literal keys.
276
279
  const get = (key) => cfgNode.properties.find(property => (property.key.name ??
277
280
  property.key.value) === key)?.value;
278
- // Fold an interpolation range into numeric breakpoints; ranges must be array literals for AOT emission.
281
+ // Fold an interpolation range into its breakpoints; ranges must be array literals for AOT emission.
279
282
  const arr = (node, name) => {
280
283
  if (node?.type !== 'ArrayExpression') {
281
284
  throw aotError(`AOT: .interpolate() ${name} must be an array literal`);
282
285
  }
283
- return node.elements.map(e => Number(evalStatic(e, env.consts ?? {})));
286
+ return node.elements.map(e => evalStatic(e, env.consts ?? {}));
284
287
  };
285
- // inputRange and outputRange define the piecewise mapping and must line up point-for-point.
286
- const input = arr(get('inputRange'), 'inputRange');
287
- const output = arr(get('outputRange'), 'outputRange');
288
- if (input.length < 2 || input.length !== output.length) {
288
+ // inputRange and outputRange define the piecewise mapping and must line up point-for-point. An
289
+ // outputRange of strings maps onto colors.
290
+ const input = arr(get('inputRange'), 'inputRange').map(Number);
291
+ const outputValues = arr(get('outputRange'), 'outputRange');
292
+ // Colors parse as strictly as a static style color, so a typo is an error rather than black.
293
+ const colors = outputValues.every(v => typeof v === 'string')
294
+ ? outputValues.map(v => {
295
+ try {
296
+ return parseColorValue(v);
297
+ }
298
+ catch (error) {
299
+ throw aotError(`AOT: .interpolate() outputRange has an ${error.message}`);
300
+ }
301
+ })
302
+ : undefined;
303
+ if (!colors && outputValues.some(v => typeof v !== 'number')) {
304
+ throw aotError('AOT: .interpolate() outputRange must be all numbers or all colors');
305
+ }
306
+ const output = colors ? [] : outputValues;
307
+ if (input.length < 2 || input.length !== outputValues.length) {
289
308
  throw aotError('AOT: .interpolate() inputRange and outputRange must be the same length (>= 2)');
290
309
  }
291
310
  check({ kind: 'interpolationPoints', count: input.length });
@@ -305,6 +324,7 @@ export function parseInterp(cfgNode, env) {
305
324
  return {
306
325
  input,
307
326
  output,
327
+ ...(colors && { colors }),
308
328
  exLeft: ex(get('extrapolateLeft') ?? both),
309
329
  exRight: ex(get('extrapolateRight') ?? both),
310
330
  };
@@ -332,6 +352,51 @@ function configFloat(rawValue) {
332
352
  checkNumber(rawValue);
333
353
  return Number(rawValue);
334
354
  }
355
+ /**
356
+ * A folded config time in whole milliseconds, checked so a time C cannot hold is reported at the field.
357
+ *
358
+ * @param node The field's value, if the app wrote one.
359
+ * @param env The expression environment.
360
+ * @param defaultValue The time when the field is left out or not known at build time.
361
+ * @param field What the time is, for the error.
362
+ *
363
+ * @returns The time.
364
+ */
365
+ function configMs(node, env, defaultValue, field) {
366
+ const rawValue = evalStaticOr(node, env, defaultValue);
367
+ check({ kind: 'milliseconds', field, value: rawValue }, node?.loc?.start);
368
+ return Math.round(Number(rawValue));
369
+ }
370
+ /**
371
+ * A timing's folded duration (250 ms when it is left out, as in React Native).
372
+ *
373
+ * @param get The timing's config.
374
+ * @param env The expression environment.
375
+ *
376
+ * @returns The duration.
377
+ */
378
+ const timingDuration = (get, env) => configMs(get('duration'), env, 250, `Animated.timing's "duration"`);
379
+ /**
380
+ * An animation's own delay (0 when it is left out).
381
+ *
382
+ * @param kind timing, spring or decay.
383
+ * @param get The animation's config.
384
+ * @param env The expression environment.
385
+ *
386
+ * @returns The delay.
387
+ */
388
+ const ownDelayMs = (kind, get, env) => configMs(get('delay'), env, 0, `Animated.${kind}'s "delay"`);
389
+ /**
390
+ * A time added up from a composition's times, checked like them: each fits an int, but a sum of them need not.
391
+ *
392
+ * @param value The sum.
393
+ *
394
+ * @returns The sum.
395
+ */
396
+ function totalMs(value) {
397
+ check({ kind: 'milliseconds', field: "this animation's total time", value });
398
+ return value;
399
+ }
335
400
  /**
336
401
  * Lowers one atomic animation (timing/spring/decay). `delayMs` is the absolute start delay (how composition
337
402
  * offsets are realized) and `loop` repeats a timing on the engine's own loop.
@@ -361,7 +426,7 @@ function lowerAnimation(entry, env) {
361
426
  };
362
427
  }
363
428
  else {
364
- const durationMs = Math.round(Number(evalStaticOr(get('duration'), env, 250)));
429
+ const durationMs = timingDuration(get, env);
365
430
  const { ease, bezier } = easingInfo(get('easing'), env);
366
431
  curve = {
367
432
  kind: 'timing',
@@ -379,7 +444,7 @@ function lowerAnimation(entry, env) {
379
444
  handle: cVar,
380
445
  curve,
381
446
  to: toNode ? lowerExpr(toNode, env) : null,
382
- delayMs,
447
+ delayMs: totalMs(delayMs),
383
448
  isLooping: loop,
384
449
  };
385
450
  }
@@ -413,10 +478,8 @@ function flattenAnim(node, env, baseDelay, loop) {
413
478
  }
414
479
  const cVar = env.animations.get(valRef.name).cVar;
415
480
  const get = animConfigGetter(args[1]);
416
- const ownDelay = Math.round(Number(evalStaticOr(get('delay'), env, 0)));
417
- const duration = kind === 'timing'
418
- ? ownDelay + Math.round(Number(evalStaticOr(get('duration'), env, 250)))
419
- : null;
481
+ const ownDelay = ownDelayMs(kind, get, env);
482
+ const duration = kind === 'timing' ? ownDelay + timingDuration(get, env) : null;
420
483
  return {
421
484
  entries: [{ cVar, kind, get, delayMs: baseDelay + ownDelay, loop }],
422
485
  duration,
@@ -426,14 +489,14 @@ function flattenAnim(node, env, baseDelay, loop) {
426
489
  if (kind === 'delay') {
427
490
  return {
428
491
  entries: [],
429
- duration: Math.round(Number(evalStaticOr(args[0], env, 0))),
492
+ duration: configMs(args[0], env, 0, "Animated.delay's time"),
430
493
  };
431
494
  }
432
495
  // Composition nodes flatten into atomic animations with absolute delay_ms offsets.
433
496
  if (kind === 'sequence' || kind === 'parallel' || kind === 'stagger') {
434
497
  const list = kind === 'stagger' ? args[1] : args[0];
435
498
  const staggerMs = kind === 'stagger'
436
- ? Math.round(Number(evalStaticOr(args[0], env, 0)))
499
+ ? configMs(args[0], env, 0, "Animated.stagger's interval")
437
500
  : 0;
438
501
  if (list?.type !== 'ArrayExpression') {
439
502
  throw aotError(`AOT: Animated.${kind}(...) needs an array of animations`);
@@ -528,7 +591,7 @@ function animStep(node, env, extraDelay) {
528
591
  }
529
592
  // Fold this step's own delay and add any delay inherited from an enclosing sequence/delay.
530
593
  const get = animConfigGetter(node.arguments[1]);
531
- const ownDelay = Math.round(Number(evalStaticOr(get('delay'), env, 0)));
594
+ const ownDelay = ownDelayMs(kind, get, env);
532
595
  return {
533
596
  cVar: env.animations.get(valRef.name).cVar,
534
597
  kind,
@@ -601,7 +664,7 @@ function sequenceSteps(seqNode, env) {
601
664
  // Fold delay-only entries into the following animation step.
602
665
  const kind = child.callee.property.name;
603
666
  if (kind === 'delay') {
604
- pendingDelay += Math.round(Number(evalStaticOr(child.arguments[0], env, 0)));
667
+ pendingDelay += configMs(child.arguments[0], env, 0, "Animated.delay's time");
605
668
  continue;
606
669
  }
607
670
  // Keep sequence chains flat: delay plus timing/spring/decay only.
@@ -653,7 +716,7 @@ function lowerChain(steps, env, ctx, completion, loop = null, trailing = null) {
653
716
  restart: lowerAnimation({ ...steps[0], delayMs: steps[0].delayMs + loop.trailingDelay }, env),
654
717
  finalWait: loop.iterations >= 0 && completion && loop.trailingDelay > 0
655
718
  ? {
656
- delayMs: loop.trailingDelay,
719
+ delayMs: totalMs(loop.trailingDelay),
657
720
  owner: waitOwner(ctx, loop.key, true),
658
721
  }
659
722
  : null,
@@ -682,6 +745,7 @@ const emptyStart = (ctx, completion) => ({
682
745
  firstConfig: ctx.animIdx,
683
746
  completion,
684
747
  completionWait: null,
748
+ completionJoin: null,
685
749
  });
686
750
  /** Numbers each composition node once, so a key names the place it is written. */
687
751
  const compositionIds = new WeakMap();
@@ -776,7 +840,11 @@ export function stopWaitOwner(node, env, ctx) {
776
840
  *
777
841
  * @returns The wait.
778
842
  */
779
- const completionWait = (ctx, key, delayMs, callback) => ({ delayMs, callback, owner: waitOwner(ctx, key, true) });
843
+ const completionWait = (ctx, key, delayMs, callback) => ({
844
+ delayMs: totalMs(delayMs),
845
+ callback,
846
+ owner: waitOwner(ctx, key, true),
847
+ });
780
848
  /**
781
849
  * A start that drives no value. As in JS, its completion still runs as finished once the composition's delays
782
850
  * have passed, counted down in a completion wait of its own.
@@ -795,7 +863,7 @@ function startNothing(ctx, completion, delayMs, key) {
795
863
  const start = {
796
864
  kind: 'completeAfter',
797
865
  completion,
798
- delayMs,
866
+ delayMs: totalMs(delayMs),
799
867
  owner: null,
800
868
  };
801
869
  if (delayMs > 0) {
@@ -863,13 +931,13 @@ function lowerLoopStart(loopNode, env, ctx, completion, key) {
863
931
  if (!steps.length) {
864
932
  return iterations < 0
865
933
  ? emptyStart(ctx, completion)
866
- : startNothing(ctx, completion, Math.min(iterations * trailingDelay, INT_MAX), key);
934
+ : startNothing(ctx, completion, iterations * trailingDelay, key);
867
935
  }
868
936
  // A timing with no duration and no delay completes inside er_anim_value_animate, so a loop made only of
869
937
  // those would restart itself forever without returning.
870
938
  const instant = (animEntry) => animEntry.kind === 'timing' &&
871
939
  animEntry.delayMs === 0 &&
872
- Math.round(Number(evalStaticOr(animEntry.get('duration'), env, 250))) === 0;
940
+ timingDuration(animEntry.get, env) === 0;
873
941
  if (trailingDelay === 0 && steps.every(instant)) {
874
942
  throw aotError('AOT: every step of this Animated.loop finishes instantly, so it would never stop repeating', 'give a step a duration or a delay.');
875
943
  }
@@ -967,27 +1035,27 @@ export function lowerAnimateStart(expr, env, state, ctx) {
967
1035
  if (completion && entries.length > 1) {
968
1036
  throw aotError('AOT: a .start(onComplete) callback on a parallel/stagger animation is not yet supported', 'attach the completion callback to a single animation or an Animated.sequence(...). For "after all parallel anims", restructure as a sequence.');
969
1037
  }
970
- // A spring or decay has no fixed end, so a delay beside it that runs past its start cannot be waited out yet.
1038
+ // Each entry starts on its own, numbered after the configs already in this body.
1039
+ const start = emptyStart(ctx, completion);
1040
+ for (const animEntry of entries) {
1041
+ start.animations.push(lowerAnimation(animEntry, env));
1042
+ ctx.animIdx++;
1043
+ }
1044
+ // A spring or decay has no fixed end, so a delay beside it that runs past its start is joined at run time.
971
1045
  const [only] = entries;
972
1046
  if (completion &&
973
- only &&
974
1047
  only.kind !== 'timing' &&
975
1048
  !only.loop &&
976
1049
  duration != null &&
977
1050
  duration > only.delayMs) {
978
- throw aotError(`AOT: a .start(onComplete) callback on an Animated.${only.kind} beside a longer Animated.delay is not yet supported`, `a ${only.kind} has no fixed length, so the callback cannot wait for whichever ends last. Run them in an ` +
979
- 'Animated.sequence([...]) instead, or drop the delay.');
980
- }
981
- // Each entry starts on its own, numbered after the configs already in this body.
982
- const start = emptyStart(ctx, completion);
983
- for (const animEntry of entries) {
984
- start.animations.push(lowerAnimation(animEntry, env));
985
- ctx.animIdx++;
1051
+ start.completionJoin = {
1052
+ delayMs: totalMs(duration),
1053
+ owner: waitOwner(ctx, key, true),
1054
+ };
986
1055
  }
987
1056
  // A delay beside the one timing that outlasts it holds the completion back until the composition ends.
988
- if (completion && only?.kind === 'timing' && !only.loop && duration != null) {
989
- const end = only.delayMs +
990
- Math.round(Number(evalStaticOr(only.get('duration'), env, 250)));
1057
+ if (completion && only.kind === 'timing' && !only.loop && duration != null) {
1058
+ const end = only.delayMs + timingDuration(only.get, env);
991
1059
  if (duration > end) {
992
1060
  start.completionWait = completionWait(ctx, key, duration - end, `er_waitcb_${ctx.out.seqN++}`);
993
1061
  ctx.out.animCbs.push({
@@ -25,8 +25,11 @@ import { printAnimationCallback, printDepEffectCheck, printEffectFunction, print
25
25
  import { printKeyboard } from './c/keyboard.mjs';
26
26
  import { printElementTree, printNode, printNodeUpdate } from './c/nodes.mjs';
27
27
  import { printPanDecls, printPanQuery } from './c/pan-responder.mjs';
28
+ import { APP_LIMIT_DEFINITION, CHANGED_FLAGS, printChangedFlag, } from './c/statements.mjs';
28
29
  import { printVectorBlocks, printVectorRebuild } from './c/vectors.mjs';
29
- import { isStateDriven, nodesOf, stateDrivenVectorOf } from './ir/nodes.mjs';
30
+ import { isStateDriven, nodesOf, stateDrivenVectorOf, updatedVectorOf, } from './ir/nodes.mjs';
31
+ import { nodeReads, vectorReads } from './ir/reads.mjs';
32
+ import { hasBoot, printBootDecls, printBootFunction } from './c/boot.mjs';
30
33
  /*----------------------------------------------------------------------------------------------------------------------
31
34
  - Constants
32
35
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -36,6 +39,8 @@ const [PKG_MAJOR, PKG_MINOR] = PKG_VERSION.split('.');
36
39
  // libm symbols, and the helpers that call them; any of them in the generated code means it includes <math.h>.
37
40
  const LIBM_USE = new RegExp('\\b(sinf|cosf|tanf|sqrtf|fabsf|roundf|floorf|ceilf|fminf|fmaxf|atan2f|powf|fmodf|isfinite|' +
38
41
  'app_roundf|app_ftoa|app_vector_dirty|M_PI)\\b');
42
+ // The double-precision libm symbols a value worked out at boot can call.
43
+ const BOOT_LIBM_USE = /\b(sin|cos|tan|sqrt|fabs|floor|ceil|fmin|fmax|atan2|pow|fmod|app_round)\(/;
39
44
  /*----------------------------------------------------------------------------------------------------------------------
40
45
  - Implementation
41
46
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -60,6 +65,40 @@ export const demoMarker = (demo) => `ER_AOT_DEMO_${demo.replace(/[^A-Za-z0-9]/gu
60
65
  * @returns The generated app.gen.c and app.gen.h, and what they contain.
61
66
  */
62
67
  export const compileSourceImpl = (src, demo, opts, wide, stores) => writeApp(lowerApp(src, opts, wide, stores), demo, opts);
68
+ /**
69
+ * app_update()'s entries, each set again only when a state it reads changed. Consecutive entries that read the
70
+ * same state share one test; an entry that reads something untracked, or nothing, runs every time.
71
+ *
72
+ * @param entries Each node's or drawing's reads, and its C lines.
73
+ * @param stateRecords The app's state, in declaration order.
74
+ *
75
+ * @returns The C lines.
76
+ */
77
+ function printGuardedUpdates(entries, stateRecords) {
78
+ const testOf = (reads) => reads?.size
79
+ ? stateRecords
80
+ .filter(stateRecord => reads.has(stateRecord))
81
+ .map(stateRecord => `changed.${stateRecord.cField}`)
82
+ .join(' || ')
83
+ : null;
84
+ const lines = [];
85
+ let index = 0;
86
+ while (index < entries.length) {
87
+ const test = testOf(entries[index].reads);
88
+ if (test === null) {
89
+ lines.push(...entries[index].lines);
90
+ index++;
91
+ continue;
92
+ }
93
+ lines.push(` if (${test})`, ' {');
94
+ while (index < entries.length && testOf(entries[index].reads) === test) {
95
+ lines.push(...entries[index].lines.map(line => ' ' + line));
96
+ index++;
97
+ }
98
+ lines.push(' }');
99
+ }
100
+ return lines;
101
+ }
63
102
  /**
64
103
  * Writes a lowered app as C: file-scope state, declarations and functions, then er_app_build(), in
65
104
  * app.gen.c, and the app's public entry points in app.gen.h.
@@ -105,11 +144,22 @@ export function writeApp(app, demo, opts) {
105
144
  `{${scalarRecords.map(scalarRecord => ` .${scalarRecord.cField} = ${cConstant(scalarRecord.initial, scalarRecord.cType)}`).join(',')} ` +
106
145
  `};\n`
107
146
  : '';
108
- const stateBlock = [scalarBlock, listBlocks].filter(Boolean).join('\n');
147
+ // One flag per state a node or drawing reads, set by each write and cleared by app_update().
148
+ const watchedRecords = stateRecords.filter(stateRecord => stateRecord.isWatched);
149
+ const changedBlock = watchedRecords.length
150
+ ? `typedef struct\n{\n${watchedRecords.map(stateRecord => ` uint8_t ${stateRecord.cField};`).join('\n')}\n} ` +
151
+ `ErAppChanged;\n\nstatic ErAppChanged ${CHANGED_FLAGS};\n`
152
+ : '';
153
+ const bootDecls = printBootDecls(app.boot);
154
+ const stateBlock = [scalarBlock, listBlocks, changedBlock, bootDecls]
155
+ .filter(Boolean)
156
+ .join('\n');
157
+ const bootFn = printBootFunction(app.boot, opts.screen);
109
158
  // The nodes er_app_build() creates, each before its children, and what app_update() re-applies to them.
110
159
  const nodes = nodesOf(app.root);
111
160
  const buildLines = printElementTree(app.root).join('\n');
112
- const updates = nodes.flatMap(node => printNode(node).update ?? []);
161
+ const updatedNodes = nodes.filter(isStateDriven);
162
+ const updates = updatedNodes.map(node => printNode(node).update);
113
163
  // A file-scope handle for each node app_update() re-applies, and one for each drawing it rebuilds.
114
164
  const handleDecls = nodes
115
165
  .flatMap(node => [
@@ -151,16 +201,29 @@ export function writeApp(app, demo, opts) {
151
201
  if (updates.length) {
152
202
  lines.push(' ERProps p;');
153
203
  }
154
- for (const update of updates) {
155
- lines.push(...printNodeUpdate(update));
156
- }
157
- // State-driven Svgs: recompute the op-tape from state and re-upload.
158
- for (const node of nodes) {
159
- const vector = stateDrivenVectorOf(node);
160
- if (vector) {
161
- lines.push(...printVectorRebuild(node.id, vector));
162
- }
204
+ // A snapshot of the flags, cleared first, so state an effect below writes is applied on the next update.
205
+ if (watchedRecords.length) {
206
+ lines.push(` const ErAppChanged changed = ${CHANGED_FLAGS};`, ` memset(&${CHANGED_FLAGS}, 0, sizeof(${CHANGED_FLAGS}));`);
163
207
  }
208
+ // Node props, then state-driven Svgs' op-tapes, each set again only when a state it reads changed.
209
+ const entries = [
210
+ ...updatedNodes.map((node, index) => ({
211
+ reads: nodeReads(node),
212
+ lines: printNodeUpdate(updates[index]),
213
+ })),
214
+ ...nodes.flatMap(node => {
215
+ const vector = updatedVectorOf(node);
216
+ return vector
217
+ ? [
218
+ {
219
+ reads: vectorReads(vector),
220
+ lines: printVectorRebuild(node.id, vector),
221
+ },
222
+ ]
223
+ : [];
224
+ }),
225
+ ];
226
+ lines.push(...printGuardedUpdates(entries, stateRecords));
164
227
  // Dep-driven useEffect: run each effect whose dependency value changed since the last app_update.
165
228
  for (const effect of out.depEffects) {
166
229
  lines.push(printDepEffectCheck(effect));
@@ -228,7 +291,8 @@ static int er_timer_add(int ms, bool repeat, void (*fn)(void))
228
291
  return (s_timers[i].gen * ER_AOT_MAX_TIMERS) + i;
229
292
  }
230
293
  }
231
- return -1; /* table full (raise ER_AOT_MAX_TIMERS) */
294
+ APP_LIMIT("timer table full, raise ER_AOT_MAX_TIMERS");
295
+ return -1;
232
296
  }`
233
297
  : '';
234
298
  const timerFnDefs = timerFns
@@ -332,7 +396,9 @@ static int16_t app_round_dim(double v)
332
396
  : '';
333
397
  // Include <math.h> when the generated code, or a helper it calls, uses a libm symbol.
334
398
  const usesMath = out.needsMath ||
399
+ BOOT_LIBM_USE.test(bootFn) ||
335
400
  LIBM_USE.test([
401
+ bootFn,
336
402
  stateBlock,
337
403
  refDecls,
338
404
  vectorBuilderBlock,
@@ -348,7 +414,11 @@ static int16_t app_round_dim(double v)
348
414
  const hostRecords = scalarRecords.filter(scalarRecord => scalarRecord.host);
349
415
  const hostSettersBlock = hostRecords
350
416
  .map(hostRecord => `void er_app_set_${hostRecord.name}(${cScalarType(hostRecord.cType)} v)\n{\n ` +
351
- `${hostRecord.cMember} = v;\n${hasUpdate ? ' app_update();\n' : ''}}`)
417
+ `${hostRecord.cMember} = v;\n` +
418
+ printChangedFlag(hostRecord, ' ')
419
+ .map(line => line + '\n')
420
+ .join('') +
421
+ `${hasUpdate ? ' app_update();\n' : ''}}`)
352
422
  .join('\n\n');
353
423
  const hostSetterProtos = hostRecords
354
424
  .map(hostRecord => `/** @brief Host-fed input '${hostRecord.name}' (useHostValue): set its value and ` +
@@ -448,6 +518,16 @@ static int16_t app_round_dim(double v)
448
518
  ' if (v <= -2147483648.0f)\n {\n return INT_MIN;\n }\n' +
449
519
  ' return (int)v;\n}',
450
520
  ],
521
+ [
522
+ 'app_d2i',
523
+ '/* A double kept as an int, as app_f2i keeps a float: for a value worked out at boot, which a float ' +
524
+ 'would round. */\n' +
525
+ 'static int app_d2i(double v)\n{\n' +
526
+ ' if (v != v)\n {\n return 0;\n }\n' +
527
+ ' if (v >= 2147483647.0)\n {\n return INT_MAX;\n }\n' +
528
+ ' if (v <= -2147483648.0)\n {\n return INT_MIN;\n }\n' +
529
+ ' return (int)v;\n}',
530
+ ],
451
531
  [
452
532
  'app_roundf',
453
533
  "/* Math.round as JS rounds: to the nearest whole number, halves up (toward +Infinity). C's roundf takes\n" +
@@ -466,6 +546,12 @@ static int16_t app_round_dim(double v)
466
546
  ' if (v == 0.0f)\n {\n return "0";\n }\n' +
467
547
  ' snprintf(buf, 16, "%g", (double)v);\n return buf;\n}',
468
548
  ],
549
+ [
550
+ 'app_round',
551
+ '/* Math.round as JS rounds, in double precision for a value worked out at boot: halves up. */\n' +
552
+ 'static double app_round(double v)\n{\n' +
553
+ ' const double f = floor(v);\n return v - f >= 0.5 ? f + 1.0 : f;\n}',
554
+ ],
469
555
  [
470
556
  'app_opacity',
471
557
  "/* A state-driven opacity as the engine's 0-255 byte: clamped to 0..1 and rounded, as Flow A's bridge and\n" +
@@ -610,6 +696,7 @@ static int16_t app_round_dim(double v)
610
696
  ];
611
697
  // Generated code with literals and comments blanked, so only a real call emits a helper (unused statics warn).
612
698
  const helperCallers = stripCLiterals([
699
+ bootFn,
613
700
  stateBlock,
614
701
  refDecls,
615
702
  vectorBuilderBlock,
@@ -663,6 +750,25 @@ static int16_t app_round_dim(double v)
663
750
  '#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n'
664
751
  : '';
665
752
  const limitsInclude = usesLimits ? '#include <limits.h>\n' : '';
753
+ // The root and every node in the tree, all created by er_app_build().
754
+ const totalNodes = out.nodeCount + 1;
755
+ const limitBlock = `/* er_app_build() creates every node the app has, so a pool too small for the tree fails here, not on the
756
+ device. ERUI_MAX_NODES comes from er_scene.h, as the engine was configured or its default. */
757
+ _Static_assert(ERUI_MAX_NODES >= ${totalNodes}, "this app builds ${totalNodes} nodes: raise ERUI_MAX_NODES to at least ${totalNodes}");
758
+
759
+ ${APP_LIMIT_DEFINITION}
760
+ /* er_node_create, reporting a full pool: the engine skips a NULL node, so the app would run with part of
761
+ its tree missing. */
762
+ static ERNode* app_node_create(ERNodeType type)
763
+ {
764
+ ERNode* node = er_node_create(type);
765
+ if (!node)
766
+ {
767
+ APP_LIMIT("node pool full, raise ERUI_MAX_NODES");
768
+ }
769
+ return node;
770
+ }
771
+ `;
666
772
  // A blank line sets off each non-empty block before and after.
667
773
  const spaced = (block) => (block ? '\n' + block + '\n' : '');
668
774
  const keyboard = app.keyboard ? printKeyboard(app.keyboard) : null;
@@ -694,8 +800,30 @@ static int16_t app_round_dim(double v)
694
800
  ? keyboard.setup +
695
801
  ' /* app-supplied on-screen keyboard layout/appearance */\n'
696
802
  : '';
803
+ const initialChanged = watchedRecords.length
804
+ ? ` memset(&${CHANGED_FLAGS}, 1, sizeof(${CHANGED_FLAGS})); /* the first update sets every node */\n`
805
+ : '';
697
806
  const initialUpdate = hasUpdate
698
- ? '\n app_update(); /* apply initial state-dependent props */\n'
807
+ ? `\n${initialChanged} app_update(); /* apply initial state-dependent props */\n`
808
+ : '';
809
+ // er_app_fits() asks app_boot() without disturbing the values a built app reads.
810
+ const fitsBody = !hasBoot(app.boot)
811
+ ? [' (void)screen_w;', ' (void)screen_h;', ' return true;']
812
+ : bootDecls
813
+ ? [
814
+ ' const ErAppBoot built = s_boot;',
815
+ ' const bool fits = app_boot(screen_w, screen_h);',
816
+ ' s_boot = built;',
817
+ ' return fits;',
818
+ ]
819
+ : [' return app_boot(screen_w, screen_h);'];
820
+ const fitsFn = 'bool er_app_fits(int screen_w, int screen_h)\n{\n' +
821
+ fitsBody.join('\n') +
822
+ '\n}';
823
+ const bootCall = hasBoot(app.boot)
824
+ ? '\n /* The values that depend on the panel size; a panel the app was not compiled for builds ' +
825
+ 'nothing. */\n' +
826
+ ' if (!app_boot(screen_w, screen_h))\n {\n return false;\n }\n'
699
827
  : '';
700
828
  // app.gen.c: includes and version pin, then file-scope state, declarations and functions, then er_app_build().
701
829
  const body = `/*
@@ -711,7 +839,8 @@ static int16_t app_round_dim(double v)
711
839
  #include <string.h>
712
840
 
713
841
  /* Every string this file writes goes into a FIXED-SIZE slot (a state buffer, ERProps.text), so an
714
- over-long value is truncated by design — the app cannot grow the buffer the way JS grows a string.
842
+ over-long value is truncated by design — the app cannot grow the buffer the way JS grows a string, and
843
+ a cut app string is reported through APP_LIMIT.
715
844
  GCC's -Wformat-truncation reports exactly that intent for any format combining %s with anything else,
716
845
  and ESP-IDF compiles with -Werror, so leaving it on would fail the build for ordinary text like
717
846
  {'n=' + name}. Clang does not implement the warning; the guard keeps its "unknown warning group"
@@ -725,21 +854,24 @@ static int16_t app_round_dim(double v)
725
854
  A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
726
855
  _Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
727
856
  "${versionMismatch}");
728
- ${mathInclude}${limitsInclude}${dimRoundBlock}\n${clockBlock}\n${stateBlock ? '\n' + stateBlock : ''}${declarations}
857
+ ${mathInclude}${limitsInclude}
858
+ ${limitBlock}${dimRoundBlock}\n${clockBlock}\n${stateBlock ? '\n' + stateBlock : ''}${declarations}
729
859
  ${appTickFn}
730
860
 
731
861
  void er_app_set_wall_clock(int64_t epoch_ms)
732
862
  {
733
863
  s_wall_offset_ms = epoch_ms - (int64_t)er_now_ms64();${hasUpdate ? '\n s_wall_clock_changed = 1;' : ''}
734
864
  }
735
- ${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}
736
- void er_app_build(int screen_w, int screen_h)
865
+ ${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}${bootFn ? '\n' + bootFn + '\n' : ''}
866
+ ${fitsFn}
867
+
868
+ bool er_app_build(int screen_w, int screen_h)
737
869
  {
738
870
  ERProps p;
739
871
  ERNode* ${nodeDecls.join(';\n ERNode* ')};
740
-
872
+ ${bootCall}
741
873
  /* A screen-sized root the app tree fills (mirrors AppRegistry mounting into a screen-sized host). */
742
- ERNode* root = er_node_create(ER_NODE_VIEW);
874
+ ERNode* root = app_node_create(ER_NODE_VIEW);
743
875
  er_props_default(&p);
744
876
  p.width = (int16_t)screen_w;
745
877
  p.height = (int16_t)screen_h;
@@ -748,23 +880,22 @@ ${animCreate ? '\n' + animCreate + '\n' : ''}
748
880
  ${buildLines}
749
881
  er_tree_append_child(root, ${app.root.id});
750
882
  er_tree_set_root(root);
751
- ${keyboardSetup}${initialUpdate}${mountEffectsBlock}}
883
+ ${keyboardSetup}${initialUpdate}${mountEffectsBlock} return true;
884
+ }
752
885
  `;
753
886
  // app.gen.h: what the file was generated for, and the app's public entry points.
754
887
  const header = `/* Generated by the embedded-react Flow B AOT compiler. DO NOT EDIT. */
755
888
  #ifndef ER_APP_GEN_H
756
889
  #define ER_APP_GEN_H
757
890
 
891
+ #include <stdbool.h>
758
892
  #include <stdint.h>
759
893
 
760
894
  /*
761
- * What this file was generated FOR. er_app_build() takes the screen size at runtime, but a responsive app
762
- * folds its \`screen.width\`/\`screen.height\` branching at GENERATE time — so the layout in here is already
763
- * committed to these dimensions and no runtime argument can change it.
764
- *
765
- * Every board example consumes the same dist/app.gen.c, so generating for one board and then building
766
- * another produces firmware that compiles, links, boots, and lays out wrong. Boards \`_Static_assert\` these
767
- * against their own panel size to turn that into a compile error; see each board example's main.c.
895
+ * The panel this file was generated at. Values that depend only on the panel size are worked out at boot by
896
+ * er_app_build(), but a branch on \`screen\` that changes the tree was compiled for this panel only, and so
897
+ * was any value the compiler had to know. er_app_build() checks those at boot and builds nothing on a panel
898
+ * that differs in any of them, returning false; er_app_fits() asks the same without building.
768
899
  *
769
900
  * WHICH demo is recorded the same way, as a marker macro named ER_AOT_DEMO_<demo> with every character
770
901
  * outside [A-Za-z0-9] encoded as _<hex>_ (so \`watch-face\` defines ER_AOT_DEMO_watch_2d_face). The encoding
@@ -777,8 +908,15 @@ ${keyboardSetup}${initialUpdate}${mountEffectsBlock}}
777
908
  #define ER_AOT_DEMO ${cstr(demo)}
778
909
  #define ${demoMarker(demo)} 1
779
910
 
780
- /** @brief Builds the AOT-compiled app's scene graph + state machine (call once after backend init). */
781
- void er_app_build(int screen_w, int screen_h);
911
+ /** @brief Builds the AOT-compiled app's scene graph + state machine (call once after backend init).
912
+ * @return false, having built nothing, when the panel does not take the layout this file was compiled
913
+ * for (see er_app_fits()). */
914
+ bool er_app_build(int screen_w, int screen_h);
915
+
916
+ /** @brief Whether a panel of this size takes the layout this file was compiled for. Values that depend only
917
+ * on the panel size are worked out at boot, so any panel that takes the same layout fits; what the
918
+ * compiler had to fold at its own panel (a branch that changes the tree, a font size) must match. */
919
+ bool er_app_fits(int screen_w, int screen_h);
782
920
 
783
921
  /** @brief Advances app timers (setInterval/setTimeout). Call once per frame with the elapsed ms; a no-op
784
922
  * for apps that use no timers, so it is always safe to call. */