embedded-react 0.15.0 → 0.17.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 (62) hide show
  1. package/aot/compile.mjs +173 -8272
  2. package/aot/compiler/animations.mjs +1001 -0
  3. package/aot/compiler/assemble.mjs +922 -0
  4. package/aot/compiler/boot.mjs +441 -0
  5. package/aot/compiler/branch-merge.mjs +319 -0
  6. package/aot/compiler/c/animations.mjs +362 -0
  7. package/aot/compiler/c/boot.mjs +127 -0
  8. package/aot/compiler/c/expressions.mjs +270 -0
  9. package/aot/compiler/c/functions.mjs +268 -0
  10. package/aot/compiler/c/keyboard.mjs +96 -0
  11. package/aot/compiler/c/nodes.mjs +294 -0
  12. package/aot/compiler/c/pan-responder.mjs +136 -0
  13. package/aot/compiler/c/statements.mjs +271 -0
  14. package/aot/compiler/c/text.mjs +83 -0
  15. package/aot/compiler/c/vectors.mjs +381 -0
  16. package/aot/compiler/c-syntax.mjs +127 -0
  17. package/aot/compiler/check.mjs +165 -0
  18. package/aot/compiler/collect.mjs +785 -0
  19. package/aot/compiler/control-flow.mjs +696 -0
  20. package/aot/compiler/diagnostics.mjs +137 -0
  21. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  22. package/aot/compiler/elements/dial.mjs +346 -0
  23. package/aot/compiler/elements/flat-list.mjs +139 -0
  24. package/aot/compiler/elements/image.mjs +151 -0
  25. package/aot/compiler/elements/modal.mjs +158 -0
  26. package/aot/compiler/elements/props.mjs +474 -0
  27. package/aot/compiler/elements/switch.mjs +183 -0
  28. package/aot/compiler/elements/text-input.mjs +171 -0
  29. package/aot/compiler/expressions.mjs +1579 -0
  30. package/aot/compiler/handlers.mjs +1072 -0
  31. package/aot/compiler/ir/animations.mjs +16 -0
  32. package/aot/compiler/ir/app.mjs +16 -0
  33. package/aot/compiler/ir/boot.mjs +16 -0
  34. package/aot/compiler/ir/expressions.mjs +16 -0
  35. package/aot/compiler/ir/functions.mjs +16 -0
  36. package/aot/compiler/ir/keyboard.mjs +16 -0
  37. package/aot/compiler/ir/nodes.mjs +107 -0
  38. package/aot/compiler/ir/pan-responder.mjs +16 -0
  39. package/aot/compiler/ir/reads.mjs +351 -0
  40. package/aot/compiler/ir/source.mjs +16 -0
  41. package/aot/compiler/ir/statements.mjs +16 -0
  42. package/aot/compiler/ir/text.mjs +16 -0
  43. package/aot/compiler/ir/types.mjs +185 -0
  44. package/aot/compiler/ir/vectors.mjs +16 -0
  45. package/aot/compiler/keyboard.mjs +152 -0
  46. package/aot/compiler/lower.mjs +311 -0
  47. package/aot/compiler/nodes.mjs +688 -0
  48. package/aot/compiler/options.mjs +55 -0
  49. package/aot/compiler/out.mjs +94 -0
  50. package/aot/compiler/pan-responder.mjs +354 -0
  51. package/aot/compiler/parse.mjs +300 -0
  52. package/aot/compiler/static-eval.mjs +454 -0
  53. package/aot/compiler/style-text.mjs +807 -0
  54. package/aot/compiler/svg.mjs +1167 -0
  55. package/aot/compiler/types.mjs +16 -0
  56. package/aot/screenshot-smoke.mjs +95 -55
  57. package/aot/style-map.mjs +366 -304
  58. package/cli.mjs +5 -8
  59. package/package.json +14 -6
  60. package/sim/embedded-react.wasm +0 -0
  61. package/src/embedded-react/FlatList.js +4 -4
  62. package/src/props.js +1 -1
@@ -0,0 +1,922 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { readFileSync } from 'node:fs';
20
+ import { cConstant, cScalarType, stripCLiterals, floatLit, cstr, } from './c-syntax.mjs';
21
+ import { CHECKED_OP } from './expressions.mjs';
22
+ import { lowerApp } from './lower.mjs';
23
+ import { printWaitDeclarations } from './c/animations.mjs';
24
+ import { printAnimationCallback, printDepEffectCheck, printEffectFunction, printHandler, printMountEffect, printStaticDecl, printTimerFunction, } from './c/functions.mjs';
25
+ import { printKeyboard } from './c/keyboard.mjs';
26
+ import { printElementTree, printNode, printNodeUpdate } from './c/nodes.mjs';
27
+ import { printPanDecls, printPanQuery } from './c/pan-responder.mjs';
28
+ import { CHANGED_FLAGS, printChangedFlag } from './c/statements.mjs';
29
+ import { printVectorBlocks, printVectorRebuild } from './c/vectors.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';
33
+ /*----------------------------------------------------------------------------------------------------------------------
34
+ - Constants
35
+ ---------------------------------------------------------------------------------------------------------------------*/
36
+ // The compiler's version, stamped into app.gen.c and asserted against er_version.h, so a mismatch fails to compile.
37
+ const PKG_VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
38
+ const [PKG_MAJOR, PKG_MINOR] = PKG_VERSION.split('.');
39
+ // libm symbols, and the helpers that call them; any of them in the generated code means it includes <math.h>.
40
+ const LIBM_USE = new RegExp('\\b(sinf|cosf|tanf|sqrtf|fabsf|roundf|floorf|ceilf|fminf|fmaxf|atan2f|powf|fmodf|isfinite|' +
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)\(/;
44
+ /*----------------------------------------------------------------------------------------------------------------------
45
+ - Implementation
46
+ ---------------------------------------------------------------------------------------------------------------------*/
47
+ /**
48
+ * The `#ifndef` marker a board example guards on, from a demo name. Every character outside [A-Za-z0-9]
49
+ * becomes `_<hex code point>_`, so the result is a C identifier AND the mapping is one-to-one: `foo-bar`
50
+ * is ER_AOT_DEMO_foo_2d_bar and `foo_bar` is ER_AOT_DEMO_foo_5f_bar. Flattening both to `foo_bar` would
51
+ * let a board guard accept the wrong app from either entry point that generates one.
52
+ */
53
+ export const demoMarker = (demo) => `ER_AOT_DEMO_${demo.replace(/[^A-Za-z0-9]/gu, character => `_${character.codePointAt(0).toString(16)}_`)}`;
54
+ /**
55
+ * Compiles a Flow B app's JSX (or TSX) source to C: lowers it (lowerApp) and writes the result as app.gen.c
56
+ * and app.gen.h. Pure (no I/O), so it can be unit-tested directly; compileSource (compile.mts) is the public
57
+ * entry around it.
58
+ *
59
+ * @param src The App.jsx/App.tsx source text.
60
+ * @param demo Demo name (only used in the generated-by header comment).
61
+ * @param opts compileSource's options, resolved (see resolveOptions).
62
+ * @param wide State/ref slots to declare 64-bit (see compileWidened).
63
+ * @param stores Collects every value stored into an int slot.
64
+ *
65
+ * @returns The generated app.gen.c and app.gen.h, and what they contain.
66
+ */
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
+ }
102
+ /**
103
+ * Writes a lowered app as C: file-scope state, declarations and functions, then er_app_build(), in
104
+ * app.gen.c, and the app's public entry points in app.gen.h.
105
+ *
106
+ * @param app The lowered app.
107
+ * @param demo Demo name (only used in the generated-by header comment).
108
+ * @param opts compileSource's options, resolved (see resolveOptions).
109
+ *
110
+ * @returns The generated app.gen.c and app.gen.h, and what they contain.
111
+ */
112
+ export function writeApp(app, demo, opts) {
113
+ const { out } = app;
114
+ // One ERNode* local in er_app_build() per node the tree allocated.
115
+ const nodeDecls = Array.from({ length: out.nodeCount }, (_, nodeIndex) => `n${nodeIndex}`);
116
+ // App state + every inlined child instance's per-instance state (each already namespaced via cField).
117
+ const stateRecords = app.state;
118
+ const scalarRecords = stateRecords.filter(stateRecord => stateRecord.kind === 'scalar');
119
+ const listRecords = stateRecords.filter(stateRecord => stateRecord.kind === 'list');
120
+ // Scalar state → one ErAppState struct. List state → a fixed-capacity struct array + a count each.
121
+ const fieldCDecl = (field) => field.kind === 'string'
122
+ ? ` char ${field.key}[${opts.caps.listStrCap}];`
123
+ : ` ${field.kind} ${field.key};`;
124
+ const itemInit = (item, struct) => {
125
+ const values = struct.fields.map(field => field.kind === 'string'
126
+ ? cstr(String(item[field.key] ?? ''))
127
+ : field.kind === 'float'
128
+ ? floatLit(Number(item[field.key]) || 0)
129
+ : String(Math.round(Number(item[field.key]) || 0)));
130
+ return `{ ${values.join(', ')} }`;
131
+ };
132
+ const listBlocks = listRecords
133
+ .map(listRecord => `typedef struct\n{\n${listRecord.struct.fields.map(fieldCDecl).join('\n')}\n} ${listRecord.cTypeName};\n\n` +
134
+ `static ${listRecord.cTypeName} ${listRecord.arrayName}[${listRecord.cap}] = ` +
135
+ `{${listRecord.items.map(item => '\n ' + itemInit(item, listRecord.struct)).join(',')}\n};\n` +
136
+ `static int ${listRecord.countMember} = ${listRecord.items.length};\n`)
137
+ .join('\n');
138
+ const scalarFieldDecl = (scalarRecord) => scalarRecord.cType === 'string'
139
+ ? ` char ${scalarRecord.cField}[${opts.caps.listStrCap}];`
140
+ : ` ${cScalarType(scalarRecord.cType)} ${scalarRecord.cField};`;
141
+ const scalarBlock = scalarRecords.length
142
+ ? `typedef struct\n{\n${scalarRecords.map(scalarFieldDecl).join('\n')}\n} ` +
143
+ `ErAppState;\n\nstatic ErAppState s_state = ` +
144
+ `{${scalarRecords.map(scalarRecord => ` .${scalarRecord.cField} = ${cConstant(scalarRecord.initial, scalarRecord.cType)}`).join(',')} ` +
145
+ `};\n`
146
+ : '';
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);
158
+ // The nodes er_app_build() creates, each before its children, and what app_update() re-applies to them.
159
+ const nodes = nodesOf(app.root);
160
+ const buildLines = printElementTree(app.root).join('\n');
161
+ const updatedNodes = nodes.filter(isStateDriven);
162
+ const updates = updatedNodes.map(node => printNode(node).update);
163
+ // A file-scope handle for each node app_update() re-applies, and one for each drawing it rebuilds.
164
+ const handleDecls = nodes
165
+ .flatMap(node => [
166
+ ...(isStateDriven(node) ? [node.id] : []),
167
+ ...(stateDrivenVectorOf(node) ? [node.id] : []),
168
+ ])
169
+ .map(nodeId => `static ERNode* s_${nodeId};`)
170
+ .join('\n');
171
+ // Static per-value ref, skipping refs the C never touches, so consumer builds don't warn about unused statics.
172
+ const refDecls = app.refs
173
+ .filter(refRecord => refRecord.used)
174
+ .map(refRecord => `static ` +
175
+ `${refRecord.kind === 'value' ? cScalarType(refRecord.cType) : refRecord.cType} ` +
176
+ `${refRecord.cVar} = ${refRecord.kind === 'value' ? cConstant(refRecord.initial, refRecord.cType) : 'NULL'};`)
177
+ .join('\n');
178
+ // Vector op-tapes + paint tables, and the build_svgN() functions declared before app_update, which calls them.
179
+ const { data: vectorBlock, builders: vectorBuilderBlock } = printVectorBlocks(out.vectors);
180
+ // Animated values — one engine-side handle each, created at the top of er_app_build (binds reference them).
181
+ const animList = app.animations;
182
+ const animDecls = animList
183
+ .map(animValue => `static ERAnimValueHandle ${animValue.cVar};`)
184
+ .join('\n');
185
+ const animCreate = animList
186
+ .map(animValue => ` ${animValue.cVar} = er_anim_value_create(${floatLit(animValue.initial)});`)
187
+ .join('\n');
188
+ // The app's functions, and what er_app_build() runs last, as C.
189
+ const { hasUpdate } = app;
190
+ const usesWaits = [...out.animWaits.values()].some(record => record.isStarted);
191
+ const handlers = out.handlers.map(printHandler);
192
+ const timerFns = out.timerFns.map(printTimerFunction);
193
+ const animCbs = out.animCbs.flatMap(printAnimationCallback);
194
+ const effectFns = out.effectFns.map(printEffectFunction);
195
+ const mountEffects = out.mountEffects.flatMap(printMountEffect).join('\n');
196
+ // app_update(): re-apply state-driven node props, rebuild state-driven Svgs, then run dep-driven effects.
197
+ const updateBlock = (() => {
198
+ if (!hasUpdate)
199
+ return '';
200
+ const lines = ['static void app_update(void)', '{'];
201
+ if (updates.length) {
202
+ lines.push(' ERProps p;');
203
+ }
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}));`);
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));
227
+ // Dep-driven useEffect: run each effect whose dependency value changed since the last app_update.
228
+ for (const effect of out.depEffects) {
229
+ lines.push(printDepEffectCheck(effect));
230
+ }
231
+ lines.push('}');
232
+ return lines.join('\n');
233
+ })();
234
+ // PanResponder gesture state, plus should-set predicates: bool callbacks the engine calls during negotiation.
235
+ const panDeclBlock = out.panResponders.flatMap(printPanDecls).join('\n');
236
+ const queryDefs = out.panResponders
237
+ .flatMap(pan => pan.queries.map(query => printPanQuery(pan, query)))
238
+ .map(query => `static bool ${query.name}(ERNode* node, const EREventData* data, void* ` +
239
+ `user_data)\n{\n (void)node;\n (void)data;\n (void)user_data;\n return ` +
240
+ `${query.expr};\n}`)
241
+ .join('\n\n');
242
+ // Event handlers, each with the engine's event callback signature.
243
+ const handlerDefs = handlers
244
+ .map(handler => `static void ${handler.name}(ERNode* node, const EREventData* data, void* ` +
245
+ `user_data)\n{\n (void)node;\n (void)data;\n ` +
246
+ `(void)user_data;\n${handler.body.join('\n')}\n}`)
247
+ .join('\n\n');
248
+ // Dep-driven effects: a previous-value static per dep, the bodies, and forward decls (app_update comes first).
249
+ const effectDeclsBlock = out.effectDecls
250
+ .flatMap(decl => printStaticDecl(decl, opts.caps.listStrCap))
251
+ .join('\n');
252
+ const effectFwdDecls = effectFns
253
+ .map(effectFn => `static void ${effectFn.name}(void);`)
254
+ .join('\n');
255
+ const effectFnDefs = effectFns
256
+ .map(effectFn => `static void ${effectFn.name}(void)\n{\n${effectFn.body.join('\n')}\n}`)
257
+ .join('\n\n');
258
+ // setInterval/setTimeout: a fixed timer table er_app_tick advances, emitted only when the app uses timers.
259
+ const timerTableBlock = out.usesTimers
260
+ ? `#include <stdbool.h>
261
+
262
+ #ifndef ER_AOT_MAX_TIMERS
263
+ #define ER_AOT_MAX_TIMERS 8
264
+ #endif
265
+
266
+ typedef struct
267
+ {
268
+ int interval_ms;
269
+ int remaining_ms;
270
+ int gen;
271
+ bool repeat;
272
+ bool active;
273
+ void (*fn)(void);
274
+ } ErTimer;
275
+ static ErTimer s_timers[ER_AOT_MAX_TIMERS];
276
+
277
+ /* An id carries the slot AND the generation that owns it, so clearing an id whose timer has already
278
+ finished (a one-shot, or an earlier clear) cannot kill whatever took the slot next. */
279
+ static int er_timer_add(int ms, bool repeat, void (*fn)(void))
280
+ {
281
+ for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
282
+ {
283
+ if (!s_timers[i].active)
284
+ {
285
+ s_timers[i].interval_ms = ms < 1 ? 1 : ms;
286
+ s_timers[i].remaining_ms = s_timers[i].interval_ms;
287
+ s_timers[i].gen = (s_timers[i].gen + 1) & 0xFFFF;
288
+ s_timers[i].repeat = repeat;
289
+ s_timers[i].active = true;
290
+ s_timers[i].fn = fn;
291
+ return (s_timers[i].gen * ER_AOT_MAX_TIMERS) + i;
292
+ }
293
+ }
294
+ return -1; /* table full (raise ER_AOT_MAX_TIMERS) */
295
+ }`
296
+ : '';
297
+ const timerFnDefs = timerFns
298
+ .map(timerFn => `static void ${timerFn.name}(void)\n{\n${timerFn.body.join('\n')}\n}`)
299
+ .join('\n\n');
300
+ // Forward-declare every timer fn: the handlers and effect fns that register one are defined before it.
301
+ const timerFnFwdDecls = timerFns
302
+ .map(timerFn => `static void ${timerFn.name}(void);`)
303
+ .join('\n');
304
+ // Animated.sequence on_complete callbacks each start the next step, so they are forward-declared.
305
+ const animCbDecls = animCbs
306
+ .map(animCb => `static void ${animCb.name}(bool finished, void* user_data);`)
307
+ .join('\n');
308
+ const animCbDefs = animCbs
309
+ .map(animCb => `static void ${animCb.name}(bool finished, void* user_data)\n{\n (void)finished;\n ` +
310
+ ` (void)user_data;\n${animCb.body.join('\n')}\n}`)
311
+ .join('\n\n');
312
+ // Apply a wall-clock change on the app loop, not in the setter: the host may set it before er_app_build().
313
+ const wallClockRefresh = hasUpdate
314
+ ? ' if (s_wall_clock_changed)\n {\n s_wall_clock_changed = 0;\n app_update();\n }\n'
315
+ : '';
316
+ // er_app_tick(): fire due timers; without timers it only applies a clock change, so a host can always call it.
317
+ // Completion waits count down on the app loop too.
318
+ const waitTick = usesWaits ? ' app_wait_tick(dt_ms);\n' : '';
319
+ const appTickFn = out.usesTimers
320
+ ? `void er_app_tick(int dt_ms)
321
+ {
322
+ ${wallClockRefresh}${waitTick} for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
323
+ {
324
+ if (!s_timers[i].active)
325
+ {
326
+ continue;
327
+ }
328
+ s_timers[i].remaining_ms -= dt_ms;
329
+ if (s_timers[i].remaining_ms <= 0)
330
+ {
331
+ void (*fn)(void) = s_timers[i].fn;
332
+ if (s_timers[i].repeat)
333
+ {
334
+ s_timers[i].remaining_ms += s_timers[i].interval_ms;
335
+ if (s_timers[i].remaining_ms <= 0)
336
+ {
337
+ s_timers[i].remaining_ms = s_timers[i].interval_ms; /* dt ran long; don't spiral */
338
+ }
339
+ }
340
+ else
341
+ {
342
+ s_timers[i].active = false;
343
+ }
344
+ if (fn)
345
+ {
346
+ fn();
347
+ }
348
+ }
349
+ }
350
+ }`
351
+ : `void er_app_tick(int dt_ms)\n{\n (void)dt_ms;\n${wallClockRefresh}${waitTick}}`;
352
+ // useEffect(fn, []) bodies, run once at the end of er_app_build().
353
+ const mountEffectsBlock = mountEffects
354
+ ? '\n /* useEffect(fn, []) — run once on mount. */\n' +
355
+ mountEffects +
356
+ '\n'
357
+ : '';
358
+ // app_round_dim() when a state-driven style value has to be snapped to a whole pixel at runtime.
359
+ const usesDimRound = /\bapp_round_dim\(/.test([
360
+ updateBlock,
361
+ handlerDefs,
362
+ queryDefs,
363
+ effectFnDefs,
364
+ animCbDefs,
365
+ timerFnDefs,
366
+ mountEffects,
367
+ buildLines,
368
+ ].join('\n'));
369
+ const dimRoundBlock = usesDimRound
370
+ ? `
371
+ /* Snaps a state-driven style value to a whole pixel the way JavaScript's Math.round does — floor(x + 0.5),
372
+ halves UP rather than away from zero. ERProps dimensions are int16 and a plain cast would truncate toward
373
+ zero, which is how the two flows once laid the same app out a pixel apart. Values known at compile time
374
+ are folded with Math.round; this is that rule's runtime twin, and Flow A's bridge applies the same one. */
375
+ static int16_t app_round_dim(double v)
376
+ {
377
+ /* NaN compares false against everything, so it would slip past both clamps into an undefined cast. */
378
+ if (v != v)
379
+ {
380
+ return 0;
381
+ }
382
+ if (v < -32768.0)
383
+ {
384
+ return -32768;
385
+ }
386
+ if (v > 32767.0)
387
+ {
388
+ return 32767;
389
+ }
390
+ const double r = v + 0.5;
391
+ const int32_t t = (int32_t)r; /* truncates toward zero */
392
+ return (int16_t)(((double)t > r) ? t - 1 : t);
393
+ }
394
+ `
395
+ : '';
396
+ // Include <math.h> when the generated code, or a helper it calls, uses a libm symbol.
397
+ const usesMath = out.needsMath ||
398
+ BOOT_LIBM_USE.test(bootFn) ||
399
+ LIBM_USE.test([
400
+ bootFn,
401
+ stateBlock,
402
+ refDecls,
403
+ vectorBuilderBlock,
404
+ updateBlock,
405
+ handlerDefs,
406
+ queryDefs,
407
+ animCbDefs,
408
+ timerFnDefs,
409
+ mountEffects,
410
+ buildLines,
411
+ ].join('\n'));
412
+ // Each useHostValue gets a public setter that writes its field and refreshes via app_update(), like a JS setter.
413
+ const hostRecords = scalarRecords.filter(scalarRecord => scalarRecord.host);
414
+ const hostSettersBlock = hostRecords
415
+ .map(hostRecord => `void er_app_set_${hostRecord.name}(${cScalarType(hostRecord.cType)} v)\n{\n ` +
416
+ `${hostRecord.cMember} = v;\n` +
417
+ printChangedFlag(hostRecord, ' ')
418
+ .map(line => line + '\n')
419
+ .join('') +
420
+ `${hasUpdate ? ' app_update();\n' : ''}}`)
421
+ .join('\n\n');
422
+ const hostSetterProtos = hostRecords
423
+ .map(hostRecord => `/** @brief Host-fed input '${hostRecord.name}' (useHostValue): set its value and ` +
424
+ `refresh the display. */\nvoid ` +
425
+ `er_app_set_${hostRecord.name}(${cScalarType(hostRecord.cType)} v);`)
426
+ .join('\n\n');
427
+ // File-local helpers (clock readers, JS-exact math), each emitted only when generated code calls it.
428
+ const APP_HELPERS = [
429
+ [
430
+ 'app_perf_now',
431
+ 'static int64_t app_perf_now(void)\n{\n return (int64_t)er_now_ms64();\n}',
432
+ ],
433
+ [
434
+ 'app_date_now',
435
+ 'static int64_t app_date_now(void)\n{\n return s_wall_offset_ms + (int64_t)er_now_ms64();\n}',
436
+ ],
437
+ ...Object.entries(CHECKED_OP).map(([operator, name]) => [
438
+ name,
439
+ `/* a ${operator} b, saturated to the int range: C leaves a signed overflow undefined. */\n` +
440
+ `static int ${name}(int a, int b)\n{\n const int64_t v = (int64_t)a ${operator} b;\n` +
441
+ ' return v > INT_MAX ? INT_MAX : v < INT_MIN ? INT_MIN : (int)v;\n}',
442
+ ]),
443
+ [
444
+ 'app_neg',
445
+ '/* -a, saturated: -INT_MIN does not fit an int. */\n' +
446
+ 'static int app_neg(int a)\n{\n return a == INT_MIN ? INT_MAX : -a;\n}',
447
+ ],
448
+ [
449
+ 'app_mod',
450
+ "/* a % b as JS computes it, kept whole: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
451
+ ' for b == 0, which is 0 here, and INT_MIN % -1 is 0, where C would overflow. */\n' +
452
+ 'static int app_mod(int a, int b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
453
+ ],
454
+ [
455
+ 'app_abs',
456
+ '/* Math.abs of an int, saturated: -INT_MIN does not fit an int. */\n' +
457
+ 'static int app_abs(int v)\n{\n return v >= 0 ? v : v == INT_MIN ? INT_MAX : -v;\n}',
458
+ ],
459
+ [
460
+ 'app_min',
461
+ 'static int app_min(int a, int b)\n{\n return a < b ? a : b;\n}',
462
+ ],
463
+ [
464
+ 'app_max',
465
+ 'static int app_max(int a, int b)\n{\n return a > b ? a : b;\n}',
466
+ ],
467
+ [
468
+ 'app_div',
469
+ '/* a / b as JS computes it, kept whole: truncated toward zero, and saturated where JS gives +-Infinity\n' +
470
+ ' (b == 0) or a result past the int range (INT_MIN / -1). 0 / 0 is NaN, which is 0. */\n' +
471
+ 'static int app_div(int a, int b)\n{\n' +
472
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
473
+ ' if (b == -1)\n {\n return a == INT_MIN ? INT_MAX : -a;\n }\n' +
474
+ ' return a / b;\n}',
475
+ ],
476
+ [
477
+ 'app_floordiv',
478
+ "/* Math.floor(a / b) for two ints, exactly: C's `/` rounds toward zero where floor rounds down, and a float\n" +
479
+ ' quotient would round an operand past 2^24. JS gives +-Infinity for b == 0, which saturates by the sign\n' +
480
+ ' of a (0 / 0 is NaN, which is 0); INT_MIN / -1 saturates too, so the quotient is taken in 64 bits. */\n' +
481
+ 'static int app_floordiv(int a, int b)\n{\n' +
482
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
483
+ ' const int64_t q = (int64_t)a / b;\n' +
484
+ ' const int64_t f = ((int64_t)a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n' +
485
+ ' return f > INT_MAX ? INT_MAX : (int)f;\n}',
486
+ ],
487
+ [
488
+ 'app_ceildiv',
489
+ '/* Math.ceil(a / b) for two ints, exactly, with the zero divisor and INT_MIN / -1 as ' +
490
+ 'app_floordiv has them. */\n' +
491
+ 'static int app_ceildiv(int a, int b)\n{\n' +
492
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
493
+ ' const int64_t q = (int64_t)a / b;\n' +
494
+ ' const int64_t c = ((int64_t)a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n' +
495
+ ' return c > INT_MAX ? INT_MAX : (int)c;\n}',
496
+ ],
497
+ [
498
+ 'app_rounddiv',
499
+ '/* Math.round(a / b) for two ints, exactly: floor(a / b + 1/2), halves up as JS rounds, which is\n' +
500
+ ' floor((2a + b) / 2b) once b is made positive. The zero divisor and the range go as in app_floordiv. */\n' +
501
+ 'static int app_rounddiv(int a, int b)\n{\n' +
502
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
503
+ ' const int64_t n = b < 0 ? -(int64_t)a : a;\n' +
504
+ ' const int64_t d = b < 0 ? -(int64_t)b : b;\n' +
505
+ ' const int64_t num = 2 * n + d, den = 2 * d;\n' +
506
+ ' const int64_t q = num / den;\n' +
507
+ ' const int64_t r = (num % den != 0 && num < 0) ? q - 1 : q;\n' +
508
+ ' return r > INT_MAX ? INT_MAX : r < INT_MIN ? INT_MIN : (int)r;\n}',
509
+ ],
510
+ [
511
+ 'app_f2i',
512
+ '/* A float kept as an int: truncated toward zero like a C cast, but saturated at the int range and NaN as\n' +
513
+ ' 0, where the cast would be undefined behavior. */\n' +
514
+ 'static int app_f2i(float v)\n{\n' +
515
+ ' if (v != v)\n {\n return 0;\n }\n' +
516
+ ' if (v >= 2147483648.0f)\n {\n return INT_MAX;\n }\n' +
517
+ ' if (v <= -2147483648.0f)\n {\n return INT_MIN;\n }\n' +
518
+ ' return (int)v;\n}',
519
+ ],
520
+ [
521
+ 'app_d2i',
522
+ '/* A double kept as an int, as app_f2i keeps a float: for a value worked out at boot, which a float ' +
523
+ 'would round. */\n' +
524
+ 'static int app_d2i(double v)\n{\n' +
525
+ ' if (v != v)\n {\n return 0;\n }\n' +
526
+ ' if (v >= 2147483647.0)\n {\n return INT_MAX;\n }\n' +
527
+ ' if (v <= -2147483648.0)\n {\n return INT_MIN;\n }\n' +
528
+ ' return (int)v;\n}',
529
+ ],
530
+ [
531
+ 'app_roundf',
532
+ "/* Math.round as JS rounds: to the nearest whole number, halves up (toward +Infinity). C's roundf takes\n" +
533
+ ' halves away from zero, which gives -3 for -2.5 where JS gives -2. */\n' +
534
+ 'static float app_roundf(float v)\n{\n' +
535
+ ' const float f = floorf(v);\n return v - f >= 0.5f ? f + 1.0f : f;\n}',
536
+ ],
537
+ [
538
+ 'app_ftoa',
539
+ "/* A float as JS's String() spells it where %g does not: Infinity, -Infinity and NaN for what %g prints as\n" +
540
+ ' inf, -inf and nan, and 0 for negative zero, which %g prints as -0. Anything else is %g, into `buf`,\n' +
541
+ ' which the caller lends (16 chars, room for any float). All ASCII, which every font bakes. */\n' +
542
+ 'static const char* app_ftoa(char* buf, float v)\n{\n' +
543
+ ' if (v != v)\n {\n return "NaN";\n }\n' +
544
+ ' if (isinf(v))\n {\n return v > 0.0f ? "Infinity" : "-Infinity";\n }\n' +
545
+ ' if (v == 0.0f)\n {\n return "0";\n }\n' +
546
+ ' snprintf(buf, 16, "%g", (double)v);\n return buf;\n}',
547
+ ],
548
+ [
549
+ 'app_round',
550
+ '/* Math.round as JS rounds, in double precision for a value worked out at boot: halves up. */\n' +
551
+ 'static double app_round(double v)\n{\n' +
552
+ ' const double f = floor(v);\n return v - f >= 0.5 ? f + 1.0 : f;\n}',
553
+ ],
554
+ [
555
+ 'app_opacity',
556
+ "/* A state-driven opacity as the engine's 0-255 byte: clamped to 0..1 and rounded, as Flow A's bridge and\n" +
557
+ ' the compile-time fold do, with NaN as 0. */\n' +
558
+ 'static uint8_t app_opacity(float v)\n{\n' +
559
+ ' if (!(v > 0.0f))\n {\n return 0;\n }\n' +
560
+ ' if (v >= 1.0f)\n {\n return 255;\n }\n' +
561
+ ' return (uint8_t)(v * 255.0f + 0.5f);\n}',
562
+ ],
563
+ [
564
+ 'app_add64',
565
+ '/* a + b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
566
+ 'static int64_t app_add64(int64_t a, int64_t b)\n{\n' +
567
+ ' if (b > 0 ? a > INT64_MAX - b : a < INT64_MIN - b)\n {\n' +
568
+ ' return b > 0 ? INT64_MAX : INT64_MIN;\n }\n return a + b;\n}',
569
+ ],
570
+ [
571
+ 'app_sub64',
572
+ '/* a - b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
573
+ 'static int64_t app_sub64(int64_t a, int64_t b)\n{\n' +
574
+ ' if (b < 0 ? a > INT64_MAX + b : a < INT64_MIN + b)\n {\n' +
575
+ ' return b < 0 ? INT64_MAX : INT64_MIN;\n }\n return a - b;\n}',
576
+ ],
577
+ [
578
+ 'app_mul64',
579
+ '/* a * b, saturated to the int64 range: C leaves a signed overflow undefined. GCC and Clang test for\n' +
580
+ ' the overflow with a builtin; anywhere else (MSVC) the limits are checked by division first. */\n' +
581
+ 'static int64_t app_mul64(int64_t a, int64_t b)\n{\n' +
582
+ '#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ >= 5)\n' +
583
+ ' int64_t v;\n if (!__builtin_mul_overflow(a, b, &v))\n {\n return v;\n }\n' +
584
+ '#else\n' +
585
+ ' if (a == 0 || b == 0 ||\n' +
586
+ ' (a > 0 ? (b > 0 ? a <= INT64_MAX / b : b >= INT64_MIN / a)\n' +
587
+ ' : (b > 0 ? a >= INT64_MIN / b : a >= INT64_MAX / b)))\n {\n' +
588
+ ' return a * b;\n }\n' +
589
+ '#endif\n' +
590
+ ' return (a < 0) == (b < 0) ? INT64_MAX : INT64_MIN;\n}',
591
+ ],
592
+ [
593
+ 'app_neg64',
594
+ '/* -a, saturated: -INT64_MIN does not fit an int64_t. */\n' +
595
+ 'static int64_t app_neg64(int64_t a)\n{\n return a == INT64_MIN ? INT64_MAX : -a;\n}',
596
+ ],
597
+ [
598
+ 'app_floordiv64',
599
+ "/* Math.floor(a / b) in whole numbers: C's `/` rounds toward zero where floor rounds down. JS gives\n" +
600
+ ' +-Infinity for b == 0, which saturates by the sign of a (0 / 0 is NaN, which is 0), and INT64_MIN / -1\n' +
601
+ ' is past the range, so it saturates too. */\n' +
602
+ 'static int64_t app_floordiv64(int64_t a, int64_t b)\n{\n' +
603
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
604
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
605
+ ' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n}',
606
+ ],
607
+ [
608
+ 'app_ceildiv64',
609
+ '/* Math.ceil(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as ' +
610
+ 'app_floordiv64 has them. */\n' +
611
+ 'static int64_t app_ceildiv64(int64_t a, int64_t b)\n{\n' +
612
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
613
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
614
+ ' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n}',
615
+ ],
616
+ [
617
+ 'app_rounddiv64',
618
+ '/* Math.round(a / b) in whole numbers, halves up as JS rounds: floor(a / b), plus ' +
619
+ 'one when what is left is at\n' +
620
+ ' least half of b. Nothing is doubled, which could overflow; the zero divisor and INT64_MIN / -1 go as in\n' +
621
+ ' app_floordiv64. */\n' +
622
+ 'static int64_t app_rounddiv64(int64_t a, int64_t b)\n{\n' +
623
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
624
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
625
+ ' int64_t q = a / b;\n int64_t r = a % b;\n' +
626
+ ' if (r != 0 && (r < 0) != (b < 0))\n {\n q -= 1;\n r += b;\n }\n' +
627
+ ' return (b > 0 ? r >= b - r : r <= b - r) ? q + 1 : q;\n}',
628
+ ],
629
+ [
630
+ 'app_div64',
631
+ '/* Math.trunc(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as ' +
632
+ 'app_floordiv64 has them. */\n' +
633
+ 'static int64_t app_div64(int64_t a, int64_t b)\n{\n' +
634
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
635
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
636
+ ' return a / b;\n}',
637
+ ],
638
+ [
639
+ 'app_mod64',
640
+ "/* a % b in whole numbers, as JS computes it: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
641
+ ' for b == 0, which is 0 here, and INT64_MIN % -1 is 0, where C would overflow. */\n' +
642
+ 'static int64_t app_mod64(int64_t a, int64_t b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
643
+ ],
644
+ [
645
+ 'app_abs64',
646
+ '/* |v|, saturated: -INT64_MIN does not fit an int64_t. */\n' +
647
+ 'static int64_t app_abs64(int64_t v)\n{\n return v >= 0 ? v : v == INT64_MIN ? INT64_MAX : -v;\n}',
648
+ ],
649
+ [
650
+ 'app_min64',
651
+ 'static int64_t app_min64(int64_t a, int64_t b)\n{\n return a < b ? a : b;\n}',
652
+ ],
653
+ [
654
+ 'app_max64',
655
+ 'static int64_t app_max64(int64_t a, int64_t b)\n{\n return a > b ? a : b;\n}',
656
+ ],
657
+ [
658
+ 'app_delay_ms64',
659
+ '/* A timer delay computed from a timestamp: ToInt32 (wrap to 32 bits), then a negative delay is 0 — the\n' +
660
+ " conversion Flow A's setTimeout applies. */\n" +
661
+ 'static int app_delay_ms64(int64_t v)\n{\n const uint32_t u = (uint32_t)v;\n ' +
662
+ 'return u > 0x7FFFFFFFu ? 0 : (int)u;\n}',
663
+ ],
664
+ [
665
+ 'app_delay_msf',
666
+ '/* A timer delay computed as a float, converted as app_delay_ms64 converts one: ToInt32 (NaN and +-Infinity\n' +
667
+ ' are 0), then a negative delay is 0. Past +-2^63 a float is a multiple of 2^32, ' +
668
+ 'which ToInt32 takes to 0. */\n' +
669
+ 'static int app_delay_msf(float v)\n{\n' +
670
+ ' if (!(v > -9223372036854775808.0f && v < 9223372036854775808.0f))\n {\n return 0;\n }\n' +
671
+ ' const uint32_t u = (uint32_t)(int64_t)v;\n return u > 0x7FFFFFFFu ? 0 : (int)u;\n}',
672
+ ],
673
+ [
674
+ 'app_slice_len',
675
+ '/* The length items.slice(0, end) leaves, as JS counts it: a negative end counts back from the length and\n' +
676
+ ' stops at 0, and an end past the length keeps every item. */\n' +
677
+ 'static int app_slice_len(int len, int end)\n{\n' +
678
+ ' if (end < 0)\n {\n return end <= -len ? 0 : len + end;\n }\n' +
679
+ ' return end < len ? end : len;\n}',
680
+ ],
681
+ [
682
+ 'app_vector_dirty',
683
+ "/* updateVector's damage hint from float math. A NaN or infinite edge (a 0/0 in app math) gives no hint,\n" +
684
+ " so the engine's own damage applies (what changed in the tape, or the whole node), where a zero-width\n" +
685
+ ' one would leave the new drawing unpainted. The rest is rounded out to whole pixels and its edges, not\n' +
686
+ ' its lengths, are bounded well inside the int range, so a rect reaching past the bound is not cut\n' +
687
+ " short; the engine clips the rect's corners from there. */\n" +
688
+ 'static void app_vector_dirty(ERNode* node, float x, float y, float w, float h)\n{\n' +
689
+ ' if (!(isfinite(x) && isfinite(y) && isfinite(w) && isfinite(h)))\n {\n return;\n }\n' +
690
+ ' const float e[4] = {floorf(x), floorf(y), ceilf(x + w), ceilf(y + h)};\n int c[4];\n' +
691
+ ' for (int k = 0; k < 4; k++)\n {\n' +
692
+ ' c[k] = (int)(e[k] < -1e9f ? -1e9f : (e[k] > 1e9f ? 1e9f : e[k]));\n }\n' +
693
+ ' er_node_set_vector_dirty_rect(node, c[0], c[1], c[2] - c[0], c[3] - c[1]);\n}',
694
+ ],
695
+ ];
696
+ // Generated code with literals and comments blanked, so only a real call emits a helper (unused statics warn).
697
+ const helperCallers = stripCLiterals([
698
+ bootFn,
699
+ stateBlock,
700
+ refDecls,
701
+ vectorBuilderBlock,
702
+ updateBlock,
703
+ handlerDefs,
704
+ queryDefs,
705
+ effectFnDefs,
706
+ animCbDefs,
707
+ timerFnDefs,
708
+ mountEffects,
709
+ buildLines,
710
+ ].join('\n'));
711
+ // The clock state, then each helper the generated code calls.
712
+ const clockBlock = [
713
+ '/* Date.now() is the engine clock plus this offset, so it reads as uptime until the host calls\n' +
714
+ ' er_app_set_wall_clock(). performance.now() is the engine clock alone. */\n' +
715
+ 'static int64_t s_wall_offset_ms;' +
716
+ (hasUpdate
717
+ ? '\n/* Set by er_app_set_wall_clock(); the next er_app_tick() re-applies what reads the clock. */\n' +
718
+ 'static int s_wall_clock_changed;'
719
+ : ''),
720
+ ...APP_HELPERS.filter(([name]) => helperCallers.includes(`${name}(`)).map(([, definition]) => definition),
721
+ ].join('\n\n');
722
+ // <limits.h> when a helper saturates at INT_MAX / INT_MIN.
723
+ const usesLimits = /\bINT_M(?:AX|IN)\b/.test(clockBlock);
724
+ // Animation completion waits: their table, and the helpers the generated code calls.
725
+ const animWaitBlock = usesWaits ? printWaitDeclarations(helperCallers) : '';
726
+ // Emit er_timer_clear only when called; a clearInterval in a dropped mount-effect cleanup leaves no caller.
727
+ const timerClearBlock = out.usesTimers && helperCallers.includes('er_timer_clear(')
728
+ ? `static void er_timer_clear(int id)
729
+ {
730
+ if (id < 0)
731
+ {
732
+ return;
733
+ }
734
+ int i = id % ER_AOT_MAX_TIMERS;
735
+ if (s_timers[i].active && s_timers[i].gen == id / ER_AOT_MAX_TIMERS)
736
+ {
737
+ s_timers[i].active = false;
738
+ }
739
+ }`
740
+ : '';
741
+ // The longer pieces of app.gen.c, named here so the template below stays readable.
742
+ const versionMismatch = `embedded-react version mismatch: app.gen.c was generated by ${PKG_VERSION} but the engine header ` +
743
+ `(er_version.h) is a different major.minor. Regenerate the app with 'npm run aot', or align the engine ` +
744
+ `and npm versions.`;
745
+ const mathInclude = usesMath
746
+ ? '#include <math.h>\n' +
747
+ '/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles ' +
748
+ 'under -std=c99 / MSVC. */\n' +
749
+ '#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n'
750
+ : '';
751
+ const limitsInclude = usesLimits ? '#include <limits.h>\n' : '';
752
+ // A blank line sets off each non-empty block before and after.
753
+ const spaced = (block) => (block ? '\n' + block + '\n' : '');
754
+ const keyboard = app.keyboard ? printKeyboard(app.keyboard) : null;
755
+ const declarations = [
756
+ refDecls,
757
+ panDeclBlock,
758
+ effectDeclsBlock,
759
+ vectorBlock,
760
+ vectorBuilderBlock,
761
+ animDecls,
762
+ handleDecls,
763
+ timerTableBlock,
764
+ timerClearBlock,
765
+ animWaitBlock,
766
+ effectFwdDecls,
767
+ updateBlock,
768
+ timerFnFwdDecls,
769
+ animCbDecls,
770
+ handlerDefs,
771
+ queryDefs,
772
+ effectFnDefs,
773
+ animCbDefs,
774
+ timerFnDefs,
775
+ keyboard?.data ?? '',
776
+ ]
777
+ .map(spaced)
778
+ .join('');
779
+ const keyboardSetup = keyboard
780
+ ? keyboard.setup +
781
+ ' /* app-supplied on-screen keyboard layout/appearance */\n'
782
+ : '';
783
+ const initialChanged = watchedRecords.length
784
+ ? ` memset(&${CHANGED_FLAGS}, 1, sizeof(${CHANGED_FLAGS})); /* the first update sets every node */\n`
785
+ : '';
786
+ const initialUpdate = hasUpdate
787
+ ? `\n${initialChanged} app_update(); /* apply initial state-dependent props */\n`
788
+ : '';
789
+ // er_app_fits() asks app_boot() without disturbing the values a built app reads.
790
+ const fitsBody = !hasBoot(app.boot)
791
+ ? [' (void)screen_w;', ' (void)screen_h;', ' return true;']
792
+ : bootDecls
793
+ ? [
794
+ ' const ErAppBoot built = s_boot;',
795
+ ' const bool fits = app_boot(screen_w, screen_h);',
796
+ ' s_boot = built;',
797
+ ' return fits;',
798
+ ]
799
+ : [' return app_boot(screen_w, screen_h);'];
800
+ const fitsFn = 'bool er_app_fits(int screen_w, int screen_h)\n{\n' +
801
+ fitsBody.join('\n') +
802
+ '\n}';
803
+ const bootCall = hasBoot(app.boot)
804
+ ? '\n /* The values that depend on the panel size; a panel the app was not compiled for builds ' +
805
+ 'nothing. */\n' +
806
+ ' if (!app_boot(screen_w, screen_h))\n {\n return false;\n }\n'
807
+ : '';
808
+ // app.gen.c: includes and version pin, then file-scope state, declarations and functions, then er_app_build().
809
+ const body = `/*
810
+ * Generated by the embedded-react Flow B AOT compiler (npm run aot -- ${demo}). DO NOT EDIT.
811
+ * Builds the app's scene graph + state machine directly against er_scene.h — no QuickJS, no JS runtime.
812
+ */
813
+ #include "app.gen.h"
814
+
815
+ #include "er_scene.h"
816
+ #include "er_version.h"
817
+
818
+ #include <stdio.h>
819
+ #include <string.h>
820
+
821
+ /* Every string this file writes goes into a FIXED-SIZE slot (a state buffer, ERProps.text), so an
822
+ over-long value is truncated by design — the app cannot grow the buffer the way JS grows a string.
823
+ GCC's -Wformat-truncation reports exactly that intent for any format combining %s with anything else,
824
+ and ESP-IDF compiles with -Werror, so leaving it on would fail the build for ordinary text like
825
+ {'n=' + name}. Clang does not implement the warning; the guard keeps its "unknown warning group"
826
+ diagnostic from firing there. */
827
+ #if defined(__GNUC__) && !defined(__clang__)
828
+ #pragma GCC diagnostic ignored "-Wformat-truncation"
829
+ #endif
830
+
831
+ /* Version-pin: this file was generated by embedded-react ${PKG_VERSION}. The engine ships LOCKSTEP, so its
832
+ headers must be the same major.minor — otherwise these generated er_scene.h calls may not match the ABI.
833
+ A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
834
+ _Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
835
+ "${versionMismatch}");
836
+ ${mathInclude}${limitsInclude}${dimRoundBlock}\n${clockBlock}\n${stateBlock ? '\n' + stateBlock : ''}${declarations}
837
+ ${appTickFn}
838
+
839
+ void er_app_set_wall_clock(int64_t epoch_ms)
840
+ {
841
+ s_wall_offset_ms = epoch_ms - (int64_t)er_now_ms64();${hasUpdate ? '\n s_wall_clock_changed = 1;' : ''}
842
+ }
843
+ ${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}${bootFn ? '\n' + bootFn + '\n' : ''}
844
+ ${fitsFn}
845
+
846
+ bool er_app_build(int screen_w, int screen_h)
847
+ {
848
+ ERProps p;
849
+ ERNode* ${nodeDecls.join(';\n ERNode* ')};
850
+ ${bootCall}
851
+ /* A screen-sized root the app tree fills (mirrors AppRegistry mounting into a screen-sized host). */
852
+ ERNode* root = er_node_create(ER_NODE_VIEW);
853
+ er_props_default(&p);
854
+ p.width = (int16_t)screen_w;
855
+ p.height = (int16_t)screen_h;
856
+ er_node_set_props(root, &p);
857
+ ${animCreate ? '\n' + animCreate + '\n' : ''}
858
+ ${buildLines}
859
+ er_tree_append_child(root, ${app.root.id});
860
+ er_tree_set_root(root);
861
+ ${keyboardSetup}${initialUpdate}${mountEffectsBlock} return true;
862
+ }
863
+ `;
864
+ // app.gen.h: what the file was generated for, and the app's public entry points.
865
+ const header = `/* Generated by the embedded-react Flow B AOT compiler. DO NOT EDIT. */
866
+ #ifndef ER_APP_GEN_H
867
+ #define ER_APP_GEN_H
868
+
869
+ #include <stdbool.h>
870
+ #include <stdint.h>
871
+
872
+ /*
873
+ * The panel this file was generated at. Values that depend only on the panel size are worked out at boot by
874
+ * er_app_build(), but a branch on \`screen\` that changes the tree was compiled for this panel only, and so
875
+ * was any value the compiler had to know. er_app_build() checks those at boot and builds nothing on a panel
876
+ * that differs in any of them, returning false; er_app_fits() asks the same without building.
877
+ *
878
+ * WHICH demo is recorded the same way, as a marker macro named ER_AOT_DEMO_<demo> with every character
879
+ * outside [A-Za-z0-9] encoded as _<hex>_ (so \`watch-face\` defines ER_AOT_DEMO_watch_2d_face). The encoding
880
+ * is one-to-one, so no two app names can ever share a marker. A board that
881
+ * needs a particular demo's useHostValue setters guards on \`#ifndef\` of its own marker, which names the
882
+ * mismatch instead of leaving a pile of implicit-declaration errors for those setters.
883
+ */
884
+ #define ER_AOT_SCREEN_W ${opts.screen.width}
885
+ #define ER_AOT_SCREEN_H ${opts.screen.height}
886
+ #define ER_AOT_DEMO ${cstr(demo)}
887
+ #define ${demoMarker(demo)} 1
888
+
889
+ /** @brief Builds the AOT-compiled app's scene graph + state machine (call once after backend init).
890
+ * @return false, having built nothing, when the panel does not take the layout this file was compiled
891
+ * for (see er_app_fits()). */
892
+ bool er_app_build(int screen_w, int screen_h);
893
+
894
+ /** @brief Whether a panel of this size takes the layout this file was compiled for. Values that depend only
895
+ * on the panel size are worked out at boot, so any panel that takes the same layout fits; what the
896
+ * compiler had to fold at its own panel (a branch that changes the tree, a font size) must match. */
897
+ bool er_app_fits(int screen_w, int screen_h);
898
+
899
+ /** @brief Advances app timers (setInterval/setTimeout). Call once per frame with the elapsed ms; a no-op
900
+ * for apps that use no timers, so it is always safe to call. */
901
+ void er_app_tick(int dt_ms);
902
+
903
+ /** @brief Tells the app the current time, which Date.now() counts on from. Until it is called Date.now()
904
+ * reads as uptime; a later call re-anchors it, the next er_app_tick() re-applies what reads the
905
+ * clock, and performance.now() never moves with it. Call it from the loop that calls
906
+ * er_app_tick(), before or after er_app_build(); safe whether or not the app reads the clock.
907
+ * @param[in] epoch_ms Current time, in milliseconds since the Unix epoch. */
908
+ void er_app_set_wall_clock(int64_t epoch_ms);
909
+ ${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
910
+ #endif
911
+ `;
912
+ // The image imports the app references; the CLI resolves each path against the demo dir and bakes them.
913
+ return {
914
+ c: body,
915
+ h: header,
916
+ nodes: out.nodeCount,
917
+ state: stateRecords.length,
918
+ handlers: handlers.length,
919
+ updates: updates.length,
920
+ images: app.images,
921
+ };
922
+ }