embedded-react 0.12.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/README.md +222 -6
- package/aot/compile.mjs +3316 -364
- package/aot/style-map.mjs +30 -6
- package/assets/bake-font.mjs +104 -12
- package/assets/bake-svg.mjs +11 -1
- package/assets/build-builtin-font.mjs +6 -12
- package/assets/emit-c.mjs +10 -2
- package/assets/emit-container.mjs +4 -2
- package/assets/font-config.mjs +49 -0
- package/assets/font-sizes.mjs +652 -0
- package/assets/glyph-coverage.mjs +281 -0
- package/assets/index.mjs +29 -5
- package/build.mjs +11 -21
- package/cli.mjs +41 -3
- package/compile-bin.mjs +71 -0
- package/hotreload/pack-app.mjs +8 -21
- package/hotreload/pack-split.mjs +12 -27
- package/pack-container.mjs +10 -47
- package/package.json +2 -1
- package/sim/embedded-react.wasm +0 -0
- package/sim/index.html +32 -3
- package/sim-server.mjs +33 -27
- package/src/embedded-react/Animated.js +23 -9
- package/src/embedded-react/Button.js +98 -0
- package/src/embedded-react/FlatList.js +88 -0
- package/src/embedded-react/ImageBackground.js +67 -0
- package/src/embedded-react/PanResponder.js +326 -0
- package/src/embedded-react/SectionList.js +148 -0
- package/src/embedded-react/TouchableOpacity.js +152 -0
- package/src/embedded-react/components.js +4 -3
- package/src/embedded-react/index.d.ts +867 -60
- package/src/embedded-react/index.js +7 -2
- package/src/embedded-react/list-child.js +54 -0
- package/src/embedded-react/svg-ops.js +309 -77
- package/src/embedded-react/warn-props.js +80 -0
- package/src/host-config.js +103 -3
- package/src/props.js +40 -0
- package/src/renderer.js +31 -0
package/aot/compile.mjs
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
// internal RAM.
|
|
22
22
|
//
|
|
23
23
|
// Supported subset (grows demo by demo; unsupported syntax throws "AOT: ..."):
|
|
24
|
-
// - View / Text / Pressable / Image / ScrollView elements
|
|
24
|
+
// - View / Text / Pressable / TouchableOpacity / Image / ScrollView elements
|
|
25
25
|
// - StyleSheet + inline styles → ERProps (static values)
|
|
26
26
|
// - text with literal + {interpolation} segments (interpolations may reference state)
|
|
27
27
|
// - useState(initial) → C state; on* handlers (onPress/onPressIn/onPressOut/onLongPress) → C functions
|
|
@@ -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,
|
|
@@ -54,11 +57,14 @@ import {
|
|
|
54
57
|
flattenSvg,
|
|
55
58
|
parseColor,
|
|
56
59
|
parsePath,
|
|
60
|
+
KAPPA,
|
|
57
61
|
PAINT_STRIDE,
|
|
58
62
|
GRAD_MAX_STOPS,
|
|
59
63
|
scaleVectorArtifact,
|
|
60
64
|
} from '../src/embedded-react/svg-ops.js';
|
|
61
65
|
import {bakeAssets} from '../assets/index.mjs';
|
|
66
|
+
import {warnMissingGlyphs} from '../assets/glyph-coverage.mjs';
|
|
67
|
+
import {analyzeFontSizes, warnFontSizes} from '../assets/font-sizes.mjs';
|
|
62
68
|
|
|
63
69
|
const here = dirname(fileURLToPath(import.meta.url)); // bridges/quickjs/js/aot
|
|
64
70
|
const repoRoot = resolve(here, '../../../..');
|
|
@@ -100,6 +106,15 @@ const [PKG_MAJOR, PKG_MINOR] = PKG_VERSION.split('.');
|
|
|
100
106
|
// DEEPEST node that failed pins the location; compileSource formats it at the top.
|
|
101
107
|
// ---------------------------------------------------------------------------------------------------
|
|
102
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
|
+
|
|
103
118
|
/** Throws an AOT error carrying an optional `hint` (a "rewrite it like this" suggestion shown to the user). */
|
|
104
119
|
function aotError(message, hint) {
|
|
105
120
|
const e = new Error(message.startsWith('AOT:') ? message : `AOT: ${message}`);
|
|
@@ -128,7 +143,8 @@ function withLoc(fn) {
|
|
|
128
143
|
};
|
|
129
144
|
}
|
|
130
145
|
|
|
131
|
-
/** Re-throws an AOT error with `file:line:col`, a code-frame,
|
|
146
|
+
/** Re-throws an AOT error with `file:line:col`, a code-frame, any hint, and the screen size this build
|
|
147
|
+
* folded its layout at — all folded into the message. */
|
|
132
148
|
function formatAotError(e, src, filename) {
|
|
133
149
|
if (!e || !e.aotLoc) return e; // nothing to locate — leave the bare message
|
|
134
150
|
const {line, column} = e.aotLoc;
|
|
@@ -140,8 +156,16 @@ function formatAotError(e, src, filename) {
|
|
|
140
156
|
/* code-frame is best-effort */
|
|
141
157
|
}
|
|
142
158
|
const hint = e.aotHint ? `\n\nhint: ${e.aotHint}` : '';
|
|
159
|
+
// A responsive app folds its layout from `screen`, so the size baked into THIS build decides which
|
|
160
|
+
// branch the compiler walks. Compile at the wrong one and the error points at whatever unsupported
|
|
161
|
+
// thing the unintended branch happens to hold, with nothing on screen tying it back to the size.
|
|
162
|
+
const screen = SCREEN_FROM_ENV
|
|
163
|
+
? `\n\nscreen: ${SCREEN_W}×${SCREEN_H} (from ER_AOT_SCREEN_W/H).`
|
|
164
|
+
: `\n\nscreen: ${SCREEN_W}×${SCREEN_H} — ER_AOT_SCREEN_W/H did not supply both dimensions, so the ` +
|
|
165
|
+
`default filled in. A responsive app picks its layout from \`screen\`, so this may be compiling a ` +
|
|
166
|
+
`branch meant for another board.`;
|
|
143
167
|
const out = new Error(
|
|
144
|
-
`${e.message}\n at ${filename}:${line}:${column + 1}\n\n${frame}${hint}`,
|
|
168
|
+
`${e.message}\n at ${filename}:${line}:${column + 1}\n\n${frame}${hint}${screen}`,
|
|
145
169
|
);
|
|
146
170
|
out.aotLoc = e.aotLoc;
|
|
147
171
|
if (e.aotHint) out.aotHint = e.aotHint;
|
|
@@ -278,16 +302,336 @@ function evalStatic(node, scope) {
|
|
|
278
302
|
const ARITH = new Set(['+', '-', '*', '/', '%']);
|
|
279
303
|
const COMPARE = new Set(['<', '>', '<=', '>=', '==', '!=', '===', '!==']);
|
|
280
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
|
+
|
|
281
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};
|
|
282
628
|
switch (node.type) {
|
|
283
629
|
case 'NumericLiteral':
|
|
284
|
-
return
|
|
285
|
-
? {code: String(node.value), cType: 'int'}
|
|
286
|
-
: {code: `${node.value}f`, cType: 'float'};
|
|
630
|
+
return numConst(node.value);
|
|
287
631
|
case 'StringLiteral':
|
|
288
632
|
return {code: cstr(node.value), cType: 'string'};
|
|
289
633
|
case 'BooleanLiteral':
|
|
290
|
-
return {code: node.value ? '1' : '0', cType: 'int'};
|
|
634
|
+
return {code: node.value ? '1' : '0', cType: 'int', isBool: true};
|
|
291
635
|
case 'Identifier': {
|
|
292
636
|
if (env.locals.has(node.name)) return env.locals.get(node.name);
|
|
293
637
|
if (env.state.has(node.name)) {
|
|
@@ -296,38 +640,101 @@ function emitExprImpl(node, env) {
|
|
|
296
640
|
throw new Error(
|
|
297
641
|
`AOT: a list state ("${node.name}") can only be used via .length or .map`,
|
|
298
642
|
);
|
|
299
|
-
return {code: s.cMember, cType: s.cType};
|
|
643
|
+
return {code: s.cMember, cType: s.cType, isBool: s.isBool};
|
|
300
644
|
}
|
|
301
645
|
if (node.name in env.consts) {
|
|
302
646
|
const v = env.consts[node.name];
|
|
303
|
-
if (typeof v === 'number')
|
|
304
|
-
return Number.isInteger(v)
|
|
305
|
-
? {code: String(v), cType: 'int'}
|
|
306
|
-
: {code: `${v}f`, cType: 'float'};
|
|
647
|
+
if (typeof v === 'number') return numConst(v);
|
|
307
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};
|
|
308
651
|
}
|
|
309
652
|
throw new Error(
|
|
310
653
|
`AOT: cannot resolve identifier "${node.name}" in a dynamic expression`,
|
|
311
654
|
);
|
|
312
655
|
}
|
|
313
656
|
case 'UnaryExpression': {
|
|
314
|
-
|
|
315
|
-
|
|
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).
|
|
316
677
|
if (
|
|
317
678
|
node.operator === '-' ||
|
|
318
679
|
node.operator === '+' ||
|
|
319
680
|
node.operator === '!'
|
|
320
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.
|
|
321
684
|
return {
|
|
322
|
-
code: `(${node.operator}(${a.code}))`,
|
|
685
|
+
code: `(${node.operator}(${node.operator === '!' ? asCond(a) : a.code}))`,
|
|
323
686
|
cType: node.operator === '!' ? 'int' : a.cType,
|
|
687
|
+
isBool: node.operator === '!',
|
|
324
688
|
};
|
|
325
689
|
throw new Error(`AOT: unsupported unary operator "${node.operator}"`);
|
|
326
690
|
}
|
|
327
691
|
case 'BinaryExpression': {
|
|
328
|
-
|
|
329
|
-
|
|
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);
|
|
330
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);
|
|
331
738
|
if (node.operator === '/')
|
|
332
739
|
return {
|
|
333
740
|
code: `((float)(${l.code}) / (float)(${r.code}))`,
|
|
@@ -335,28 +742,96 @@ function emitExprImpl(node, env) {
|
|
|
335
742
|
};
|
|
336
743
|
const cType =
|
|
337
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
|
+
};
|
|
338
765
|
return {code: `(${l.code} ${node.operator} ${r.code})`, cType};
|
|
339
766
|
}
|
|
340
767
|
if (COMPARE.has(node.operator)) {
|
|
341
|
-
const eqOp =
|
|
342
|
-
node.operator === '===' || node.operator === '=='
|
|
343
|
-
? '=='
|
|
344
|
-
: node.operator === '!==' || node.operator === '!='
|
|
345
|
-
? '!='
|
|
346
|
-
: null;
|
|
347
|
-
// String (in)equality → strcmp; the generated C already includes <string.h>.
|
|
348
|
-
if (eqOp && (l.cType === 'string' || r.cType === 'string'))
|
|
349
|
-
return {
|
|
350
|
-
code: `(strcmp(${l.code}, ${r.code}) ${eqOp} 0)`,
|
|
351
|
-
cType: 'int',
|
|
352
|
-
};
|
|
353
768
|
const op =
|
|
354
769
|
node.operator === '==='
|
|
355
770
|
? '=='
|
|
356
771
|
: node.operator === '!=='
|
|
357
772
|
? '!='
|
|
358
773
|
: node.operator;
|
|
359
|
-
|
|
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
|
+
};
|
|
360
835
|
}
|
|
361
836
|
throw new Error(`AOT: unsupported binary operator "${node.operator}"`);
|
|
362
837
|
}
|
|
@@ -365,32 +840,74 @@ function emitExprImpl(node, env) {
|
|
|
365
840
|
node.operator === '&&' || node.operator === '||' ? node.operator : null;
|
|
366
841
|
if (!op)
|
|
367
842
|
throw new Error(`AOT: unsupported logical operator "${node.operator}"`);
|
|
368
|
-
const l =
|
|
369
|
-
|
|
370
|
-
|
|
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
|
+
};
|
|
371
872
|
}
|
|
372
873
|
case 'ConditionalExpression': {
|
|
373
|
-
const t =
|
|
374
|
-
const c =
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
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'
|
|
379
894
|
: c.cType === a.cType
|
|
380
895
|
? c.cType
|
|
381
896
|
: 'int';
|
|
382
|
-
return {
|
|
897
|
+
return {
|
|
898
|
+
code: `(${asCond(t)} ? ${c.code} : ${a.code})`,
|
|
899
|
+
cType,
|
|
900
|
+
isBool: Boolean(c.isBool && a.isBool),
|
|
901
|
+
};
|
|
383
902
|
}
|
|
384
903
|
case 'MemberExpression': {
|
|
385
904
|
// Static fold: member access that resolves to a compile-time constant (e.g. a .map item's `.key`).
|
|
386
905
|
try {
|
|
387
|
-
const v = evalStatic(node, env.consts ?? {});
|
|
388
|
-
if (typeof v === 'number')
|
|
389
|
-
return Number.isInteger(v)
|
|
390
|
-
? {code: String(v), cType: 'int'}
|
|
391
|
-
: {code: `${v}f`, cType: 'float'};
|
|
906
|
+
const v = evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
907
|
+
if (typeof v === 'number') return numConst(v);
|
|
392
908
|
if (typeof v === 'string') return {code: cstr(v), cType: 'string'};
|
|
393
|
-
if (typeof v === 'boolean')
|
|
909
|
+
if (typeof v === 'boolean')
|
|
910
|
+
return {code: v ? '1' : '0', cType: 'int', isBool: true};
|
|
394
911
|
} catch {
|
|
395
912
|
/* not static — fall through to the dynamic member forms below */
|
|
396
913
|
}
|
|
@@ -426,6 +943,7 @@ function emitExprImpl(node, env) {
|
|
|
426
943
|
prop === 'current'
|
|
427
944
|
) {
|
|
428
945
|
const r = env.refs.get(obj.name);
|
|
946
|
+
r.used = true;
|
|
429
947
|
return {code: r.cVar, cType: r.cType};
|
|
430
948
|
}
|
|
431
949
|
// `<event>.x / .y / .dx / .dy` — touch fields of the handler's EREventData.
|
|
@@ -436,6 +954,19 @@ function emitExprImpl(node, env) {
|
|
|
436
954
|
) {
|
|
437
955
|
return {code: `data->${prop}`, cType: 'int'};
|
|
438
956
|
}
|
|
957
|
+
// `<event>.vx / .vy` — how fast the finger was going (px/ms) at the last measured move. The engine
|
|
958
|
+
// measures it; a Flow B handler could not, having neither a clock nor the previous point.
|
|
959
|
+
if (
|
|
960
|
+
obj.type === 'Identifier' &&
|
|
961
|
+
env.event === obj.name &&
|
|
962
|
+
(prop === 'vx' || prop === 'vy')
|
|
963
|
+
) {
|
|
964
|
+
return {code: `data->${prop}`, cType: 'float'};
|
|
965
|
+
}
|
|
966
|
+
// `<gestureState>.…` — the second argument of a PanResponder callback (see emitPanResponder).
|
|
967
|
+
if (obj.type === 'Identifier' && env.gesture === obj.name && prop) {
|
|
968
|
+
return panGestureField(prop, env.pan);
|
|
969
|
+
}
|
|
439
970
|
// `<event>.layout.x / .y / .width / .height` — the onLayout rect (EREventData.layout_rect; ERRect uses w/h).
|
|
440
971
|
if (
|
|
441
972
|
obj.type === 'MemberExpression' &&
|
|
@@ -456,30 +987,80 @@ function emitExprImpl(node, env) {
|
|
|
456
987
|
return {code: '(float)M_PI', cType: 'float'};
|
|
457
988
|
throw aotError(
|
|
458
989
|
'AOT: unsupported member expression in a dynamic context',
|
|
459
|
-
'in a handler or dynamic expression you can read state, `ref.current`, a `.map` item field, event fields (e.x / e.y / e.dx / e.dy / e.layout.*), and Math.PI — other member access must be a compile-time constant.',
|
|
990
|
+
'in a handler or dynamic expression you can read state, `ref.current`, a `.map` item field, event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.layout.*), and Math.PI — other member access must be a compile-time constant.',
|
|
460
991
|
);
|
|
461
992
|
}
|
|
462
993
|
case 'CallExpression': {
|
|
463
|
-
// Math.* helpers → libm (the generated C includes <math.h> when these appear).
|
|
464
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).
|
|
465
1018
|
if (c.type === 'MemberExpression' && c.object.name === 'Math') {
|
|
466
1019
|
const fn = c.property.name;
|
|
467
|
-
const
|
|
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'};
|
|
468
1045
|
const UNARY = {
|
|
469
1046
|
sin: 'sinf',
|
|
470
1047
|
cos: 'cosf',
|
|
471
1048
|
tan: 'tanf',
|
|
472
1049
|
sqrt: 'sqrtf',
|
|
473
1050
|
abs: 'fabsf',
|
|
474
|
-
round: '
|
|
1051
|
+
round: 'app_roundf',
|
|
475
1052
|
floor: 'floorf',
|
|
476
1053
|
ceil: 'ceilf',
|
|
477
1054
|
};
|
|
478
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'};
|
|
479
1060
|
const inner = `${UNARY[fn]}((float)(${a[0].code}))`;
|
|
480
|
-
// round/floor/ceil yield a whole number
|
|
481
|
-
return
|
|
482
|
-
? {code: `(
|
|
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'}
|
|
483
1064
|
: {code: inner, cType: 'float'};
|
|
484
1065
|
}
|
|
485
1066
|
const BINARY = {
|
|
@@ -499,15 +1080,67 @@ function emitExprImpl(node, env) {
|
|
|
499
1080
|
'AOT: unsupported call expression in a dynamic expression',
|
|
500
1081
|
);
|
|
501
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;
|
|
502
1091
|
}
|
|
503
1092
|
throw new Error(
|
|
504
1093
|
`AOT: unsupported expression "${node.type}" in a dynamic context`,
|
|
505
1094
|
);
|
|
506
1095
|
}
|
|
507
|
-
|
|
1096
|
+
/** emitExpr for the destinations that can hold a 64-bit timestamp: state, refs, locals, text, conditions. */
|
|
1097
|
+
const emitExprWide = withLoc(emitExprImpl);
|
|
508
1098
|
|
|
509
|
-
|
|
510
|
-
|
|
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
|
+
}
|
|
1114
|
+
|
|
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
|
+
);
|
|
511
1144
|
const cTypeOfValue = v =>
|
|
512
1145
|
typeof v === 'string'
|
|
513
1146
|
? 'string'
|
|
@@ -515,6 +1148,140 @@ const cTypeOfValue = v =>
|
|
|
515
1148
|
? 'float'
|
|
516
1149
|
: 'int';
|
|
517
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
|
+
|
|
518
1285
|
// ---------------------------------------------------------------------------------------------------
|
|
519
1286
|
// AST helpers + collection passes — small predicates (isFn, fnReturnsJSX, …) and the up-front scans
|
|
520
1287
|
// that walk the component body ONCE to gather what later emission needs: the module scope, useState,
|
|
@@ -545,6 +1312,34 @@ function findComponent(program) {
|
|
|
545
1312
|
// e.g. ER_AOT_SCREEN_W=240 ER_AOT_SCREEN_H=320 for the CYD; defaults to a wide 800×480.
|
|
546
1313
|
const SCREEN_W = Number(process.env.ER_AOT_SCREEN_W) || 800;
|
|
547
1314
|
const SCREEN_H = Number(process.env.ER_AOT_SCREEN_H) || 480;
|
|
1315
|
+
// Whether BOTH dimensions above came from the environment. A blank or unparsable override falls back to
|
|
1316
|
+
// the default for that axis alone, so this asks what was actually used, not whether the vars are set.
|
|
1317
|
+
const SCREEN_FROM_ENV =
|
|
1318
|
+
Number(process.env.ER_AOT_SCREEN_W) > 0 &&
|
|
1319
|
+
Number(process.env.ER_AOT_SCREEN_H) > 0;
|
|
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
|
+
}
|
|
548
1343
|
|
|
549
1344
|
function moduleScope(program, screen, seed = {}) {
|
|
550
1345
|
// `seed` pre-populates the scope (e.g. image imports as their asset-name strings) BEFORE module consts are
|
|
@@ -562,7 +1357,7 @@ function moduleScope(program, screen, seed = {}) {
|
|
|
562
1357
|
)
|
|
563
1358
|
continue;
|
|
564
1359
|
try {
|
|
565
|
-
scope[decl.id.name] = evalStatic(decl.init, scope);
|
|
1360
|
+
scope[decl.id.name] = evalStatic(decl.init, withUndefined(scope));
|
|
566
1361
|
} catch {
|
|
567
1362
|
/* not a static const — skip */
|
|
568
1363
|
}
|
|
@@ -616,7 +1411,7 @@ function inferItemStruct(items, name) {
|
|
|
616
1411
|
* lookup keys stay the bare JS names (`count`), but the C field / array / count derive from `cField`
|
|
617
1412
|
* (`<prefix>count`). prefix='' (the App) leaves storage names exactly as the JS names — backward compatible.
|
|
618
1413
|
*/
|
|
619
|
-
function collectState(fnBody, scope, prefix = '') {
|
|
1414
|
+
function collectState(fnBody, scope, prefix = '', wide = NO_WIDE) {
|
|
620
1415
|
const byName = new Map();
|
|
621
1416
|
const bySetter = new Map();
|
|
622
1417
|
for (const stmt of fnBody.body) {
|
|
@@ -685,7 +1480,24 @@ function collectState(fnBody, scope, prefix = '') {
|
|
|
685
1480
|
`AOT: useHostValue("${name}") must be a number — its initial value evaluated to ${JSON.stringify(initVal)}`,
|
|
686
1481
|
'useHostValue(0) / useHostValue(0.0) — the host feeds an int or float; booleans, strings, and objects are not supported.',
|
|
687
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
|
+
}
|
|
688
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';
|
|
689
1501
|
// A numeric literal written with a decimal point or exponent (e.g. useState(70.0)) forces a FLOAT
|
|
690
1502
|
// slot even though the value is integral — lets the state hold sub-integer values (a smooth drag)
|
|
691
1503
|
// while the UI shows Math.round(value). (70.0 === 70 in JS, so we read the raw source to tell them apart.)
|
|
@@ -697,19 +1509,24 @@ function collectState(fnBody, scope, prefix = '') {
|
|
|
697
1509
|
) {
|
|
698
1510
|
cType = 'float';
|
|
699
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';
|
|
700
1514
|
// String scalar → a fixed char buffer in ErAppState; setters snprintf into it (see scalarAssign).
|
|
701
1515
|
const initCode =
|
|
702
1516
|
cType === 'string'
|
|
703
1517
|
? cstr(String(initVal))
|
|
704
1518
|
: cType === 'float'
|
|
705
1519
|
? floatLit(initVal)
|
|
706
|
-
:
|
|
1520
|
+
: cType === 'i64'
|
|
1521
|
+
? i64Lit(Number(initVal))
|
|
1522
|
+
: String(Number(initVal));
|
|
707
1523
|
rec = {
|
|
708
1524
|
name,
|
|
709
1525
|
cField,
|
|
710
1526
|
setter,
|
|
711
1527
|
kind: 'scalar',
|
|
712
1528
|
cType,
|
|
1529
|
+
isBool,
|
|
713
1530
|
cMember: `s_state.${cField}`,
|
|
714
1531
|
initCode,
|
|
715
1532
|
host: isHost, // host-fed → also emit a public er_app_set_<name>() setter
|
|
@@ -906,9 +1723,8 @@ export async function bakeSvgArtifacts(src, baseDir) {
|
|
|
906
1723
|
}).program;
|
|
907
1724
|
const imports = collectSvgImports(program);
|
|
908
1725
|
if (imports.size === 0) return {};
|
|
909
|
-
const {svgToVector, svgToRaster, writeRasterPng} =
|
|
910
|
-
'../assets/bake-svg.mjs'
|
|
911
|
-
);
|
|
1726
|
+
const {svgToVector, svgToRaster, writeRasterPng} =
|
|
1727
|
+
await import('../assets/bake-svg.mjs');
|
|
912
1728
|
const artifacts = {};
|
|
913
1729
|
for (const [, imp] of imports) {
|
|
914
1730
|
const p = resolve(baseDir, imp.importPath);
|
|
@@ -1053,8 +1869,23 @@ function collectAnims(fnBody, scope, prefix = '') {
|
|
|
1053
1869
|
decl.id.type === 'Identifier'
|
|
1054
1870
|
) {
|
|
1055
1871
|
const initVal = init.arguments[0]
|
|
1056
|
-
?
|
|
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
|
+
)
|
|
1057
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
|
+
}
|
|
1058
1889
|
anims.set(decl.id.name, {
|
|
1059
1890
|
cVar: `s_av_${prefix}${decl.id.name}`,
|
|
1060
1891
|
initCode: floatLit(initVal),
|
|
@@ -1072,7 +1903,7 @@ function collectAnims(fnBody, scope, prefix = '') {
|
|
|
1072
1903
|
* - NODE ref (`useRef()` / `useRef(null)`): holds an `ERNode*`, captured by `ref={r}` on an element and
|
|
1073
1904
|
* used as the target of imperative calls like updateVector(r, …). kind === 'node'.
|
|
1074
1905
|
*/
|
|
1075
|
-
function collectRefs(fnBody, scope, prefix = '') {
|
|
1906
|
+
function collectRefs(fnBody, scope, prefix = '', wide = NO_WIDE) {
|
|
1076
1907
|
const refs = new Map();
|
|
1077
1908
|
if (fnBody.type !== 'BlockStatement') return refs;
|
|
1078
1909
|
for (const stmt of fnBody.body) {
|
|
@@ -1084,28 +1915,50 @@ function collectRefs(fnBody, scope, prefix = '') {
|
|
|
1084
1915
|
init.callee.name === 'useRef' &&
|
|
1085
1916
|
decl.id.type === 'Identifier'
|
|
1086
1917
|
) {
|
|
1087
|
-
const cVar = `s_ref_${prefix}${decl.id.name}`;
|
|
1088
1918
|
const arg = init.arguments[0];
|
|
1919
|
+
if (isPanCreate(arg)) continue; // a PanResponder ref — collectPanResponders owns it
|
|
1920
|
+
const cVar = `s_ref_${prefix}${decl.id.name}`;
|
|
1089
1921
|
if (!arg || arg.type === 'NullLiteral') {
|
|
1090
1922
|
refs.set(decl.id.name, {
|
|
1091
1923
|
cVar,
|
|
1092
1924
|
cType: 'ERNode*',
|
|
1093
1925
|
initCode: 'NULL',
|
|
1094
1926
|
kind: 'node',
|
|
1927
|
+
used: false,
|
|
1095
1928
|
});
|
|
1096
1929
|
continue;
|
|
1097
1930
|
}
|
|
1098
|
-
const v =
|
|
1099
|
-
|
|
1100
|
-
|
|
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(
|
|
1101
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)}.`,
|
|
1102
1941
|
);
|
|
1103
|
-
|
|
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';
|
|
1104
1951
|
refs.set(decl.id.name, {
|
|
1105
1952
|
cVar,
|
|
1106
1953
|
cType,
|
|
1107
|
-
initCode:
|
|
1954
|
+
initCode:
|
|
1955
|
+
cType === 'float'
|
|
1956
|
+
? floatLit(v)
|
|
1957
|
+
: cType === 'i64'
|
|
1958
|
+
? i64Lit(v)
|
|
1959
|
+
: String(v),
|
|
1108
1960
|
kind: 'value',
|
|
1961
|
+
used: false,
|
|
1109
1962
|
});
|
|
1110
1963
|
}
|
|
1111
1964
|
}
|
|
@@ -1141,7 +1994,25 @@ const ANIM_TRANSFORM_PROPS = {
|
|
|
1141
1994
|
/** Formats a number as a valid C float literal (`1` → `1.0f`, not `1f` which doesn't compile). */
|
|
1142
1995
|
function floatLit(n) {
|
|
1143
1996
|
const v = Number(n);
|
|
1144
|
-
|
|
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`;
|
|
1145
2016
|
}
|
|
1146
2017
|
|
|
1147
2018
|
/** The polynomial family of an `Easing.quad` / `Easing.cubic` node, for in/out/inOut composition. */
|
|
@@ -1278,12 +2149,12 @@ function argbLiteral(value) {
|
|
|
1278
2149
|
function emitColorExpr(node, env) {
|
|
1279
2150
|
if (node.type === 'StringLiteral') return colorLiteral(node.value);
|
|
1280
2151
|
if (node.type === 'ConditionalExpression') {
|
|
1281
|
-
const t = emitExpr(node.test, env)
|
|
2152
|
+
const t = asCond(emitExpr(node.test, env));
|
|
1282
2153
|
return `((${t}) ? ${emitColorExpr(node.consequent, env)} : ${emitColorExpr(node.alternate, env)})`;
|
|
1283
2154
|
}
|
|
1284
2155
|
// A statically-resolvable color (a const string, or a theme token like `theme.card`) folds to a literal.
|
|
1285
2156
|
try {
|
|
1286
|
-
const s = evalStatic(node, env.consts ?? {});
|
|
2157
|
+
const s = evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
1287
2158
|
if (typeof s === 'string') return colorLiteral(s);
|
|
1288
2159
|
} catch {
|
|
1289
2160
|
/* not static — fall through to the error below */
|
|
@@ -1306,12 +2177,12 @@ function emitEnumExpr(node, table, env) {
|
|
|
1306
2177
|
return c;
|
|
1307
2178
|
}
|
|
1308
2179
|
if (node.type === 'ConditionalExpression') {
|
|
1309
|
-
const t = emitExpr(node.test, env)
|
|
2180
|
+
const t = asCond(emitExpr(node.test, env));
|
|
1310
2181
|
return `((${t}) ? ${emitEnumExpr(node.consequent, table, env)} : ${emitEnumExpr(node.alternate, table, env)})`;
|
|
1311
2182
|
}
|
|
1312
2183
|
// A statically resolvable enum (a const string) folds to its constant.
|
|
1313
2184
|
try {
|
|
1314
|
-
const s = evalStatic(node, env.consts ?? {});
|
|
2185
|
+
const s = evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
1315
2186
|
if (typeof s === 'string' && table[s]) return table[s];
|
|
1316
2187
|
} catch {
|
|
1317
2188
|
/* not static — fall through */
|
|
@@ -1322,9 +2193,41 @@ function emitEnumExpr(node, table, env) {
|
|
|
1322
2193
|
);
|
|
1323
2194
|
}
|
|
1324
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
|
+
|
|
1325
2223
|
/** Lowers one dynamic inline-style value to ERProps field assignment(s) (C expressions). */
|
|
1326
2224
|
function lowerDynamicStyleValue(key, valueNode, env) {
|
|
1327
|
-
|
|
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);
|
|
1328
2231
|
if (!meta)
|
|
1329
2232
|
throw aotError(
|
|
1330
2233
|
`AOT: a state-driven value for style "${key}" is not supported (static only)`,
|
|
@@ -1332,22 +2235,42 @@ function lowerDynamicStyleValue(key, valueNode, env) {
|
|
|
1332
2235
|
);
|
|
1333
2236
|
if (meta.kind === 'color')
|
|
1334
2237
|
return [{field: meta.field, code: emitColorExpr(valueNode, env)}];
|
|
1335
|
-
if (meta.kind === 'opacity')
|
|
1336
|
-
return [
|
|
1337
|
-
{
|
|
1338
|
-
field: meta.field,
|
|
1339
|
-
code: `(uint8_t)((${emitExpr(valueNode, env).code}) * 255.0f)`,
|
|
1340
|
-
},
|
|
1341
|
-
];
|
|
1342
2238
|
if (meta.kind === 'enum')
|
|
1343
2239
|
return [
|
|
1344
2240
|
{field: meta.field, code: emitEnumExpr(valueNode, meta.table, env)},
|
|
1345
2241
|
];
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
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 */
|
|
1349
2255
|
}
|
|
1350
2256
|
|
|
2257
|
+
/**
|
|
2258
|
+
* Whether a style already writes `field`, counting its percentage twin: `width: '50%'` lowers to
|
|
2259
|
+
* `width_pct`, and the author has still set the width. Used by the components that fall back to a
|
|
2260
|
+
* built-in size or inset when the style leaves one out — without the twin they inject a pixel default
|
|
2261
|
+
* ALONGSIDE the percentage, and the engine prefers the pixel value for a size.
|
|
2262
|
+
*
|
|
2263
|
+
* @param {{field: string}[]} staticAssigns Static field writes from collectStyleAssigns().
|
|
2264
|
+
* @param {{field: string}[]} dynAssigns State-driven field writes from collectStyleAssigns().
|
|
2265
|
+
* @param {string} field ERProps field to look for.
|
|
2266
|
+
*/
|
|
2267
|
+
const styleWrites = (staticAssigns, dynAssigns, field) =>
|
|
2268
|
+
[field, `${field}_pct`].some(
|
|
2269
|
+
f =>
|
|
2270
|
+
staticAssigns.some(a => a.field === f) ||
|
|
2271
|
+
dynAssigns.some(a => a.field === f),
|
|
2272
|
+
);
|
|
2273
|
+
|
|
1351
2274
|
/**
|
|
1352
2275
|
* Collects an element's merged style into static field assigns and dynamic (state-driven) field assigns.
|
|
1353
2276
|
* Inline object values are tried statically first; a value that references state becomes a dynAssign.
|
|
@@ -1378,6 +2301,8 @@ function collectStyleAssigns(openingElement, scope, env) {
|
|
|
1378
2301
|
return null;
|
|
1379
2302
|
};
|
|
1380
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;
|
|
1381
2306
|
if (expr.type === 'ArrayExpression') {
|
|
1382
2307
|
for (const e of expr.elements) if (e) apply(e);
|
|
1383
2308
|
return;
|
|
@@ -1391,6 +2316,9 @@ function collectStyleAssigns(openingElement, scope, env) {
|
|
|
1391
2316
|
const key = prop.computed
|
|
1392
2317
|
? evalStatic(prop.key, scope)
|
|
1393
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;
|
|
1394
2322
|
|
|
1395
2323
|
// Animated value bound directly to a prop (opacity / backgroundColor / color), optionally through
|
|
1396
2324
|
// an .interpolate({ inputRange, outputRange }) mapping.
|
|
@@ -1431,19 +2359,35 @@ function collectStyleAssigns(openingElement, scope, env) {
|
|
|
1431
2359
|
if (handled) continue;
|
|
1432
2360
|
}
|
|
1433
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;
|
|
1434
2366
|
try {
|
|
1435
|
-
|
|
1436
|
-
fields.set(a.field, {dynamic: false, code: a.expr});
|
|
2367
|
+
staticValue = {v: evalStatic(prop.value, withUndefined(scope))};
|
|
1437
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 {
|
|
1438
2375
|
for (const a of lowerDynamicStyleValue(key, prop.value, env))
|
|
1439
2376
|
fields.set(a.field, {dynamic: true, code: a.code});
|
|
1440
2377
|
}
|
|
1441
2378
|
}
|
|
1442
2379
|
return;
|
|
1443
2380
|
}
|
|
1444
|
-
// A StyleSheet reference / identifier resolving to a static style object.
|
|
1445
|
-
|
|
1446
|
-
|
|
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
|
+
}
|
|
1447
2391
|
};
|
|
1448
2392
|
for (const attr of openingElement.attributes) {
|
|
1449
2393
|
if (attr.type !== 'JSXAttribute' || attr.name.name !== 'style') continue;
|
|
@@ -1489,18 +2433,11 @@ function buildText(children, scope, env) {
|
|
|
1489
2433
|
format += t.replace(/%/g, '%%');
|
|
1490
2434
|
} else if (child.type === 'JSXExpressionContainer') {
|
|
1491
2435
|
if (child.expression.type === 'JSXEmptyExpression') continue;
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
);
|
|
1498
|
-
} catch {
|
|
1499
|
-
const e = emitExpr(child.expression, env); // references state → dynamic
|
|
1500
|
-
format += printfSpec(e.cType);
|
|
1501
|
-
args.push(e.code);
|
|
1502
|
-
dynamic = true;
|
|
1503
|
-
}
|
|
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;
|
|
1504
2441
|
} else if (child.type === 'JSXElement') {
|
|
1505
2442
|
throw new Error(
|
|
1506
2443
|
'AOT: nested <Text> / element children inside <Text> not yet supported (spans)',
|
|
@@ -1536,7 +2473,7 @@ function staticTextContent(children, scope) {
|
|
|
1536
2473
|
c.expression.type !== 'JSXEmptyExpression'
|
|
1537
2474
|
) {
|
|
1538
2475
|
const v = evalStatic(c.expression, scope); // throws if it references state
|
|
1539
|
-
|
|
2476
|
+
s += jsxChildText(v);
|
|
1540
2477
|
} else if (c.type === 'JSXElement')
|
|
1541
2478
|
throw aotError(
|
|
1542
2479
|
'AOT: a nested <Text> span may not itself contain another <Text> (one level of spans only)',
|
|
@@ -1584,7 +2521,8 @@ function collectTextSpans(children, scope, env) {
|
|
|
1584
2521
|
'spans must be static; keep dynamic text in its own single <Text> (no nested <Text> siblings).',
|
|
1585
2522
|
);
|
|
1586
2523
|
}
|
|
1587
|
-
|
|
2524
|
+
// React draws nothing for null, undefined, or a boolean child.
|
|
2525
|
+
if (v !== undefined && v !== null && typeof v !== 'boolean')
|
|
1588
2526
|
spans.push(inheritSpan(cstr(String(v))));
|
|
1589
2527
|
} else if (
|
|
1590
2528
|
c.type === 'JSXElement' &&
|
|
@@ -1652,36 +2590,49 @@ function compileListOp(rec, arg, env) {
|
|
|
1652
2590
|
for (const f of struct.fields) {
|
|
1653
2591
|
const valNode = props.get(f.key);
|
|
1654
2592
|
if (!valNode) continue;
|
|
1655
|
-
const e = emitExpr(valNode, env);
|
|
1656
2593
|
if (f.kind === 'string')
|
|
1657
2594
|
lines.push(
|
|
1658
|
-
` snprintf(${arr}[${cnt}].${f.key}, sizeof(${arr}[${cnt}].${f.key}),
|
|
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)};`,
|
|
1659
2600
|
);
|
|
1660
|
-
else lines.push(` ${arr}[${cnt}].${f.key} = ${e.code};`);
|
|
1661
2601
|
}
|
|
1662
2602
|
lines.push(` ${cnt}++;`, ' }');
|
|
1663
2603
|
}
|
|
1664
2604
|
return lines;
|
|
1665
2605
|
}
|
|
1666
|
-
// setItems(items.slice(0,
|
|
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.
|
|
1667
2608
|
if (
|
|
1668
2609
|
arg.type === 'CallExpression' &&
|
|
1669
2610
|
arg.callee.type === 'MemberExpression' &&
|
|
1670
2611
|
arg.callee.object.name === rec.name &&
|
|
1671
2612
|
arg.callee.property.name === 'slice'
|
|
1672
2613
|
) {
|
|
1673
|
-
const end = arg.arguments
|
|
1674
|
-
if (
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
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
|
+
];
|
|
1682
2633
|
}
|
|
1683
2634
|
throw new Error(
|
|
1684
|
-
`AOT: unsupported list operation on "${rec.name}" (use [...${rec.name}, item], ${rec.name}.slice(0,
|
|
2635
|
+
`AOT: unsupported list operation on "${rec.name}" (use [...${rec.name}, item], ${rec.name}.slice(0, n), or [])`,
|
|
1685
2636
|
);
|
|
1686
2637
|
}
|
|
1687
2638
|
|
|
@@ -1932,7 +2883,7 @@ function emitCompletionCb(fnNode, env, state, ctx) {
|
|
|
1932
2883
|
: [{type: 'ExpressionStatement', expression: body}];
|
|
1933
2884
|
const cctx = {stateChanged: false, animIdx: 0, out: ctx.out};
|
|
1934
2885
|
const lines = compileStmts(list, {...env, locals}, state, cctx, ' ');
|
|
1935
|
-
if (cctx.stateChanged) lines.push(
|
|
2886
|
+
if (cctx.stateChanged) lines.push(APP_UPDATE_CALL);
|
|
1936
2887
|
ctx.out.animCbs.push({name, body: lines});
|
|
1937
2888
|
return name;
|
|
1938
2889
|
}
|
|
@@ -1975,7 +2926,7 @@ function compileAnimateStart(expr, env, state, ctx) {
|
|
|
1975
2926
|
function evalStaticOr(node, env, dflt) {
|
|
1976
2927
|
if (!node) return dflt;
|
|
1977
2928
|
try {
|
|
1978
|
-
return evalStatic(node, env.consts ?? {});
|
|
2929
|
+
return evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
1979
2930
|
} catch {
|
|
1980
2931
|
return dflt;
|
|
1981
2932
|
}
|
|
@@ -1986,11 +2937,78 @@ function blockList(node) {
|
|
|
1986
2937
|
return node.type === 'BlockStatement' ? node.body : [node];
|
|
1987
2938
|
}
|
|
1988
2939
|
|
|
1989
|
-
/**
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
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)});`;
|
|
1994
3012
|
}
|
|
1995
3013
|
|
|
1996
3014
|
/** True if `node` is a `<ref>.current` member access on a known value ref. */
|
|
@@ -2002,15 +3020,19 @@ function refTarget(node, env) {
|
|
|
2002
3020
|
node.property.name === 'current' &&
|
|
2003
3021
|
env.refs?.has(node.object.name)
|
|
2004
3022
|
) {
|
|
2005
|
-
|
|
3023
|
+
const r = env.refs.get(node.object.name);
|
|
3024
|
+
r.used = true;
|
|
3025
|
+
return r;
|
|
2006
3026
|
}
|
|
2007
3027
|
return null;
|
|
2008
3028
|
}
|
|
2009
3029
|
|
|
2010
|
-
/** An imperative updateVector shape `{ arc:[…]|circle:[…]|rect:[
|
|
2011
|
-
* → { entries (op-tape C exprs),
|
|
2012
|
-
* event fields (emitExpr); paint must be static.
|
|
2013
|
-
|
|
3030
|
+
/** An imperative updateVector shape `{ arc:[…]|circle:[…]|rect:[x,y,w,h,rx?,ry?]|line:[…]|path:'…', fill, … }`
|
|
3031
|
+
* → { entries (op-tape C exprs), locals (C declarations to emit ahead of them), paint (static 7-num
|
|
3032
|
+
* record) }. Geometry coords may reference state/refs/event fields (emitExpr); paint must be static.
|
|
3033
|
+
* Shares the ...EntriesC geometry with the JSX path. `tag` names any locals and must be unique in the
|
|
3034
|
+
* handler block the caller writes them into. */
|
|
3035
|
+
function imperativeShape(shapeNode, env, tag) {
|
|
2014
3036
|
if (shapeNode?.type !== 'ObjectExpression')
|
|
2015
3037
|
throw new Error('AOT: each updateVector shape must be an object literal');
|
|
2016
3038
|
const props = {};
|
|
@@ -2028,14 +3050,18 @@ function imperativeShape(shapeNode, env) {
|
|
|
2028
3050
|
.slice(0, n)
|
|
2029
3051
|
.map(el => `(float)(${emitExpr(el, env).code})`);
|
|
2030
3052
|
};
|
|
2031
|
-
let
|
|
2032
|
-
if (props.arc)
|
|
2033
|
-
else if (props.circle)
|
|
2034
|
-
else if (props.rect)
|
|
2035
|
-
|
|
3053
|
+
let geo;
|
|
3054
|
+
if (props.arc) geo = geometryOf(arcEntriesC(...arr('arc', 5)));
|
|
3055
|
+
else if (props.circle) geo = geometryOf(circleEntriesC(...arr('circle', 3)));
|
|
3056
|
+
else if (props.rect) {
|
|
3057
|
+
// Destructured rather than spread: the radii are optional, so a 4-element literal must not slide
|
|
3058
|
+
// `tag` into rx's slot.
|
|
3059
|
+
const [x, y, w, h, rx = null, ry = null] = arr('rect', 6);
|
|
3060
|
+
geo = geometryOf(rectEntriesC(x, y, w, h, rx, ry, tag));
|
|
3061
|
+
} else if (props.line) geo = geometryOf(lineEntriesC(...arr('line', 4)));
|
|
2036
3062
|
else if (props.path)
|
|
2037
|
-
|
|
2038
|
-
floatLit,
|
|
3063
|
+
geo = geometryOf(
|
|
3064
|
+
parsePath(String(evalStatic(props.path, env.consts ?? {}))).map(floatLit),
|
|
2039
3065
|
);
|
|
2040
3066
|
else
|
|
2041
3067
|
throw new Error(
|
|
@@ -2058,7 +3084,7 @@ function imperativeShape(shapeNode, env) {
|
|
|
2058
3084
|
JOIN_MAP[stat('join', 'miter')] ?? 0,
|
|
2059
3085
|
stat('fillRule', 'nonzero') === 'evenodd' ? 1 : 0,
|
|
2060
3086
|
];
|
|
2061
|
-
return {
|
|
3087
|
+
return {...geo, paint};
|
|
2062
3088
|
}
|
|
2063
3089
|
|
|
2064
3090
|
/** Lowers `updateVector(nodeRef, shapes, [x,y,w,h]?)` to: fill a mutable op-tape, push it to the node, and
|
|
@@ -2071,25 +3097,37 @@ function compileUpdateVector(expr, env, ctx, indent) {
|
|
|
2071
3097
|
throw new Error(
|
|
2072
3098
|
'AOT: updateVector(ref, …) first arg must be a node ref (const r = useRef())',
|
|
2073
3099
|
);
|
|
3100
|
+
ref.used = true;
|
|
2074
3101
|
if (shapesArg?.type !== 'ArrayExpression')
|
|
2075
3102
|
throw new Error(
|
|
2076
3103
|
'AOT: updateVector(ref, shapes, …) shapes must be an array literal',
|
|
2077
3104
|
);
|
|
3105
|
+
// Claimed before the shape loop so a shape's locals can carry it: two updateVector calls can land in
|
|
3106
|
+
// the same handler block, where a name keyed only on the shape index would collide.
|
|
3107
|
+
const id = out.svgN++;
|
|
2078
3108
|
const entries = [];
|
|
3109
|
+
const decls = [];
|
|
2079
3110
|
const paints = [];
|
|
2080
3111
|
for (const s of shapesArg.elements) {
|
|
2081
|
-
const {
|
|
3112
|
+
const {
|
|
3113
|
+
entries: e,
|
|
3114
|
+
locals,
|
|
3115
|
+
paint,
|
|
3116
|
+
} = imperativeShape(s, env, `uv${id}_${paints.length}`);
|
|
3117
|
+
decls.push(...locals);
|
|
2082
3118
|
entries.push('ER_VOP_SHAPE', floatLit(paints.length), ...e);
|
|
2083
3119
|
paints.push(paint);
|
|
2084
3120
|
}
|
|
2085
|
-
const id = out.svgN++;
|
|
2086
3121
|
const len = entries.length;
|
|
2087
3122
|
out.needsMath = true;
|
|
2088
3123
|
out.vectorData.push(`static float s_uv${id}_ops[${len}];`);
|
|
2089
3124
|
out.vectorData.push(
|
|
2090
3125
|
`static const ERVectorPaint s_uv${id}_paints[] = {\n${paints.map(p => ' ' + emitVectorPaint(p)).join(',\n')}\n};`,
|
|
2091
3126
|
);
|
|
2092
|
-
const lines =
|
|
3127
|
+
const lines = [
|
|
3128
|
+
...decls.map(d => `${indent}${d}`),
|
|
3129
|
+
...entries.map((e, i) => `${indent}s_uv${id}_ops[${i}] = ${e};`),
|
|
3130
|
+
];
|
|
2093
3131
|
lines.push(
|
|
2094
3132
|
`${indent}er_node_set_vector_ops(${ref.cVar}, s_uv${id}_ops, ${len}, s_uv${id}_paints, ${paints.length}, NULL, 0);`,
|
|
2095
3133
|
);
|
|
@@ -2098,9 +3136,16 @@ function compileUpdateVector(expr, env, ctx, indent) {
|
|
|
2098
3136
|
throw new Error(
|
|
2099
3137
|
'AOT: updateVector dirtyRect must be a [x, y, w, h] array literal',
|
|
2100
3138
|
);
|
|
2101
|
-
const
|
|
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';
|
|
2102
3147
|
lines.push(
|
|
2103
|
-
`${indent}
|
|
3148
|
+
`${indent}${fn}(${ref.cVar}, ${rect.map(e => e.code).join(', ')});`,
|
|
2104
3149
|
);
|
|
2105
3150
|
}
|
|
2106
3151
|
return lines;
|
|
@@ -2115,7 +3160,16 @@ function compileTimerAdd(expr, env, state, ctx) {
|
|
|
2115
3160
|
'AOT: a setInterval/setTimeout callback must be an inline function',
|
|
2116
3161
|
'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).',
|
|
2117
3162
|
);
|
|
2118
|
-
|
|
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;
|
|
2119
3173
|
const repeat = expr.callee.name === 'setInterval';
|
|
2120
3174
|
const slot = ctx.out.timerFns.length;
|
|
2121
3175
|
const name = `er_timer_fn_${slot}`;
|
|
@@ -2142,8 +3196,13 @@ function inlineHelperCall(name, fn, args, env, state, ctx, indent) {
|
|
|
2142
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.',
|
|
2143
3197
|
);
|
|
2144
3198
|
if (args[i]) {
|
|
2145
|
-
const e =
|
|
2146
|
-
locals.set(p.name, {
|
|
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
|
+
});
|
|
2147
3206
|
}
|
|
2148
3207
|
});
|
|
2149
3208
|
const body = fn.body;
|
|
@@ -2151,10 +3210,18 @@ function inlineHelperCall(name, fn, args, env, state, ctx, indent) {
|
|
|
2151
3210
|
body.type === 'BlockStatement'
|
|
2152
3211
|
? body.body
|
|
2153
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;
|
|
2154
3217
|
ctx.inlining.add(name);
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
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
|
+
}
|
|
2158
3225
|
}
|
|
2159
3226
|
|
|
2160
3227
|
function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
@@ -2182,7 +3249,7 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
|
2182
3249
|
expr.callee.name === 'clearTimeout')
|
|
2183
3250
|
) {
|
|
2184
3251
|
return [
|
|
2185
|
-
`${indent}er_timer_clear(${emitExpr(expr.arguments[0], env)
|
|
3252
|
+
`${indent}er_timer_clear(${asInt(emitExpr(expr.arguments[0], env))});`,
|
|
2186
3253
|
];
|
|
2187
3254
|
}
|
|
2188
3255
|
// `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
|
|
@@ -2192,17 +3259,80 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
|
2192
3259
|
throw new Error(
|
|
2193
3260
|
'AOT: the only assignment allowed in a handler is `ref.current = ...`',
|
|
2194
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;`];
|
|
2195
3321
|
return [
|
|
2196
|
-
`${indent}${r.cVar} ${expr.operator} ${
|
|
3322
|
+
`${indent}${r.cVar} ${expr.operator} ${expr.operator === '=' ? storeCode(e, r.cType) : e.code};`,
|
|
2197
3323
|
];
|
|
2198
3324
|
}
|
|
2199
|
-
// `ref.current++` / `ref.current
|
|
3325
|
+
// `ref.current++` / `ref.current--`; a whole-number ref steps through the checked `+ 1` / `- 1`.
|
|
2200
3326
|
if (expr.type === 'UpdateExpression') {
|
|
2201
3327
|
const r = refTarget(expr.argument, env);
|
|
2202
3328
|
if (!r)
|
|
2203
3329
|
throw new Error(
|
|
2204
3330
|
'AOT: the only ++/-- allowed in a handler is on `ref.current`',
|
|
2205
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
|
+
];
|
|
2206
3336
|
return [`${indent}${r.cVar}${expr.operator};`];
|
|
2207
3337
|
}
|
|
2208
3338
|
// Animated.*(…).start() — single timing/spring/decay OR a sequence/parallel/stagger/delay/loop
|
|
@@ -2254,20 +3384,23 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
|
2254
3384
|
throw new Error(
|
|
2255
3385
|
'AOT: updater function must be a single expression (for now)',
|
|
2256
3386
|
);
|
|
2257
|
-
return [scalarAssign(rec,
|
|
3387
|
+
return [scalarAssign(rec, arg.body, {...env, locals}, indent)];
|
|
2258
3388
|
}
|
|
2259
|
-
return [scalarAssign(rec,
|
|
3389
|
+
return [scalarAssign(rec, arg, env, indent)];
|
|
2260
3390
|
}
|
|
2261
3391
|
const compileHandlerExpr = withLoc(compileHandlerExprImpl);
|
|
2262
3392
|
|
|
2263
3393
|
/**
|
|
2264
3394
|
* Compiles a list of handler statements to C lines. Supports: `const x = expr` (a C local, visible to
|
|
2265
3395
|
* later statements), `if (cond) {...} else {...}`, state setters, and Animated.*(...).start(). `ctx`
|
|
2266
|
-
* accumulates `stateChanged` (→ trailing app_update)
|
|
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.
|
|
2267
3399
|
*/
|
|
2268
3400
|
function compileStmts(list, env, state, ctx, indent) {
|
|
2269
3401
|
const lines = [];
|
|
2270
|
-
for (
|
|
3402
|
+
for (let si = 0; si < list.length; si++) {
|
|
3403
|
+
const st = list[si];
|
|
2271
3404
|
if (st.type === 'VariableDeclaration') {
|
|
2272
3405
|
for (const decl of st.declarations) {
|
|
2273
3406
|
if (decl.id.type !== 'Identifier')
|
|
@@ -2276,7 +3409,12 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2276
3409
|
);
|
|
2277
3410
|
if (!decl.init)
|
|
2278
3411
|
throw new Error('AOT: a handler local must have an initializer');
|
|
2279
|
-
|
|
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}`;
|
|
2280
3418
|
// `const id = setInterval/setTimeout(…)` → an int timer-id local (so a later clearInterval(id) resolves).
|
|
2281
3419
|
if (
|
|
2282
3420
|
decl.init.type === 'CallExpression' &&
|
|
@@ -2285,8 +3423,9 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2285
3423
|
decl.init.callee.name === 'setTimeout')
|
|
2286
3424
|
) {
|
|
2287
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};`);
|
|
2288
3427
|
lines.push(
|
|
2289
|
-
`${indent}int ${cName} = ${compileTimerAdd(decl.init, env, state, ctx)};`,
|
|
3428
|
+
`${indent}${hoist ? '' : 'int '}${cName} = ${compileTimerAdd(decl.init, env, state, ctx)};`,
|
|
2290
3429
|
`${indent}(void)${cName};`,
|
|
2291
3430
|
);
|
|
2292
3431
|
env = {
|
|
@@ -2298,28 +3437,79 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2298
3437
|
};
|
|
2299
3438
|
continue;
|
|
2300
3439
|
}
|
|
2301
|
-
const e =
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
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
|
+
}
|
|
2305
3463
|
env = {
|
|
2306
3464
|
...env,
|
|
2307
3465
|
locals: new Map(env.locals).set(decl.id.name, {
|
|
2308
3466
|
code: cName,
|
|
2309
3467
|
cType: e.cType,
|
|
3468
|
+
isBool: e.isBool,
|
|
2310
3469
|
}),
|
|
2311
3470
|
};
|
|
2312
3471
|
}
|
|
2313
3472
|
continue;
|
|
2314
3473
|
}
|
|
2315
|
-
//
|
|
2316
|
-
//
|
|
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.
|
|
2317
3479
|
if (st.type === 'ReturnStatement') {
|
|
2318
|
-
if (ctx.allowReturn)
|
|
2319
|
-
|
|
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;
|
|
2320
3507
|
}
|
|
2321
3508
|
if (st.type === 'IfStatement') {
|
|
2322
|
-
lines.push(
|
|
3509
|
+
lines.push(
|
|
3510
|
+
`${indent}if (${asCond(emitExprWide(st.test, env))})`,
|
|
3511
|
+
`${indent}{`,
|
|
3512
|
+
);
|
|
2323
3513
|
lines.push(
|
|
2324
3514
|
...compileStmts(
|
|
2325
3515
|
blockList(st.consequent),
|
|
@@ -2348,7 +3538,7 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2348
3538
|
if (st.type !== 'ExpressionStatement')
|
|
2349
3539
|
throw aotError(
|
|
2350
3540
|
`AOT: unsupported statement "${st.type}" in event handler`,
|
|
2351
|
-
'a handler supports only `const x = …` locals, `if (…) { … } else { … }`, and expression statements (setters / ref writes / updateVector / Animated…start). Loops (for/while), switch
|
|
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.',
|
|
2352
3542
|
);
|
|
2353
3543
|
lines.push(...compileHandlerExpr(st.expression, env, state, ctx, indent));
|
|
2354
3544
|
}
|
|
@@ -2362,6 +3552,7 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2362
3552
|
* then again from app_update whenever a SCALAR dep changes (compared against a stored prev). The body is
|
|
2363
3553
|
* compiled WITHOUT a trailing app_update — it runs INSIDE app_update / at mount, so re-applying state it
|
|
2364
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.
|
|
2365
3556
|
*/
|
|
2366
3557
|
function compileEffect(eff, env, state, out) {
|
|
2367
3558
|
const body = eff.fn.body;
|
|
@@ -2373,10 +3564,26 @@ function compileEffect(eff, env, state, out) {
|
|
|
2373
3564
|
!eff.deps ||
|
|
2374
3565
|
(eff.deps.type === 'ArrayExpression' && eff.deps.elements.length === 0);
|
|
2375
3566
|
if (isMount) {
|
|
2376
|
-
const ctx = {
|
|
3567
|
+
const ctx = {
|
|
3568
|
+
stateChanged: false,
|
|
3569
|
+
animIdx: 0,
|
|
3570
|
+
out,
|
|
3571
|
+
allowReturn: true,
|
|
3572
|
+
bodyList: stmts,
|
|
3573
|
+
};
|
|
2377
3574
|
const lines = compileStmts(stmts, env, state, ctx, ' ');
|
|
2378
|
-
if (ctx.
|
|
2379
|
-
|
|
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);
|
|
2380
3587
|
return;
|
|
2381
3588
|
}
|
|
2382
3589
|
if (eff.deps.type !== 'ArrayExpression')
|
|
@@ -2388,25 +3595,67 @@ function compileEffect(eff, env, state, out) {
|
|
|
2388
3595
|
const name = `er_effect_${id}`;
|
|
2389
3596
|
const deps = eff.deps.elements.map(d => {
|
|
2390
3597
|
if (!d) throw aotError('AOT: a useEffect dependency must be an expression');
|
|
2391
|
-
const e =
|
|
2392
|
-
if (
|
|
3598
|
+
const e = emitExprWide(d, env);
|
|
3599
|
+
if (!['int', 'float', 'i64', 'string'].includes(e.cType))
|
|
2393
3600
|
throw aotError(
|
|
2394
3601
|
'AOT: useEffect dependencies must be scalar (number / bool / string)',
|
|
2395
3602
|
'depend on scalar state values; object/array dependencies are not yet supported.',
|
|
2396
3603
|
);
|
|
2397
3604
|
return e;
|
|
2398
3605
|
});
|
|
2399
|
-
|
|
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, ' ');
|
|
2400
3640
|
out.effectFns.push({
|
|
2401
3641
|
name,
|
|
2402
|
-
body:
|
|
3642
|
+
body: hasCleanup
|
|
3643
|
+
? [
|
|
3644
|
+
` if (${armed})`,
|
|
3645
|
+
' {',
|
|
3646
|
+
` ${armed} = 0;`,
|
|
3647
|
+
` ${name}_cleanup();`,
|
|
3648
|
+
' }',
|
|
3649
|
+
...bodyLines,
|
|
3650
|
+
]
|
|
3651
|
+
: bodyLines,
|
|
2403
3652
|
});
|
|
2404
3653
|
// A static "previous value" per dep; snapshot at mount, then app_update detects changes against it.
|
|
2405
3654
|
deps.forEach((d, j) =>
|
|
2406
3655
|
out.effectDecls.push(
|
|
2407
3656
|
d.cType === 'string'
|
|
2408
3657
|
? `static char s_eff${id}_d${j}[${LIST_STR_CAP}];`
|
|
2409
|
-
: `static ${d.cType
|
|
3658
|
+
: `static ${cScalarType(d.cType)} s_eff${id}_d${j};`,
|
|
2410
3659
|
),
|
|
2411
3660
|
);
|
|
2412
3661
|
const snap = (j, d) =>
|
|
@@ -2424,30 +3673,379 @@ function compileEffect(eff, env, state, out) {
|
|
|
2424
3673
|
` if (strcmp(s_eff${id}_d${j}, ${d.code}) != 0) { ${snap(j, d)}; er_changed = 1; }`,
|
|
2425
3674
|
);
|
|
2426
3675
|
else {
|
|
2427
|
-
const t = d.cType
|
|
3676
|
+
const t = cScalarType(d.cType);
|
|
2428
3677
|
check.push(
|
|
2429
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; }`,
|
|
2430
3679
|
);
|
|
2431
3680
|
}
|
|
2432
|
-
});
|
|
2433
|
-
check.push(` if (er_changed) ${name}();`, ' }');
|
|
2434
|
-
out.depEffects.push(check.join('\n'));
|
|
3681
|
+
});
|
|
3682
|
+
check.push(` if (er_changed) ${name}();`, ' }');
|
|
3683
|
+
out.depEffects.push(check.join('\n'));
|
|
3684
|
+
}
|
|
3685
|
+
|
|
3686
|
+
function compileHandler(fnNode, env, state, out, pan = null) {
|
|
3687
|
+
const body = fnNode.body;
|
|
3688
|
+
const list =
|
|
3689
|
+
body.type === 'BlockStatement'
|
|
3690
|
+
? body.body
|
|
3691
|
+
: [{type: 'ExpressionStatement', expression: body}];
|
|
3692
|
+
// The handler's first parameter is the event; `<event>.x/.y/.dx/.dy/.vx/.vy` map to EREventData fields.
|
|
3693
|
+
// A PanResponder callback takes a second one, RN's gestureState — see panGestureField.
|
|
3694
|
+
const eventParam =
|
|
3695
|
+
fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
|
|
3696
|
+
const gestureParam =
|
|
3697
|
+
pan && fnNode.params[1]?.type === 'Identifier'
|
|
3698
|
+
? fnNode.params[1].name
|
|
3699
|
+
: null;
|
|
3700
|
+
let henv = env;
|
|
3701
|
+
if (eventParam) henv = {...henv, event: eventParam};
|
|
3702
|
+
if (gestureParam) henv = {...henv, gesture: gestureParam, pan};
|
|
3703
|
+
const ctx = {stateChanged: false, animIdx: 0, out};
|
|
3704
|
+
const stmts = compileStmts(list, henv, state, ctx, ' ');
|
|
3705
|
+
if (ctx.stateChanged) stmts.push(APP_UPDATE_CALL); // re-apply state-dependent props once
|
|
3706
|
+
return stmts;
|
|
3707
|
+
}
|
|
3708
|
+
|
|
3709
|
+
// ---------------------------------------------------------------------------------------------------
|
|
3710
|
+
// PanResponder (Flow B) — LOWERED onto the engine's responder system, not transpiled.
|
|
3711
|
+
//
|
|
3712
|
+
// RN's PanResponder is a JS state machine over raw touches. The engine already has that machine, in C:
|
|
3713
|
+
// capture/bubble negotiation (er_responder_query_set) picks an owner, and GRANT / MOVE / RELEASE /
|
|
3714
|
+
// TERMINATE then fire on the owner alone, carrying cumulative travel and velocity. So the should-set
|
|
3715
|
+
// predicates become QUERIES and the callbacks become responder EVENT handlers — no gesture math is
|
|
3716
|
+
// duplicated into the generated C, and the app gets real arbitration for free (a granted pan owns the
|
|
3717
|
+
// gesture, so a ScrollView ancestor cannot auto-scroll out from under it).
|
|
3718
|
+
//
|
|
3719
|
+
// The one thing with no engine counterpart is RN's anchor: `g.dx` is measured from the GRANT, while the
|
|
3720
|
+
// engine's `data->dx` runs from touch-down — a claim that needed 10 px of slop would otherwise open with
|
|
3721
|
+
// a 10 px jump. That anchor, plus `x0`/`y0`, is a handful of file-scope ints per responder.
|
|
3722
|
+
// ---------------------------------------------------------------------------------------------------
|
|
3723
|
+
|
|
3724
|
+
/** RN PanResponder config key → the engine responder QUERY it lowers to. */
|
|
3725
|
+
const PAN_QUERIES = {
|
|
3726
|
+
onStartShouldSetPanResponder: 'ER_QUERY_START_SHOULD_SET',
|
|
3727
|
+
onStartShouldSetPanResponderCapture: 'ER_QUERY_START_SHOULD_SET_CAPTURE',
|
|
3728
|
+
onMoveShouldSetPanResponder: 'ER_QUERY_MOVE_SHOULD_SET',
|
|
3729
|
+
onMoveShouldSetPanResponderCapture: 'ER_QUERY_MOVE_SHOULD_SET_CAPTURE',
|
|
3730
|
+
onPanResponderTerminationRequest: 'ER_QUERY_TERMINATION_REQUEST',
|
|
3731
|
+
};
|
|
3732
|
+
|
|
3733
|
+
/** Query constant → the suffix of the C function emitted for it. */
|
|
3734
|
+
const PAN_QUERY_SUFFIX = {
|
|
3735
|
+
ER_QUERY_START_SHOULD_SET: 'start_should_set',
|
|
3736
|
+
ER_QUERY_START_SHOULD_SET_CAPTURE: 'start_should_set_capture',
|
|
3737
|
+
ER_QUERY_MOVE_SHOULD_SET: 'move_should_set',
|
|
3738
|
+
ER_QUERY_MOVE_SHOULD_SET_CAPTURE: 'move_should_set_capture',
|
|
3739
|
+
ER_QUERY_TERMINATION_REQUEST: 'termination_request',
|
|
3740
|
+
};
|
|
3741
|
+
|
|
3742
|
+
/** RN PanResponder config key → the engine responder EVENT it lowers to. */
|
|
3743
|
+
const PAN_EVENTS = {
|
|
3744
|
+
onPanResponderGrant: 'ER_EVENT_RESPONDER_GRANT',
|
|
3745
|
+
onPanResponderMove: 'ER_EVENT_RESPONDER_MOVE',
|
|
3746
|
+
onPanResponderRelease: 'ER_EVENT_RESPONDER_RELEASE',
|
|
3747
|
+
onPanResponderTerminate: 'ER_EVENT_RESPONDER_TERMINATE',
|
|
3748
|
+
onPanResponderReject: 'ER_EVENT_RESPONDER_REJECT',
|
|
3749
|
+
};
|
|
3750
|
+
|
|
3751
|
+
/** Config keys the Flow A module acts on that have no Flow B lowering — rejected by name, not ignored. */
|
|
3752
|
+
const PAN_FLOW_A_ONLY = {
|
|
3753
|
+
onPanResponderStart:
|
|
3754
|
+
'it reports EXTRA fingers joining a gesture already in flight; Flow B lowers one gesture per responder.',
|
|
3755
|
+
onPanResponderEnd:
|
|
3756
|
+
'it reports a finger lifting while others stay down; Flow B lowers one gesture per responder.',
|
|
3757
|
+
};
|
|
3758
|
+
|
|
3759
|
+
/** True for a `PanResponder.create({…})` call. */
|
|
3760
|
+
const isPanCreate = n =>
|
|
3761
|
+
n?.type === 'CallExpression' &&
|
|
3762
|
+
n.callee.type === 'MemberExpression' &&
|
|
3763
|
+
!n.callee.computed &&
|
|
3764
|
+
n.callee.object.type === 'Identifier' &&
|
|
3765
|
+
n.callee.object.name === 'PanResponder' &&
|
|
3766
|
+
n.callee.property.name === 'create';
|
|
3767
|
+
|
|
3768
|
+
/**
|
|
3769
|
+
* One `gestureState` field → the C expression that reads it. Travel is rebased onto the grant (RN's
|
|
3770
|
+
* anchor); the point and the velocity come straight off the engine payload; the finger count is the
|
|
3771
|
+
* engine's own, which is why er_touch_active_count() exists.
|
|
3772
|
+
*/
|
|
3773
|
+
function panGestureField(prop, pan) {
|
|
3774
|
+
switch (prop) {
|
|
3775
|
+
case 'dx':
|
|
3776
|
+
return {code: `(data->dx - ${pan.cPrefix}_base_dx)`, cType: 'int'};
|
|
3777
|
+
case 'dy':
|
|
3778
|
+
return {code: `(data->dy - ${pan.cPrefix}_base_dy)`, cType: 'int'};
|
|
3779
|
+
case 'moveX':
|
|
3780
|
+
return {code: 'data->x', cType: 'int'};
|
|
3781
|
+
case 'moveY':
|
|
3782
|
+
return {code: 'data->y', cType: 'int'};
|
|
3783
|
+
case 'x0':
|
|
3784
|
+
return {code: `${pan.cPrefix}_x0`, cType: 'int'};
|
|
3785
|
+
case 'y0':
|
|
3786
|
+
return {code: `${pan.cPrefix}_y0`, cType: 'int'};
|
|
3787
|
+
case 'vx':
|
|
3788
|
+
case 'vy':
|
|
3789
|
+
return {code: `data->${prop}`, cType: 'float'};
|
|
3790
|
+
case 'numberActiveTouches':
|
|
3791
|
+
return {code: 'er_touch_active_count()', cType: 'int'};
|
|
3792
|
+
case 'stateID':
|
|
3793
|
+
return {code: String(pan.stateID), cType: 'int'};
|
|
3794
|
+
}
|
|
3795
|
+
throw aotError(
|
|
3796
|
+
`AOT: unknown gestureState field "${prop}" in a PanResponder callback`,
|
|
3797
|
+
'a gestureState carries dx / dy / moveX / moveY / x0 / y0 / vx / vy / numberActiveTouches / stateID.',
|
|
3798
|
+
);
|
|
3799
|
+
}
|
|
3800
|
+
|
|
3801
|
+
/** Validates one `PanResponder.create({…})` config and builds the descriptor the emitter works from. */
|
|
3802
|
+
function buildPanDescriptor(name, createCall, prefix) {
|
|
3803
|
+
const cfg = createCall.arguments[0];
|
|
3804
|
+
if (!cfg || cfg.type !== 'ObjectExpression')
|
|
3805
|
+
throw aotError(
|
|
3806
|
+
'AOT: PanResponder.create(...) needs an object literal of callbacks',
|
|
3807
|
+
'write the config inline — `PanResponder.create({ onStartShouldSetPanResponder: () => true, … })` — so the AOT can see which callbacks exist at compile time.',
|
|
3808
|
+
);
|
|
3809
|
+
const queries = new Map();
|
|
3810
|
+
const events = new Map();
|
|
3811
|
+
for (const prop of cfg.properties) {
|
|
3812
|
+
if (prop.type !== 'ObjectProperty' && prop.type !== 'ObjectMethod')
|
|
3813
|
+
throw aotError(
|
|
3814
|
+
'AOT: a spread inside PanResponder.create({…}) is not supported',
|
|
3815
|
+
'list the callbacks explicitly.',
|
|
3816
|
+
);
|
|
3817
|
+
if (prop.computed)
|
|
3818
|
+
throw aotError(
|
|
3819
|
+
'AOT: a computed key in PanResponder.create({…}) is not supported',
|
|
3820
|
+
'name each callback literally — the AOT decides at compile time which engine query or event a key becomes.',
|
|
3821
|
+
);
|
|
3822
|
+
const key = prop.key.name ?? prop.key.value;
|
|
3823
|
+
// A shorthand method (`onPanResponderMove(e, g) { … }`) IS the function node; a property holds it.
|
|
3824
|
+
const fn = prop.type === 'ObjectMethod' ? prop : prop.value;
|
|
3825
|
+
if (PAN_FLOW_A_ONLY[key])
|
|
3826
|
+
throw aotError(
|
|
3827
|
+
`AOT: PanResponder "${key}" is not supported in Flow B`,
|
|
3828
|
+
`${PAN_FLOW_A_ONLY[key]} Use onPanResponderGrant / Release / Terminate instead, or build this screen for Flow A.`,
|
|
3829
|
+
);
|
|
3830
|
+
const query = PAN_QUERIES[key];
|
|
3831
|
+
const event = PAN_EVENTS[key];
|
|
3832
|
+
if (!query && !event)
|
|
3833
|
+
throw aotError(
|
|
3834
|
+
`AOT: unknown PanResponder config key "${key}"`,
|
|
3835
|
+
`supported: ${[...Object.keys(PAN_QUERIES), ...Object.keys(PAN_EVENTS)].join(', ')}.`,
|
|
3836
|
+
);
|
|
3837
|
+
if (prop.type !== 'ObjectMethod' && !isFn(fn))
|
|
3838
|
+
throw aotError(
|
|
3839
|
+
`AOT: PanResponder "${key}" must be a function`,
|
|
3840
|
+
'pass an inline arrow — `(e, g) => …` — so it can be compiled into the generated C.',
|
|
3841
|
+
);
|
|
3842
|
+
if (query) queries.set(query, fn);
|
|
3843
|
+
else events.set(event, fn);
|
|
3844
|
+
}
|
|
3845
|
+
return {
|
|
3846
|
+
name,
|
|
3847
|
+
cPrefix: `s_pan_${prefix}${name}`,
|
|
3848
|
+
fnPrefix: `er_pan_${prefix}${name}`,
|
|
3849
|
+
stateID: 0, // assigned when the responder is first wired to a node
|
|
3850
|
+
queries,
|
|
3851
|
+
events,
|
|
3852
|
+
emitted: null,
|
|
3853
|
+
};
|
|
3854
|
+
}
|
|
3855
|
+
|
|
3856
|
+
/**
|
|
3857
|
+
* Collects `const pan = useRef(PanResponder.create({…})).current` → Map(name → descriptor). The
|
|
3858
|
+
* `useRef(…)` form (read back as `pan.current.panHandlers`) is accepted too; a bare `create(…)` is not,
|
|
3859
|
+
* because it would re-create the recogniser every render in Flow A and the two flows must agree.
|
|
3860
|
+
*/
|
|
3861
|
+
function collectPanResponders(fnBody, prefix = '') {
|
|
3862
|
+
const pans = new Map();
|
|
3863
|
+
if (fnBody.type !== 'BlockStatement') return pans;
|
|
3864
|
+
for (const stmt of fnBody.body) {
|
|
3865
|
+
if (stmt.type !== 'VariableDeclaration') continue;
|
|
3866
|
+
for (const decl of stmt.declarations) {
|
|
3867
|
+
const init = decl.init;
|
|
3868
|
+
if (decl.id.type !== 'Identifier' || !init) continue;
|
|
3869
|
+
const viaCurrent =
|
|
3870
|
+
init.type === 'MemberExpression' &&
|
|
3871
|
+
!init.computed &&
|
|
3872
|
+
init.property.name === 'current' &&
|
|
3873
|
+
init.object.type === 'CallExpression' &&
|
|
3874
|
+
init.object.callee.name === 'useRef'
|
|
3875
|
+
? init.object
|
|
3876
|
+
: null;
|
|
3877
|
+
const viaRef =
|
|
3878
|
+
init.type === 'CallExpression' && init.callee.name === 'useRef'
|
|
3879
|
+
? init
|
|
3880
|
+
: null;
|
|
3881
|
+
const useRefCall = viaCurrent || viaRef;
|
|
3882
|
+
if (!useRefCall || !isPanCreate(useRefCall.arguments[0])) {
|
|
3883
|
+
if (isPanCreate(init))
|
|
3884
|
+
throw aotError(
|
|
3885
|
+
'AOT: PanResponder.create(...) must be kept in a useRef',
|
|
3886
|
+
`write \`const ${decl.id.name} = useRef(PanResponder.create({…})).current;\` — the recogniser owns the live gesture, so a fresh one per render would throw the drag away (the same rule Flow A enforces).`,
|
|
3887
|
+
);
|
|
3888
|
+
continue;
|
|
3889
|
+
}
|
|
3890
|
+
const pan = buildPanDescriptor(
|
|
3891
|
+
decl.id.name,
|
|
3892
|
+
useRefCall.arguments[0],
|
|
3893
|
+
prefix,
|
|
3894
|
+
);
|
|
3895
|
+
pan.viaRefCurrent = !viaCurrent; // how the app spells the spread: pan.current.panHandlers
|
|
3896
|
+
pans.set(decl.id.name, pan);
|
|
3897
|
+
}
|
|
3898
|
+
}
|
|
3899
|
+
return pans;
|
|
2435
3900
|
}
|
|
2436
3901
|
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
: [{type: 'ExpressionStatement', expression: body}];
|
|
2443
|
-
// The handler's first parameter is the event; `<event>.x/.y/.dx/.dy` map to EREventData fields.
|
|
3902
|
+
/**
|
|
3903
|
+
* Lowers a should-set predicate to a single C boolean expression: the engine calls these synchronously
|
|
3904
|
+
* inside hit-testing, before anyone owns the gesture, so they may only READ.
|
|
3905
|
+
*/
|
|
3906
|
+
function compilePanQuery(fnNode, env, pan) {
|
|
2444
3907
|
const eventParam =
|
|
2445
3908
|
fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
|
|
2446
|
-
const
|
|
2447
|
-
|
|
2448
|
-
const
|
|
2449
|
-
if (
|
|
2450
|
-
|
|
3909
|
+
const gestureParam =
|
|
3910
|
+
fnNode.params[1]?.type === 'Identifier' ? fnNode.params[1].name : null;
|
|
3911
|
+
const qenv = {...env, pan};
|
|
3912
|
+
if (eventParam) qenv.event = eventParam;
|
|
3913
|
+
if (gestureParam) qenv.gesture = gestureParam;
|
|
3914
|
+
const body = fnNode.body;
|
|
3915
|
+
const expr =
|
|
3916
|
+
body.type === 'BlockStatement'
|
|
3917
|
+
? body.body.length === 1 && body.body[0].type === 'ReturnStatement'
|
|
3918
|
+
? body.body[0].argument
|
|
3919
|
+
: null
|
|
3920
|
+
: body;
|
|
3921
|
+
if (!expr)
|
|
3922
|
+
throw aotError(
|
|
3923
|
+
'AOT: a PanResponder should-set predicate must be a single boolean expression',
|
|
3924
|
+
'write it as `() => true` or `(e, g) => Math.abs(g.dx) > 8`. The engine asks these mid-hit-test, so they may only read (state, event/gesture fields, constants) — never set state.',
|
|
3925
|
+
);
|
|
3926
|
+
return `(${emitExpr(expr, qenv).code}) != 0`;
|
|
3927
|
+
}
|
|
3928
|
+
|
|
3929
|
+
/**
|
|
3930
|
+
* Emits one PanResponder's gesture state + C callbacks (once, however many nodes spread it), then wires
|
|
3931
|
+
* them onto a node. Grant/release/terminate are ALWAYS emitted even with no user callback: they own the
|
|
3932
|
+
* anchor bookkeeping that makes `g.dx` grant-relative.
|
|
3933
|
+
*/
|
|
3934
|
+
function emitPanResponder(pan, v, out, env, state) {
|
|
3935
|
+
if (!pan.emitted) {
|
|
3936
|
+
pan.stateID = ++out.panN;
|
|
3937
|
+
const p = pan.cPrefix;
|
|
3938
|
+
const penv = {...env, pan};
|
|
3939
|
+
const userBody = evt =>
|
|
3940
|
+
pan.events.has(evt)
|
|
3941
|
+
? compileHandler(pan.events.get(evt), penv, state, out, pan)
|
|
3942
|
+
: [];
|
|
3943
|
+
const guard = [
|
|
3944
|
+
' if (!' + p + '_granted)',
|
|
3945
|
+
' {',
|
|
3946
|
+
' return;',
|
|
3947
|
+
' }',
|
|
3948
|
+
];
|
|
3949
|
+
|
|
3950
|
+
out.panDecls.push(
|
|
3951
|
+
`/* PanResponder "${pan.name}" (gesture ${pan.stateID}) — RN's gestureState. The grant anchors the`,
|
|
3952
|
+
` travel so g.dx opens at 0 however much slop the claim cost; data->dx runs from touch-down. */`,
|
|
3953
|
+
`static int ${p}_granted = 0;`,
|
|
3954
|
+
`static int ${p}_base_dx = 0;`,
|
|
3955
|
+
`static int ${p}_base_dy = 0;`,
|
|
3956
|
+
`static int ${p}_x0 = 0;`,
|
|
3957
|
+
`static int ${p}_y0 = 0;`,
|
|
3958
|
+
);
|
|
3959
|
+
|
|
3960
|
+
pan.emitted = {events: [], queries: []};
|
|
3961
|
+
const push = (evt, suffix, body) => {
|
|
3962
|
+
const name = `${pan.fnPrefix}_${suffix}`;
|
|
3963
|
+
out.handlers.push({name, body});
|
|
3964
|
+
pan.emitted.events.push([evt, name]);
|
|
3965
|
+
};
|
|
3966
|
+
push('ER_EVENT_RESPONDER_GRANT', 'grant', [
|
|
3967
|
+
` if (${p}_granted)`,
|
|
3968
|
+
' {',
|
|
3969
|
+
' return; /* a second finger re-granted this node: one gesture, not two */',
|
|
3970
|
+
' }',
|
|
3971
|
+
` ${p}_granted = 1;`,
|
|
3972
|
+
` ${p}_base_dx = data->dx;`,
|
|
3973
|
+
` ${p}_base_dy = data->dy;`,
|
|
3974
|
+
` ${p}_x0 = data->x;`,
|
|
3975
|
+
` ${p}_y0 = data->y;`,
|
|
3976
|
+
...userBody('ER_EVENT_RESPONDER_GRANT'),
|
|
3977
|
+
]);
|
|
3978
|
+
// Release and terminate both END the gesture: run the app's callback while the anchor is still
|
|
3979
|
+
// valid (it is what g.dx reads through), then clear it for the next one.
|
|
3980
|
+
for (const [evt, suffix] of [
|
|
3981
|
+
['ER_EVENT_RESPONDER_RELEASE', 'release'],
|
|
3982
|
+
['ER_EVENT_RESPONDER_TERMINATE', 'terminate'],
|
|
3983
|
+
])
|
|
3984
|
+
push(evt, suffix, [
|
|
3985
|
+
...guard,
|
|
3986
|
+
...userBody(evt),
|
|
3987
|
+
` ${p}_granted = 0;`,
|
|
3988
|
+
` ${p}_base_dx = 0;`,
|
|
3989
|
+
` ${p}_base_dy = 0;`,
|
|
3990
|
+
]);
|
|
3991
|
+
if (pan.events.has('ER_EVENT_RESPONDER_MOVE'))
|
|
3992
|
+
push('ER_EVENT_RESPONDER_MOVE', 'move', [
|
|
3993
|
+
...guard,
|
|
3994
|
+
...userBody('ER_EVENT_RESPONDER_MOVE'),
|
|
3995
|
+
]);
|
|
3996
|
+
// Reject fires on a node that ASKED for the gesture and was refused — it never owned it, so no guard.
|
|
3997
|
+
if (pan.events.has('ER_EVENT_RESPONDER_REJECT'))
|
|
3998
|
+
push(
|
|
3999
|
+
'ER_EVENT_RESPONDER_REJECT',
|
|
4000
|
+
'reject',
|
|
4001
|
+
userBody('ER_EVENT_RESPONDER_REJECT'),
|
|
4002
|
+
);
|
|
4003
|
+
|
|
4004
|
+
for (const [query, fn] of pan.queries) {
|
|
4005
|
+
const name = `${pan.fnPrefix}_${PAN_QUERY_SUFFIX[query]}`;
|
|
4006
|
+
out.queries.push({name, expr: compilePanQuery(fn, penv, pan)});
|
|
4007
|
+
pan.emitted.queries.push([query, name]);
|
|
4008
|
+
}
|
|
4009
|
+
}
|
|
4010
|
+
|
|
4011
|
+
for (const [evt, name] of pan.emitted.events)
|
|
4012
|
+
out.build.push(` er_event_set(${v}, ${evt}, ${name}, NULL);`);
|
|
4013
|
+
for (const [query, name] of pan.emitted.queries)
|
|
4014
|
+
out.build.push(
|
|
4015
|
+
` er_responder_query_set(${v}, ${query}, ${name}, NULL);`,
|
|
4016
|
+
);
|
|
4017
|
+
}
|
|
4018
|
+
|
|
4019
|
+
/**
|
|
4020
|
+
* Resolves a JSX spread to the PanResponder it spreads, or null when it is some other spread. A name
|
|
4021
|
+
* that IS a responder but is spelled the other way round (`.current` where the app already unwrapped it,
|
|
4022
|
+
* or vice versa) is an error rather than a silent miss — Flow A would throw at runtime on the same code.
|
|
4023
|
+
*/
|
|
4024
|
+
function panSpreadTarget(argument, env) {
|
|
4025
|
+
if (
|
|
4026
|
+
argument?.type !== 'MemberExpression' ||
|
|
4027
|
+
argument.computed ||
|
|
4028
|
+
argument.property.name !== 'panHandlers'
|
|
4029
|
+
)
|
|
4030
|
+
return null;
|
|
4031
|
+
const obj = argument.object;
|
|
4032
|
+
const viaCurrent =
|
|
4033
|
+
obj.type === 'MemberExpression' &&
|
|
4034
|
+
!obj.computed &&
|
|
4035
|
+
obj.property.name === 'current' &&
|
|
4036
|
+
obj.object.type === 'Identifier';
|
|
4037
|
+
const rootName = viaCurrent ? obj.object.name : obj.name;
|
|
4038
|
+
const pan =
|
|
4039
|
+
obj.type === 'Identifier' || viaCurrent ? env.pans?.get(rootName) : null;
|
|
4040
|
+
if (!pan) return null;
|
|
4041
|
+
if (pan.viaRefCurrent !== viaCurrent)
|
|
4042
|
+
throw aotError(
|
|
4043
|
+
`AOT: "${rootName}" is a PanResponder, but this spread does not match how it was declared`,
|
|
4044
|
+
pan.viaRefCurrent
|
|
4045
|
+
? `it was declared as \`useRef(PanResponder.create({…}))\`, so spread \`{...${rootName}.current.panHandlers}\`.`
|
|
4046
|
+
: `it was declared as \`useRef(PanResponder.create({…})).current\`, so spread \`{...${rootName}.panHandlers}\`.`,
|
|
4047
|
+
);
|
|
4048
|
+
return pan;
|
|
2451
4049
|
}
|
|
2452
4050
|
|
|
2453
4051
|
// ---------------------------------------------------------------------------------------------------
|
|
@@ -2464,6 +4062,11 @@ function extractProps(openingElement, scope, env) {
|
|
|
2464
4062
|
for (const attr of openingElement.attributes) {
|
|
2465
4063
|
if (attr.type === 'JSXSpreadAttribute') {
|
|
2466
4064
|
// Static spread: {...obj} where obj folds to a compile-time object → merge its keys as props.
|
|
4065
|
+
if (panSpreadTarget(attr.argument, env))
|
|
4066
|
+
throw aotError(
|
|
4067
|
+
'AOT: a PanResponder can only be spread onto a host element',
|
|
4068
|
+
'spread `{...pan.panHandlers}` onto the <View> (or <Pressable>/<ScrollView>) that should own the gesture, not onto a component instance — the AOT wires the responder to a real scene node.',
|
|
4069
|
+
);
|
|
2467
4070
|
let obj;
|
|
2468
4071
|
try {
|
|
2469
4072
|
obj = evalStatic(attr.argument, scope);
|
|
@@ -2499,7 +4102,7 @@ function extractProps(openingElement, scope, env) {
|
|
|
2499
4102
|
try {
|
|
2500
4103
|
props[attr.name.name] = {static: true, value: evalStatic(node, scope)};
|
|
2501
4104
|
} catch {
|
|
2502
|
-
props[attr.name.name] = {static: false, ...
|
|
4105
|
+
props[attr.name.name] = {static: false, ...emitExprWide(node, env)};
|
|
2503
4106
|
}
|
|
2504
4107
|
}
|
|
2505
4108
|
return props;
|
|
@@ -2582,8 +4185,14 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
2582
4185
|
childrenRef = {kind: 'props', name: param.name};
|
|
2583
4186
|
}
|
|
2584
4187
|
|
|
2585
|
-
|
|
2586
|
-
const
|
|
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();
|
|
2587
4196
|
// Callback props bound here resolve to the CALLER's function (node + caller env/state) so the child can
|
|
2588
4197
|
// use them as event handlers (onPress={onTap}); inherit any the caller itself received (forwarding).
|
|
2589
4198
|
const fnProps = new Map(env.fnProps);
|
|
@@ -2599,8 +4208,18 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
2599
4208
|
state: d.state ?? state,
|
|
2600
4209
|
});
|
|
2601
4210
|
else if (d.static) childScope[name] = d.value;
|
|
2602
|
-
else
|
|
2603
|
-
childLocals.set(name, {
|
|
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
|
+
}
|
|
2604
4223
|
}
|
|
2605
4224
|
const children = childNodes.length
|
|
2606
4225
|
? {nodes: childNodes, scope, env, ref: childrenRef}
|
|
@@ -2612,15 +4231,47 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
2612
4231
|
// exactly like a React component — it receives everything else through props. All initials/values fold
|
|
2613
4232
|
// against the child's static-prop scope. prefix is per-instance; the App keeps the bare (unprefixed) names.
|
|
2614
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
|
+
|
|
2615
4261
|
const childAnims = collectAnims(fn.body, childScope, prefix);
|
|
2616
|
-
const childRefs = collectRefs(fn.body, childScope, prefix);
|
|
4262
|
+
const childRefs = collectRefs(fn.body, childScope, prefix, env.wide);
|
|
4263
|
+
const childPans = collectPanResponders(fn.body, prefix);
|
|
2617
4264
|
const childCallbacks = collectCallbacks(fn.body);
|
|
2618
4265
|
const childMemos = collectMemos(fn.body);
|
|
2619
4266
|
let childState = state;
|
|
2620
4267
|
if (usesState(fn)) {
|
|
2621
|
-
childState = collectState(fn.body, childScope, prefix);
|
|
4268
|
+
childState = collectState(fn.body, childScope, prefix, env.wide);
|
|
2622
4269
|
out.childStateRecords.push(...childState.byName.values());
|
|
4270
|
+
for (const name of childState.byName.keys()) delete childScope[name];
|
|
2623
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];
|
|
2624
4275
|
out.childRefs.push(...childRefs.values());
|
|
2625
4276
|
out.childAnims.push(...childAnims.values());
|
|
2626
4277
|
|
|
@@ -2633,6 +4284,7 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
2633
4284
|
state: childState.byName,
|
|
2634
4285
|
anims: childAnims,
|
|
2635
4286
|
refs: childRefs,
|
|
4287
|
+
pans: childPans,
|
|
2636
4288
|
callbacks: childCallbacks,
|
|
2637
4289
|
helpers: collectHelpers(fn.body, out.program),
|
|
2638
4290
|
cbPrefix: prefix,
|
|
@@ -2644,8 +4296,13 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
2644
4296
|
try {
|
|
2645
4297
|
childScope[name] = evalStatic(expr, childScope);
|
|
2646
4298
|
} catch {
|
|
2647
|
-
const e =
|
|
2648
|
-
childLocals.set(name, {
|
|
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
|
|
2649
4306
|
}
|
|
2650
4307
|
}
|
|
2651
4308
|
for (const eff of collectEffects(fn.body)) {
|
|
@@ -2697,12 +4354,42 @@ function emitMap(call, parentVar, scope, out, env, state) {
|
|
|
2697
4354
|
parentVar,
|
|
2698
4355
|
iterScope,
|
|
2699
4356
|
out,
|
|
2700
|
-
|
|
4357
|
+
rowEnv(env, [itemName, idxName], iterScope),
|
|
2701
4358
|
state,
|
|
2702
4359
|
);
|
|
2703
4360
|
});
|
|
2704
4361
|
}
|
|
2705
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
|
+
|
|
2706
4393
|
/**
|
|
2707
4394
|
* `{listState.map((item, i) => <Row/>)}` over a STATE array of variable length. Pre-allocates a fixed
|
|
2708
4395
|
* pool of `cap` rows (no runtime malloc); each row k binds `item` to `s_<name>[k]` (a struct local) and
|
|
@@ -2717,8 +4404,12 @@ function emitDynamicMap(call, rec, parentVar, scope, out, env, state) {
|
|
|
2717
4404
|
const retJSX = componentReturnJSX(cb);
|
|
2718
4405
|
for (let k = 0; k < rec.cap; k++) {
|
|
2719
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];
|
|
2720
4410
|
if (idxName) iterScope[idxName] = k; // the index is a compile-time literal per pooled row
|
|
2721
4411
|
const locals = new Map(env.locals);
|
|
4412
|
+
if (idxName) locals.delete(idxName); // the index is a per-row literal in iterScope
|
|
2722
4413
|
if (itemName)
|
|
2723
4414
|
locals.set(itemName, {
|
|
2724
4415
|
code: `${rec.arrayName}[${k}]`,
|
|
@@ -2729,7 +4420,7 @@ function emitDynamicMap(call, rec, parentVar, scope, out, env, state) {
|
|
|
2729
4420
|
parentVar,
|
|
2730
4421
|
iterScope,
|
|
2731
4422
|
out,
|
|
2732
|
-
|
|
4423
|
+
rowEnv(env, [itemName, idxName], iterScope, locals),
|
|
2733
4424
|
state,
|
|
2734
4425
|
{
|
|
2735
4426
|
displayCode: `(${k} < ${rec.countMember})`,
|
|
@@ -2767,7 +4458,7 @@ function emitChildren(children, parentVar, scope, out, env, state) {
|
|
|
2767
4458
|
if (cond)
|
|
2768
4459
|
emitElementInto(expr.right, parentVar, scope, out, env, state);
|
|
2769
4460
|
} catch {
|
|
2770
|
-
const code = emitExpr(expr.left, env)
|
|
4461
|
+
const code = asCond(emitExpr(expr.left, env));
|
|
2771
4462
|
emitElementInto(expr.right, parentVar, scope, out, env, state, {
|
|
2772
4463
|
displayCode: code,
|
|
2773
4464
|
});
|
|
@@ -2790,7 +4481,7 @@ function emitChildren(children, parentVar, scope, out, env, state) {
|
|
|
2790
4481
|
state,
|
|
2791
4482
|
);
|
|
2792
4483
|
} catch {
|
|
2793
|
-
const code = emitExpr(expr.test, env)
|
|
4484
|
+
const code = asCond(emitExpr(expr.test, env));
|
|
2794
4485
|
if (expr.consequent.type === 'JSXElement')
|
|
2795
4486
|
emitElementInto(
|
|
2796
4487
|
expr.consequent,
|
|
@@ -2847,6 +4538,32 @@ function emitChildren(children, parentVar, scope, out, env, state) {
|
|
|
2847
4538
|
// Flow A uses), giving a flat {ops, paints}. We bake those into C const arrays + er_node_set_vector_ops.
|
|
2848
4539
|
// ---------------------------------------------------------------------------------------------------
|
|
2849
4540
|
|
|
4541
|
+
/**
|
|
4542
|
+
* Yields an <Svg> subtree's shape children in source order, inlining any `<>…</>` in place: a fragment
|
|
4543
|
+
* carries no paint and no transform, so it is transparent to the tape (the Flow A walk in flattenSvg
|
|
4544
|
+
* treats it the same way). Whitespace between elements and JSX comments are skipped; anything else
|
|
4545
|
+
* that has no shape to contribute throws, rather than vanishing from the generated C.
|
|
4546
|
+
*/
|
|
4547
|
+
function* svgShapeChildren(children) {
|
|
4548
|
+
for (const c of children) {
|
|
4549
|
+
if (c.type === 'JSXElement') yield c;
|
|
4550
|
+
else if (c.type === 'JSXFragment') yield* svgShapeChildren(c.children);
|
|
4551
|
+
else if (c.type === 'JSXText') {
|
|
4552
|
+
if (c.value.trim())
|
|
4553
|
+
throw new Error(
|
|
4554
|
+
`AOT: <Svg> cannot draw text — remove ${JSON.stringify(c.value.trim())} from the subtree`,
|
|
4555
|
+
);
|
|
4556
|
+
} else if (c.type === 'JSXExpressionContainer') {
|
|
4557
|
+
if (c.expression.type !== 'JSXEmptyExpression')
|
|
4558
|
+
throw new Error(
|
|
4559
|
+
'AOT: dynamic <Svg> children ({…}) not yet supported — use literal shape elements',
|
|
4560
|
+
);
|
|
4561
|
+
} else {
|
|
4562
|
+
throw new Error(`AOT: unsupported <Svg> child (${c.type})`);
|
|
4563
|
+
}
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
4566
|
+
|
|
2850
4567
|
/** Converts an SVG JSX element (Svg/Circle/Path/Rect/Line/Arc/G/…) to flattenSvg's `{type, props}` shape,
|
|
2851
4568
|
* statically evaluating every attribute. Dynamic attrs/children throw (a state-driven Svg is not supported). */
|
|
2852
4569
|
function jsxToSvgElement(node, scope) {
|
|
@@ -2871,16 +4588,8 @@ function jsxToSvgElement(node, scope) {
|
|
|
2871
4588
|
);
|
|
2872
4589
|
}
|
|
2873
4590
|
const children = [];
|
|
2874
|
-
for (const c of node.children)
|
|
2875
|
-
|
|
2876
|
-
else if (
|
|
2877
|
-
c.type === 'JSXExpressionContainer' &&
|
|
2878
|
-
c.expression.type !== 'JSXEmptyExpression'
|
|
2879
|
-
)
|
|
2880
|
-
throw new Error(
|
|
2881
|
-
'AOT: dynamic <Svg> children ({…}) not yet supported — use literal shape elements',
|
|
2882
|
-
);
|
|
2883
|
-
}
|
|
4591
|
+
for (const c of svgShapeChildren(node.children))
|
|
4592
|
+
children.push(jsxToSvgElement(c, scope));
|
|
2884
4593
|
if (children.length) props.children = children;
|
|
2885
4594
|
return {type, props};
|
|
2886
4595
|
}
|
|
@@ -2941,8 +4650,15 @@ function svgAttrs(openingElement, scope, env) {
|
|
|
2941
4650
|
else if (vn.type === 'StringLiteral') out[name] = vn.value;
|
|
2942
4651
|
else if (vn.type === 'JSXExpressionContainer') {
|
|
2943
4652
|
try {
|
|
2944
|
-
out[name] = evalStatic(vn.expression, scope);
|
|
4653
|
+
out[name] = evalStatic(vn.expression, withUndefined(scope));
|
|
2945
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
|
+
}
|
|
2946
4662
|
// Keep the raw expression node too: color paint attrs (fill/stroke) lower via emitColorExpr (→ ARGB),
|
|
2947
4663
|
// not the generic numeric `dyn` code, so a dynamic color resolves to a uint, not a char*.
|
|
2948
4664
|
out[name] = {
|
|
@@ -3055,13 +4771,13 @@ function gradAttr(v, scope, env, what) {
|
|
|
3055
4771
|
node.consequent.type === 'ObjectExpression' &&
|
|
3056
4772
|
nullish(node.alternate)
|
|
3057
4773
|
) {
|
|
3058
|
-
cond = emitExpr(node.test, env)
|
|
4774
|
+
cond = asCond(emitExpr(node.test, env));
|
|
3059
4775
|
node = node.consequent;
|
|
3060
4776
|
} else if (
|
|
3061
4777
|
node.alternate.type === 'ObjectExpression' &&
|
|
3062
4778
|
nullish(node.consequent)
|
|
3063
4779
|
) {
|
|
3064
|
-
cond = `!(${emitExpr(node.test, env)
|
|
4780
|
+
cond = `!(${asCond(emitExpr(node.test, env))})`;
|
|
3065
4781
|
node = node.alternate;
|
|
3066
4782
|
} else
|
|
3067
4783
|
throw new Error(
|
|
@@ -3072,7 +4788,7 @@ function gradAttr(v, scope, env, what) {
|
|
|
3072
4788
|
node.operator === '&&' &&
|
|
3073
4789
|
node.right.type === 'ObjectExpression'
|
|
3074
4790
|
) {
|
|
3075
|
-
cond = emitExpr(node.left, env)
|
|
4791
|
+
cond = asCond(emitExpr(node.left, env));
|
|
3076
4792
|
node = node.right;
|
|
3077
4793
|
}
|
|
3078
4794
|
const spec = gradSpec(node, scope, env, what);
|
|
@@ -3202,7 +4918,32 @@ const circleEntriesC = (cx, cy, r) => [
|
|
|
3202
4918
|
'0.0f',
|
|
3203
4919
|
'ER_VOP_CLOSE',
|
|
3204
4920
|
];
|
|
3205
|
-
|
|
4921
|
+
/** The numeric value of a C float literal (as produced by floatLit/cf, or the `(float)(N)` cast the
|
|
4922
|
+
* imperative updateVector path emits), or null for a state-driven expr. */
|
|
4923
|
+
const C_NUM = '-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?';
|
|
4924
|
+
const cLit = e => {
|
|
4925
|
+
const t = String(e).trim();
|
|
4926
|
+
const cast = new RegExp(`^\\(float\\)\\((${C_NUM})\\)$`).exec(t);
|
|
4927
|
+
if (cast) return parseFloat(cast[1]);
|
|
4928
|
+
return new RegExp(`^${C_NUM}f$`).test(t) ? parseFloat(t) : null;
|
|
4929
|
+
};
|
|
4930
|
+
|
|
4931
|
+
/** Normalizes a shape's geometry result. Most shapes are just an op-tape; a rounded <Rect> also returns
|
|
4932
|
+
* the `const float` locals the caller must declare ahead of that tape, in the same C block. */
|
|
4933
|
+
const geometryOf = g => (Array.isArray(g) ? {entries: g, locals: []} : g);
|
|
4934
|
+
|
|
4935
|
+
/** A corner radius clamped to half its side, mirroring svg-ops rectRadii. Folded to a literal when both
|
|
4936
|
+
* the radius and the side are static — the usual case, since only x/y/width tend to be state-driven. */
|
|
4937
|
+
const clampRadiusC = (r, side) => {
|
|
4938
|
+
const lr = cLit(r);
|
|
4939
|
+
if (lr != null && lr <= 0) return '0.0f';
|
|
4940
|
+
const ls = cLit(side);
|
|
4941
|
+
if (lr != null && ls != null)
|
|
4942
|
+
return floatLit(Math.max(0, Math.min(lr, ls / 2)));
|
|
4943
|
+
return `fminf(fmaxf(${r}, 0.0f), (${side}) * 0.5f)`;
|
|
4944
|
+
};
|
|
4945
|
+
|
|
4946
|
+
const sharpRectEntriesC = (x, y, w, h) => [
|
|
3206
4947
|
'ER_VOP_MOVE',
|
|
3207
4948
|
x,
|
|
3208
4949
|
y,
|
|
@@ -3217,6 +4958,95 @@ const rectEntriesC = (x, y, w, h) => [
|
|
|
3217
4958
|
`(${y} + ${h})`,
|
|
3218
4959
|
'ER_VOP_CLOSE',
|
|
3219
4960
|
];
|
|
4961
|
+
|
|
4962
|
+
// rx/ry are null when the rect has no corner radius at all. Corners are cubics, not ER_VOP_ARC, for the
|
|
4963
|
+
// same reason svg-ops uses them: a corner must start at EXACTLY the preceding line's endpoint. Returns
|
|
4964
|
+
// { entries, locals }; `tag` names the locals and must be unique within the caller's C block.
|
|
4965
|
+
const rectEntriesC = (x, y, w, h, rx = null, ry = null, tag = '') => {
|
|
4966
|
+
// A negative radius is invalid, and invalid means `auto` — so it falls back to the other radius
|
|
4967
|
+
// rather than squaring the corners (svg-ops rectRadii, and what browsers render). Only a literal can
|
|
4968
|
+
// be resolved here; a state-driven radius is assumed non-negative and merely clamped at runtime.
|
|
4969
|
+
const isNeg = e => {
|
|
4970
|
+
const l = cLit(e);
|
|
4971
|
+
return l != null && l < 0;
|
|
4972
|
+
};
|
|
4973
|
+
if (isNeg(rx)) rx = null;
|
|
4974
|
+
if (isNeg(ry)) ry = null;
|
|
4975
|
+
if (rx == null && ry == null)
|
|
4976
|
+
return {entries: sharpRectEntriesC(x, y, w, h), locals: []};
|
|
4977
|
+
let cx = clampRadiusC(rx ?? ry, w);
|
|
4978
|
+
let cy = clampRadiusC(ry ?? rx, h);
|
|
4979
|
+
if (cLit(cx) === 0 || cLit(cy) === 0)
|
|
4980
|
+
return {entries: sharpRectEntriesC(x, y, w, h), locals: []};
|
|
4981
|
+
// A clamp that did not fold is a runtime fminf/fmaxf pair the tape below would otherwise repeat ten
|
|
4982
|
+
// times over — and with a state-driven side, each copy drags the whole side expression with it. Bind
|
|
4983
|
+
// it once instead; a folded radius stays inline, so an all-static rect emits exactly what it used to.
|
|
4984
|
+
const locals = [];
|
|
4985
|
+
if (cLit(cx) == null) {
|
|
4986
|
+
locals.push(`const float rx_${tag} = ${cx};`);
|
|
4987
|
+
cx = `rx_${tag}`;
|
|
4988
|
+
}
|
|
4989
|
+
if (cLit(cy) == null) {
|
|
4990
|
+
locals.push(`const float ry_${tag} = ${cy};`);
|
|
4991
|
+
cy = `ry_${tag}`;
|
|
4992
|
+
}
|
|
4993
|
+
const k = floatLit(KAPPA);
|
|
4994
|
+
const kx = `(${cx} * ${k})`;
|
|
4995
|
+
const ky = `(${cy} * ${k})`;
|
|
4996
|
+
const x1 = `(${x} + ${cx})`;
|
|
4997
|
+
const x2 = `(${x} + ${w} - ${cx})`;
|
|
4998
|
+
const y1 = `(${y} + ${cy})`;
|
|
4999
|
+
const y2 = `(${y} + ${h} - ${cy})`;
|
|
5000
|
+
const r = `(${x} + ${w})`;
|
|
5001
|
+
const b = `(${y} + ${h})`;
|
|
5002
|
+
const entries = [
|
|
5003
|
+
'ER_VOP_MOVE',
|
|
5004
|
+
x1,
|
|
5005
|
+
y,
|
|
5006
|
+
'ER_VOP_LINE',
|
|
5007
|
+
x2,
|
|
5008
|
+
y,
|
|
5009
|
+
'ER_VOP_CUBIC',
|
|
5010
|
+
`(${x2} + ${kx})`,
|
|
5011
|
+
y,
|
|
5012
|
+
r,
|
|
5013
|
+
`(${y1} - ${ky})`,
|
|
5014
|
+
r,
|
|
5015
|
+
y1,
|
|
5016
|
+
'ER_VOP_LINE',
|
|
5017
|
+
r,
|
|
5018
|
+
y2,
|
|
5019
|
+
'ER_VOP_CUBIC',
|
|
5020
|
+
r,
|
|
5021
|
+
`(${y2} + ${ky})`,
|
|
5022
|
+
`(${x2} + ${kx})`,
|
|
5023
|
+
b,
|
|
5024
|
+
x2,
|
|
5025
|
+
b,
|
|
5026
|
+
'ER_VOP_LINE',
|
|
5027
|
+
x1,
|
|
5028
|
+
b,
|
|
5029
|
+
'ER_VOP_CUBIC',
|
|
5030
|
+
`(${x1} - ${kx})`,
|
|
5031
|
+
b,
|
|
5032
|
+
x,
|
|
5033
|
+
`(${y2} + ${ky})`,
|
|
5034
|
+
x,
|
|
5035
|
+
y2,
|
|
5036
|
+
'ER_VOP_LINE',
|
|
5037
|
+
x,
|
|
5038
|
+
y1,
|
|
5039
|
+
'ER_VOP_CUBIC',
|
|
5040
|
+
x,
|
|
5041
|
+
`(${y1} - ${ky})`,
|
|
5042
|
+
`(${x1} - ${kx})`,
|
|
5043
|
+
y,
|
|
5044
|
+
x1,
|
|
5045
|
+
y,
|
|
5046
|
+
'ER_VOP_CLOSE',
|
|
5047
|
+
];
|
|
5048
|
+
return {entries, locals};
|
|
5049
|
+
};
|
|
3220
5050
|
const lineEntriesC = (x1, y1, x2, y2) => [
|
|
3221
5051
|
'ER_VOP_MOVE',
|
|
3222
5052
|
x1,
|
|
@@ -3230,8 +5060,16 @@ const lineEntriesC = (x1, y1, x2, y2) => [
|
|
|
3230
5060
|
const arcEntries = a =>
|
|
3231
5061
|
arcEntriesC(cf(a.cx), cf(a.cy), cf(a.r), cf(a.startAngle), cf(a.endAngle));
|
|
3232
5062
|
const circleEntries = a => circleEntriesC(cf(a.cx), cf(a.cy), cf(a.r));
|
|
3233
|
-
const rectEntries = a =>
|
|
3234
|
-
rectEntriesC(
|
|
5063
|
+
const rectEntries = (a, tag) =>
|
|
5064
|
+
rectEntriesC(
|
|
5065
|
+
cf(a.x),
|
|
5066
|
+
cf(a.y),
|
|
5067
|
+
cf(a.width),
|
|
5068
|
+
cf(a.height),
|
|
5069
|
+
a.rx == null ? null : cf(a.rx),
|
|
5070
|
+
a.ry == null ? null : cf(a.ry),
|
|
5071
|
+
tag,
|
|
5072
|
+
);
|
|
3235
5073
|
const lineEntries = a => lineEntriesC(cf(a.x1), cf(a.y1), cf(a.x2), cf(a.y2));
|
|
3236
5074
|
const pathEntries = a => {
|
|
3237
5075
|
if (a.d == null) return [];
|
|
@@ -3253,6 +5091,11 @@ const SHAPE_ENTRIES = {
|
|
|
3253
5091
|
function svgHasDynamic(el, scope) {
|
|
3254
5092
|
let dyn = false;
|
|
3255
5093
|
const walk = node => {
|
|
5094
|
+
// A fragment holds no attributes of its own but its shapes' attributes still count.
|
|
5095
|
+
if (node.type === 'JSXFragment') {
|
|
5096
|
+
for (const c of node.children) walk(c);
|
|
5097
|
+
return;
|
|
5098
|
+
}
|
|
3256
5099
|
if (node.type !== 'JSXElement') return;
|
|
3257
5100
|
for (const attr of node.openingElement.attributes) {
|
|
3258
5101
|
if (
|
|
@@ -3458,9 +5301,9 @@ function emitSvgDynamic(el, scope, out, env, state) {
|
|
|
3458
5301
|
'AOT: a viewBox on a state-driven <Svg> is not yet supported — size shapes in the width/height space',
|
|
3459
5302
|
);
|
|
3460
5303
|
const entries = [];
|
|
5304
|
+
const decls = []; // C locals the shapes need declared ahead of the tape (rounded-rect radii)
|
|
3461
5305
|
const specs = [];
|
|
3462
|
-
for (const c of el.children) {
|
|
3463
|
-
if (c.type !== 'JSXElement') continue;
|
|
5306
|
+
for (const c of svgShapeChildren(el.children)) {
|
|
3464
5307
|
const type = c.openingElement.name.name;
|
|
3465
5308
|
const fn = SHAPE_ENTRIES[type];
|
|
3466
5309
|
if (!fn)
|
|
@@ -3468,9 +5311,11 @@ function emitSvgDynamic(el, scope, out, env, state) {
|
|
|
3468
5311
|
`AOT: <${type}> is not a supported shape in a state-driven <Svg> (no <G>/viewBox yet)`,
|
|
3469
5312
|
);
|
|
3470
5313
|
const a = svgAttrs(c.openingElement, scope, env);
|
|
3471
|
-
|
|
3472
|
-
|
|
3473
|
-
|
|
5314
|
+
// build_svgN() is this <Svg>'s own function, so the shape index alone keeps a local's name unique.
|
|
5315
|
+
const shape = geometryOf(fn(a, `s${specs.length}`));
|
|
5316
|
+
if (!shape.entries.length) continue;
|
|
5317
|
+
decls.push(...shape.locals);
|
|
5318
|
+
entries.push('ER_VOP_SHAPE', floatLit(specs.length), ...shape.entries);
|
|
3474
5319
|
specs.push(paintSpec(a, env, scope));
|
|
3475
5320
|
}
|
|
3476
5321
|
const v = `n${out.n++}`;
|
|
@@ -3515,9 +5360,10 @@ function emitSvgDynamic(el, scope, out, env, state) {
|
|
|
3515
5360
|
out.vectorData.push(
|
|
3516
5361
|
`static const ERVectorPaint s_svg${id}_paints[] = {\n${specs.map(p => ' ' + paintInitFromSpec(p)).join(',\n')}\n};`,
|
|
3517
5362
|
);
|
|
3518
|
-
const builderLines =
|
|
3519
|
-
(
|
|
3520
|
-
|
|
5363
|
+
const builderLines = [
|
|
5364
|
+
...decls.map(d => ` ${d}`),
|
|
5365
|
+
...entries.map((e, i) => ` s_svg${id}_ops[${i}] = ${e};`),
|
|
5366
|
+
];
|
|
3521
5367
|
if (dynPaint)
|
|
3522
5368
|
specs.forEach((ps, pi) =>
|
|
3523
5369
|
ps.fields.forEach((f, fi) =>
|
|
@@ -3534,69 +5380,368 @@ function emitSvgDynamic(el, scope, out, env, state) {
|
|
|
3534
5380
|
`static void build_svg${id}(void)\n{\n${builderLines.join('\n')}\n}`,
|
|
3535
5381
|
);
|
|
3536
5382
|
|
|
3537
|
-
emitSvgBox(v, svgA.width, svgA.height, el.openingElement, scope, out, env);
|
|
3538
|
-
out.build.push(
|
|
3539
|
-
` build_svg${id}();`,
|
|
3540
|
-
` er_node_set_vector_ops(${v}, s_svg${id}_ops, ${len}, s_svg${id}_paints, ${nPaints}, ${grads.length ? `s_svg${id}_grads` : 'NULL'}, ${grads.length});`,
|
|
3541
|
-
` s_${v} = ${v};`,
|
|
3542
|
-
);
|
|
3543
|
-
out.handles.push(v);
|
|
3544
|
-
out.svgUpdates.push({
|
|
3545
|
-
id,
|
|
3546
|
-
len,
|
|
3547
|
-
nPaints,
|
|
3548
|
-
nGrads: grads.length,
|
|
3549
|
-
nodeVar: `s_${v}`,
|
|
5383
|
+
emitSvgBox(v, svgA.width, svgA.height, el.openingElement, scope, out, env);
|
|
5384
|
+
out.build.push(
|
|
5385
|
+
` build_svg${id}();`,
|
|
5386
|
+
` er_node_set_vector_ops(${v}, s_svg${id}_ops, ${len}, s_svg${id}_paints, ${nPaints}, ${grads.length ? `s_svg${id}_grads` : 'NULL'}, ${grads.length});`,
|
|
5387
|
+
` s_${v} = ${v};`,
|
|
5388
|
+
);
|
|
5389
|
+
out.handles.push(v);
|
|
5390
|
+
out.svgUpdates.push({
|
|
5391
|
+
id,
|
|
5392
|
+
len,
|
|
5393
|
+
nPaints,
|
|
5394
|
+
nGrads: grads.length,
|
|
5395
|
+
nodeVar: `s_${v}`,
|
|
5396
|
+
});
|
|
5397
|
+
return v;
|
|
5398
|
+
}
|
|
5399
|
+
|
|
5400
|
+
// ---------------------------------------------------------------------------------------------------
|
|
5401
|
+
// Node emitters — typed components. Each maps one JSX element to its engine node + props: the shared
|
|
5402
|
+
// helpers (emitRefBind, compileValueHandler) then Switch / TextInput / ActivityIndicator / Modal /
|
|
5403
|
+
// FlatList. The generic host node (View/Text/Pressable/Image/ScrollView) + the element dispatcher live
|
|
5404
|
+
// in the next section (emitNodeImpl).
|
|
5405
|
+
// ---------------------------------------------------------------------------------------------------
|
|
5406
|
+
|
|
5407
|
+
/** Captures `ref={r}` (r a node ref) by storing the freshly-created node handle into the ref's slot. */
|
|
5408
|
+
function emitRefBind(v, openingElement, out, env) {
|
|
5409
|
+
for (const attr of openingElement.attributes) {
|
|
5410
|
+
if (attr.type !== 'JSXAttribute' || attr.name.name !== 'ref') continue;
|
|
5411
|
+
const e =
|
|
5412
|
+
attr.value?.type === 'JSXExpressionContainer'
|
|
5413
|
+
? attr.value.expression
|
|
5414
|
+
: null;
|
|
5415
|
+
if (e?.type === 'Identifier' && env.refs?.get(e.name)?.kind === 'node') {
|
|
5416
|
+
const r = env.refs.get(e.name);
|
|
5417
|
+
r.used = true;
|
|
5418
|
+
out.build.push(` ${r.cVar} = ${v};`);
|
|
5419
|
+
} else
|
|
5420
|
+
throw new Error(
|
|
5421
|
+
'AOT: ref={…} must reference a node ref declared with useRef()',
|
|
5422
|
+
);
|
|
5423
|
+
}
|
|
5424
|
+
}
|
|
5425
|
+
|
|
5426
|
+
/** Compiles a value-callback (e.g. Switch onValueChange) — binds its first param to `valueCode`, not an event. */
|
|
5427
|
+
function compileValueHandler(
|
|
5428
|
+
fnNode,
|
|
5429
|
+
valueCode,
|
|
5430
|
+
env,
|
|
5431
|
+
state,
|
|
5432
|
+
out,
|
|
5433
|
+
cType = 'int',
|
|
5434
|
+
valueCode2 = null,
|
|
5435
|
+
isBool = false,
|
|
5436
|
+
) {
|
|
5437
|
+
const param =
|
|
5438
|
+
fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
|
|
5439
|
+
const locals = new Map(env.locals);
|
|
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});
|
|
5442
|
+
// A second parameter (a RANGE <Dial>'s low end) binds the same way, so `onChange={(hi, lo) => …}`
|
|
5443
|
+
// lowers to data->value / data->value_start with no object allocated on device.
|
|
5444
|
+
const param2 =
|
|
5445
|
+
fnNode.params[1]?.type === 'Identifier' ? fnNode.params[1].name : null;
|
|
5446
|
+
if (param2 && valueCode2) locals.set(param2, {code: valueCode2, cType});
|
|
5447
|
+
const ctx = {stateChanged: false, animIdx: 0, out};
|
|
5448
|
+
const body = fnNode.body;
|
|
5449
|
+
const list =
|
|
5450
|
+
body.type === 'BlockStatement'
|
|
5451
|
+
? body.body
|
|
5452
|
+
: [{type: 'ExpressionStatement', expression: body}];
|
|
5453
|
+
const stmts = compileStmts(list, {...env, locals}, state, ctx, ' ');
|
|
5454
|
+
if (ctx.stateChanged) stmts.push(APP_UPDATE_CALL);
|
|
5455
|
+
return stmts;
|
|
5456
|
+
}
|
|
5457
|
+
|
|
5458
|
+
/** <Dial> prop → ERProps field tables (see emitDial). */
|
|
5459
|
+
const DIAL_FLOAT_PROPS = {
|
|
5460
|
+
value: 'arc_value',
|
|
5461
|
+
valueStart: 'arc_value_start',
|
|
5462
|
+
minSpan: 'arc_min_span',
|
|
5463
|
+
min: 'arc_min',
|
|
5464
|
+
max: 'arc_max',
|
|
5465
|
+
startAngle: 'arc_start_angle',
|
|
5466
|
+
sweepAngle: 'arc_sweep_angle',
|
|
5467
|
+
step: 'arc_step',
|
|
5468
|
+
gapAngle: 'arc_gap_angle',
|
|
5469
|
+
};
|
|
5470
|
+
const DIAL_INT_PROPS = {
|
|
5471
|
+
thickness: 'arc_width',
|
|
5472
|
+
bandThickness: 'arc_band_width',
|
|
5473
|
+
knobSize: 'arc_knob_size',
|
|
5474
|
+
knobBorderWidth: 'arc_knob_border_width',
|
|
5475
|
+
segments: 'arc_segments',
|
|
5476
|
+
};
|
|
5477
|
+
const DIAL_COLOR_PROPS = {
|
|
5478
|
+
trackColor: 'arc_track_color',
|
|
5479
|
+
indicatorColor: 'arc_indicator_color',
|
|
5480
|
+
bandColor: 'arc_band_color',
|
|
5481
|
+
knobColor: 'arc_knob_color',
|
|
5482
|
+
knobBorderColor: 'arc_knob_border_color',
|
|
5483
|
+
};
|
|
5484
|
+
const DIAL_ENUM_PROPS = {
|
|
5485
|
+
cap: {
|
|
5486
|
+
field: 'arc_cap',
|
|
5487
|
+
table: {butt: 'ER_ARC_CAP_BUTT', round: 'ER_ARC_CAP_ROUND'},
|
|
5488
|
+
},
|
|
5489
|
+
knob: {
|
|
5490
|
+
field: 'arc_knob',
|
|
5491
|
+
table: {
|
|
5492
|
+
none: 'ER_ARC_KNOB_NONE',
|
|
5493
|
+
circle: 'ER_ARC_KNOB_CIRCLE',
|
|
5494
|
+
image: 'ER_ARC_KNOB_IMAGE',
|
|
5495
|
+
child: 'ER_ARC_KNOB_CHILD',
|
|
5496
|
+
},
|
|
5497
|
+
},
|
|
5498
|
+
};
|
|
5499
|
+
|
|
5500
|
+
/**
|
|
5501
|
+
* <Dial value={v} min max startAngle sweepAngle step thickness bandThickness trackColor indicatorColor
|
|
5502
|
+
* indicatorGradient bandColor cap segments gapAngle knob knobSize knobColor knobBorderColor
|
|
5503
|
+
* knobBorderWidth knobImage adjustable onChange={(v) => setV(v)} style=… />
|
|
5504
|
+
* → ER_NODE_ARC, the engine's native arc widget. Numbers and colours are static literals or state-driven
|
|
5505
|
+
* (recomputed in app_update); `value` may also be a useAnimatedValue handle, which binds ER_PROP_ARC_VALUE
|
|
5506
|
+
* natively so a ramp costs no app_update at all. onChange lowers to ER_EVENT_VALUE_CHANGE with its param
|
|
5507
|
+
* bound to data->value (the quantized value the built-in drag produced). Default 120x120 box.
|
|
5508
|
+
*/
|
|
5509
|
+
function emitDial(el, scope, out, env, state) {
|
|
5510
|
+
const v = `n${out.n++}`;
|
|
5511
|
+
const {staticAssigns, dynAssigns, binds} = collectStyleAssigns(
|
|
5512
|
+
el.openingElement,
|
|
5513
|
+
scope,
|
|
5514
|
+
env,
|
|
5515
|
+
);
|
|
5516
|
+
const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
|
|
5517
|
+
if (!hasField('width')) staticAssigns.push({field: 'width', expr: '120'});
|
|
5518
|
+
if (!hasField('height')) staticAssigns.push({field: 'height', expr: '120'});
|
|
5519
|
+
|
|
5520
|
+
const SUPPORTED =
|
|
5521
|
+
'supported props: value, min, max, startAngle, sweepAngle, step, thickness, bandThickness, ' +
|
|
5522
|
+
'trackColor, indicatorColor, indicatorGradient, bandColor, cap, segments, gapAngle, knob, knobSize, ' +
|
|
5523
|
+
'minSpan, ' +
|
|
5524
|
+
'knobColor, knobBorderColor, knobBorderWidth, knobImage, adjustable, range, valueStart, onChange, style.';
|
|
5525
|
+
const numeric = (field, node, isFloat) => {
|
|
5526
|
+
try {
|
|
5527
|
+
const n = evalStatic(node, scope);
|
|
5528
|
+
if (typeof n !== 'number') throw new Error('not a number');
|
|
5529
|
+
staticAssigns.push({
|
|
5530
|
+
field,
|
|
5531
|
+
expr: isFloat ? floatLit(n) : String(Math.round(n)),
|
|
5532
|
+
});
|
|
5533
|
+
} catch {
|
|
5534
|
+
const e = emitExpr(node, env);
|
|
5535
|
+
dynAssigns.push({
|
|
5536
|
+
field,
|
|
5537
|
+
code: isFloat ? `(float)(${e.code})` : `app_round_dim(${e.code})`,
|
|
5538
|
+
});
|
|
5539
|
+
}
|
|
5540
|
+
};
|
|
5541
|
+
const colour = (field, node) => {
|
|
5542
|
+
try {
|
|
5543
|
+
const c = evalStatic(node, scope);
|
|
5544
|
+
if (typeof c !== 'string') throw new Error('not a colour');
|
|
5545
|
+
staticAssigns.push({field, expr: colorLiteral(c)});
|
|
5546
|
+
} catch {
|
|
5547
|
+
dynAssigns.push({field, code: emitColorExpr(node, env)});
|
|
5548
|
+
}
|
|
5549
|
+
};
|
|
5550
|
+
|
|
5551
|
+
let onChangeFn = null;
|
|
5552
|
+
let knobImage = null; // static asset name
|
|
5553
|
+
for (const attr of el.openingElement.attributes) {
|
|
5554
|
+
if (attr.type !== 'JSXAttribute')
|
|
5555
|
+
throw aotError('AOT: spread props on <Dial> are not supported');
|
|
5556
|
+
const name = attr.name.name;
|
|
5557
|
+
if (name === 'style' || name === 'ref' || name === 'key') continue;
|
|
5558
|
+
const node = attrExpr(attr);
|
|
5559
|
+
if (
|
|
5560
|
+
(name === 'value' || name === 'valueStart') &&
|
|
5561
|
+
node?.type === 'Identifier' &&
|
|
5562
|
+
env.anims?.has(node.name)
|
|
5563
|
+
) {
|
|
5564
|
+
binds.push({
|
|
5565
|
+
cVar: env.anims.get(node.name).cVar,
|
|
5566
|
+
prop:
|
|
5567
|
+
name === 'value' ? 'ER_PROP_ARC_VALUE' : 'ER_PROP_ARC_VALUE_START',
|
|
5568
|
+
});
|
|
5569
|
+
} else if (DIAL_FLOAT_PROPS[name])
|
|
5570
|
+
numeric(DIAL_FLOAT_PROPS[name], node, true);
|
|
5571
|
+
else if (DIAL_INT_PROPS[name]) numeric(DIAL_INT_PROPS[name], node, false);
|
|
5572
|
+
else if (DIAL_COLOR_PROPS[name]) colour(DIAL_COLOR_PROPS[name], node);
|
|
5573
|
+
else if (DIAL_ENUM_PROPS[name]) {
|
|
5574
|
+
const {field, table} = DIAL_ENUM_PROPS[name];
|
|
5575
|
+
let tok = null;
|
|
5576
|
+
try {
|
|
5577
|
+
tok = evalStatic(node, scope);
|
|
5578
|
+
} catch {
|
|
5579
|
+
/* state-driven — handled below */
|
|
5580
|
+
}
|
|
5581
|
+
if (typeof tok === 'string') {
|
|
5582
|
+
if (!table[tok])
|
|
5583
|
+
throw aotError(
|
|
5584
|
+
`AOT: unsupported <Dial ${name}> "${tok}"`,
|
|
5585
|
+
`${name} must be one of: ${Object.keys(table).join(' / ')}.`,
|
|
5586
|
+
);
|
|
5587
|
+
staticAssigns.push({field, expr: table[tok]});
|
|
5588
|
+
} else {
|
|
5589
|
+
dynAssigns.push({
|
|
5590
|
+
field,
|
|
5591
|
+
code: `(uint8_t)(${emitEnumExpr(node, table, env)})`,
|
|
5592
|
+
});
|
|
5593
|
+
}
|
|
5594
|
+
} else if (name === 'adjustable' || name === 'range') {
|
|
5595
|
+
const field = name === 'range' ? 'arc_range' : 'arc_adjustable';
|
|
5596
|
+
try {
|
|
5597
|
+
staticAssigns.push({field, expr: evalStatic(node, scope) ? '1' : '0'});
|
|
5598
|
+
} catch {
|
|
5599
|
+
dynAssigns.push({
|
|
5600
|
+
field,
|
|
5601
|
+
code: `(uint8_t)((${emitExpr(node, env).code}) ? 1 : 0)`,
|
|
5602
|
+
});
|
|
5603
|
+
}
|
|
5604
|
+
} else if (name === 'knobImage') {
|
|
5605
|
+
knobImage = imageNameFromSource(node, env);
|
|
5606
|
+
if (knobImage == null)
|
|
5607
|
+
throw aotError(
|
|
5608
|
+
'AOT: <Dial knobImage> must resolve to a static asset name',
|
|
5609
|
+
"use an imported image (`import knob from './knob.png'` → knobImage={knob}) or a string asset name.",
|
|
5610
|
+
);
|
|
5611
|
+
const path = env.imageNames?.get(knobImage);
|
|
5612
|
+
if (path) out.images.set(knobImage, path);
|
|
5613
|
+
} else if (name === 'indicatorGradient') {
|
|
5614
|
+
// A gradient is usually applied only in SOME state (a thermostat ramps its band in AUTO and paints
|
|
5615
|
+
// it solid otherwise), so `cond ? {…} : null` is the common shape. The stops themselves are still
|
|
5616
|
+
// constant — only WHETHER they apply varies — so bake them and switch the stop COUNT at runtime:
|
|
5617
|
+
// the engine ignores a gradient with fewer than two stops and falls back to indicatorColor.
|
|
5618
|
+
let gradNode = node;
|
|
5619
|
+
let gradCond = null;
|
|
5620
|
+
if (node?.type === 'ConditionalExpression') {
|
|
5621
|
+
const nullish = n =>
|
|
5622
|
+
n?.type === 'NullLiteral' ||
|
|
5623
|
+
(n?.type === 'Identifier' && n.name === 'undefined');
|
|
5624
|
+
if (nullish(node.alternate)) {
|
|
5625
|
+
gradNode = node.consequent;
|
|
5626
|
+
gradCond = emitExpr(node.test, env).code;
|
|
5627
|
+
} else if (nullish(node.consequent)) {
|
|
5628
|
+
gradNode = node.alternate;
|
|
5629
|
+
gradCond = `!(${emitExpr(node.test, env).code})`;
|
|
5630
|
+
}
|
|
5631
|
+
}
|
|
5632
|
+
const g = evalStaticOrThrow(
|
|
5633
|
+
gradNode,
|
|
5634
|
+
scope,
|
|
5635
|
+
'AOT: <Dial indicatorGradient> must be a static object (optionally behind a ternary against null)',
|
|
5636
|
+
"indicatorGradient={{ type: 'conic', stops: [{ color: '#00f' }, { color: '#f00' }] }}, or " +
|
|
5637
|
+
'indicatorGradient={on ? {…} : null}',
|
|
5638
|
+
);
|
|
5639
|
+
const stops = Array.isArray(g?.stops) ? g.stops.slice(0, 4) : [];
|
|
5640
|
+
if (stops.length < 2)
|
|
5641
|
+
throw aotError(
|
|
5642
|
+
'AOT: <Dial indicatorGradient> needs at least 2 stops (max 4)',
|
|
5643
|
+
);
|
|
5644
|
+
staticAssigns.push({
|
|
5645
|
+
field: 'gradient_type',
|
|
5646
|
+
expr: g.type === 'radial' ? 'ER_GRADIENT_RADIAL' : 'ER_GRADIENT_CONIC',
|
|
5647
|
+
});
|
|
5648
|
+
if (gradCond)
|
|
5649
|
+
dynAssigns.push({
|
|
5650
|
+
field: 'gradient_stop_count',
|
|
5651
|
+
code: `(uint8_t)((${gradCond}) ? ${stops.length} : 0)`,
|
|
5652
|
+
});
|
|
5653
|
+
else
|
|
5654
|
+
staticAssigns.push({
|
|
5655
|
+
field: 'gradient_stop_count',
|
|
5656
|
+
expr: String(stops.length),
|
|
5657
|
+
});
|
|
5658
|
+
stops.forEach((st, i) => {
|
|
5659
|
+
const off =
|
|
5660
|
+
typeof st.offset === 'number' ? st.offset : i / (stops.length - 1);
|
|
5661
|
+
staticAssigns.push({
|
|
5662
|
+
field: `gradient_stops[${i}].color`,
|
|
5663
|
+
expr: colorLiteral(String(st.color)),
|
|
5664
|
+
});
|
|
5665
|
+
staticAssigns.push({
|
|
5666
|
+
field: `gradient_stops[${i}].position`,
|
|
5667
|
+
expr: floatLit(off),
|
|
5668
|
+
});
|
|
5669
|
+
});
|
|
5670
|
+
} else if (name === 'onChange') onChangeFn = node;
|
|
5671
|
+
else
|
|
5672
|
+
throw aotError(`AOT: <Dial> prop "${name}" is not supported`, SUPPORTED);
|
|
5673
|
+
}
|
|
5674
|
+
|
|
5675
|
+
const isDynamic = dynAssigns.length > 0;
|
|
5676
|
+
out.build.push(` ${v} = er_node_create(ER_NODE_ARC);`);
|
|
5677
|
+
if (isDynamic) {
|
|
5678
|
+
out.build.push(` s_${v} = ${v};`);
|
|
5679
|
+
out.handles.push(v);
|
|
5680
|
+
out.updates.push({
|
|
5681
|
+
v,
|
|
5682
|
+
styleAssigns: staticAssigns,
|
|
5683
|
+
text: null,
|
|
5684
|
+
dynAssigns,
|
|
5685
|
+
imageName: knobImage != null ? cstr(knobImage) : null,
|
|
5686
|
+
});
|
|
5687
|
+
} else {
|
|
5688
|
+
out.build.push(` er_props_default(&p);`);
|
|
5689
|
+
for (const a of staticAssigns)
|
|
5690
|
+
out.build.push(` p.${a.field} = ${a.expr};`);
|
|
5691
|
+
if (knobImage != null)
|
|
5692
|
+
out.build.push(
|
|
5693
|
+
` snprintf(p.image_name, sizeof(p.image_name), "%s", ${cstr(knobImage)});`,
|
|
5694
|
+
);
|
|
5695
|
+
out.build.push(` er_node_set_props(${v}, &p);`);
|
|
5696
|
+
}
|
|
5697
|
+
|
|
5698
|
+
// Animated bindings: style props plus an animated `value` (ER_PROP_ARC_VALUE).
|
|
5699
|
+
binds.forEach((b, i) => {
|
|
5700
|
+
if (b.interp) {
|
|
5701
|
+
const it = b.interp;
|
|
5702
|
+
out.build.push(
|
|
5703
|
+
` {`,
|
|
5704
|
+
` static const ERInterpolation interp_${v}_${i} = { { ${it.input.map(floatLit).join(', ')} }, { ${it.output.map(floatLit).join(', ')} }, ${it.input.length}, ${it.exLeft}, ${it.exRight} };`,
|
|
5705
|
+
` er_anim_value_bind_interpolated(${b.cVar}, ${v}, ${b.prop}, &interp_${v}_${i});`,
|
|
5706
|
+
` }`,
|
|
5707
|
+
);
|
|
5708
|
+
} else {
|
|
5709
|
+
out.build.push(` er_anim_value_bind(${b.cVar}, ${v}, ${b.prop});`);
|
|
5710
|
+
}
|
|
3550
5711
|
});
|
|
3551
|
-
return v;
|
|
3552
|
-
}
|
|
3553
|
-
|
|
3554
|
-
// ---------------------------------------------------------------------------------------------------
|
|
3555
|
-
// Node emitters — typed components. Each maps one JSX element to its engine node + props: the shared
|
|
3556
|
-
// helpers (emitRefBind, compileValueHandler) then Switch / TextInput / ActivityIndicator / Modal /
|
|
3557
|
-
// FlatList. The generic host node (View/Text/Pressable/Image/ScrollView) + the element dispatcher live
|
|
3558
|
-
// in the next section (emitNodeImpl).
|
|
3559
|
-
// ---------------------------------------------------------------------------------------------------
|
|
3560
5712
|
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
if (
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
:
|
|
3569
|
-
|
|
3570
|
-
out.build.push(` ${env.refs.get(e.name).cVar} = ${v};`);
|
|
3571
|
-
else
|
|
3572
|
-
throw new Error(
|
|
3573
|
-
'AOT: ref={…} must reference a node ref declared with useRef()',
|
|
5713
|
+
if (onChangeFn) {
|
|
5714
|
+
// A useCallback identifier resolves to its arrow, the same way the generic host-node event path does —
|
|
5715
|
+
// a dial's change handler is exactly the kind of thing an app wraps in useCallback.
|
|
5716
|
+
if (onChangeFn.type === 'Identifier' && env.callbacks?.has(onChangeFn.name))
|
|
5717
|
+
onChangeFn = env.callbacks.get(onChangeFn.name);
|
|
5718
|
+
if (!isFn(onChangeFn))
|
|
5719
|
+
throw aotError(
|
|
5720
|
+
'AOT: <Dial onChange> must be an inline function or a useCallback',
|
|
5721
|
+
'onChange={(v) => setValue(v)}',
|
|
3574
5722
|
);
|
|
5723
|
+
const handlerName = `er_handler_${out.handlers.length}`;
|
|
5724
|
+
out.handlers.push({
|
|
5725
|
+
name: handlerName,
|
|
5726
|
+
body: compileValueHandler(
|
|
5727
|
+
onChangeFn,
|
|
5728
|
+
'data->value',
|
|
5729
|
+
env,
|
|
5730
|
+
state,
|
|
5731
|
+
out,
|
|
5732
|
+
'float',
|
|
5733
|
+
'data->value_start',
|
|
5734
|
+
),
|
|
5735
|
+
});
|
|
5736
|
+
out.build.push(
|
|
5737
|
+
` er_event_set(${v}, ER_EVENT_VALUE_CHANGE, ${handlerName}, NULL);`,
|
|
5738
|
+
);
|
|
3575
5739
|
}
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
valueCode,
|
|
3582
|
-
env,
|
|
3583
|
-
state,
|
|
3584
|
-
out,
|
|
3585
|
-
cType = 'int',
|
|
3586
|
-
) {
|
|
3587
|
-
const param =
|
|
3588
|
-
fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
|
|
3589
|
-
const locals = new Map(env.locals);
|
|
3590
|
-
if (param) locals.set(param, {code: valueCode, cType});
|
|
3591
|
-
const ctx = {stateChanged: false, animIdx: 0, out};
|
|
3592
|
-
const body = fnNode.body;
|
|
3593
|
-
const list =
|
|
3594
|
-
body.type === 'BlockStatement'
|
|
3595
|
-
? body.body
|
|
3596
|
-
: [{type: 'ExpressionStatement', expression: body}];
|
|
3597
|
-
const stmts = compileStmts(list, {...env, locals}, state, ctx, ' ');
|
|
3598
|
-
if (ctx.stateChanged) stmts.push(' app_update();');
|
|
3599
|
-
return stmts;
|
|
5740
|
+
emitRefBind(v, el.openingElement, out, env);
|
|
5741
|
+
// Children lay out inside the dial's box like any View's (a centre readout), and with knob="child" the
|
|
5742
|
+
// engine moves the first one onto the value point.
|
|
5743
|
+
emitChildren(el.children, v, scope, out, env, state);
|
|
5744
|
+
return v;
|
|
3600
5745
|
}
|
|
3601
5746
|
|
|
3602
5747
|
/**
|
|
@@ -3612,9 +5757,7 @@ function emitSwitch(el, scope, out, env, state) {
|
|
|
3612
5757
|
scope,
|
|
3613
5758
|
env,
|
|
3614
5759
|
);
|
|
3615
|
-
const hasField = f =>
|
|
3616
|
-
staticAssigns.some(a => a.field === f) ||
|
|
3617
|
-
dynAssigns.some(a => a.field === f);
|
|
5760
|
+
const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
|
|
3618
5761
|
if (!hasField('width')) staticAssigns.push({field: 'width', expr: '51'});
|
|
3619
5762
|
if (!hasField('height')) staticAssigns.push({field: 'height', expr: '31'});
|
|
3620
5763
|
|
|
@@ -3664,7 +5807,7 @@ function emitSwitch(el, scope, out, env, state) {
|
|
|
3664
5807
|
} catch {
|
|
3665
5808
|
dynAssigns.push({
|
|
3666
5809
|
field: 'switch_value',
|
|
3667
|
-
code: `(uint8_t)((${emitExpr(valueNode, env)
|
|
5810
|
+
code: `(uint8_t)((${asCond(emitExpr(valueNode, env))}) ? 1 : 0)`,
|
|
3668
5811
|
});
|
|
3669
5812
|
}
|
|
3670
5813
|
}
|
|
@@ -3694,10 +5837,19 @@ function emitSwitch(el, scope, out, env, state) {
|
|
|
3694
5837
|
'controlled switch: <Switch value={on} onValueChange={(v) => setOn(v)} />',
|
|
3695
5838
|
);
|
|
3696
5839
|
const handlerName = `er_handler_${out.handlers.length}`;
|
|
3697
|
-
const toggled = `(!(${emitExpr(valueNode, env)
|
|
5840
|
+
const toggled = `(!(${asCond(emitExpr(valueNode, env))}))`; // the engine toggles on press → param is !value
|
|
3698
5841
|
out.handlers.push({
|
|
3699
5842
|
name: handlerName,
|
|
3700
|
-
body: compileValueHandler(
|
|
5843
|
+
body: compileValueHandler(
|
|
5844
|
+
onChangeFn,
|
|
5845
|
+
toggled,
|
|
5846
|
+
env,
|
|
5847
|
+
state,
|
|
5848
|
+
out,
|
|
5849
|
+
'int',
|
|
5850
|
+
null,
|
|
5851
|
+
true,
|
|
5852
|
+
),
|
|
3701
5853
|
});
|
|
3702
5854
|
out.build.push(
|
|
3703
5855
|
` er_event_set(${v}, ER_EVENT_PRESS, ${handlerName}, NULL);`,
|
|
@@ -3745,15 +5897,16 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
3745
5897
|
field: 'cursor_color',
|
|
3746
5898
|
expr: colorLiteral(String(evalStatic(node, scope))),
|
|
3747
5899
|
});
|
|
3748
|
-
else if (name === 'editable') {
|
|
5900
|
+
else if (name === 'editable' || name === 'secureTextEntry') {
|
|
5901
|
+
const field = name === 'editable' ? 'editable' : 'secure_text_entry';
|
|
3749
5902
|
try {
|
|
3750
5903
|
staticAssigns.push({
|
|
3751
|
-
field
|
|
5904
|
+
field,
|
|
3752
5905
|
expr: evalStatic(node, scope) ? '1' : '0',
|
|
3753
5906
|
});
|
|
3754
5907
|
} catch {
|
|
3755
5908
|
dynAssigns.push({
|
|
3756
|
-
field
|
|
5909
|
+
field,
|
|
3757
5910
|
code: `(uint8_t)((${emitExpr(node, env).code}) ? 1 : 0)`,
|
|
3758
5911
|
});
|
|
3759
5912
|
}
|
|
@@ -3761,7 +5914,6 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
3761
5914
|
[
|
|
3762
5915
|
'autoFocus',
|
|
3763
5916
|
'keyboardType',
|
|
3764
|
-
'secureTextEntry',
|
|
3765
5917
|
'maxLength',
|
|
3766
5918
|
'multiline',
|
|
3767
5919
|
'autoCapitalize',
|
|
@@ -3776,7 +5928,7 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
3776
5928
|
} else
|
|
3777
5929
|
throw aotError(
|
|
3778
5930
|
`AOT: <TextInput> prop "${name}" is not supported`,
|
|
3779
|
-
'supported props: value, onChangeText, placeholder, placeholderTextColor, cursorColor, editable, style.',
|
|
5931
|
+
'supported props: value, onChangeText, placeholder, placeholderTextColor, cursorColor, editable, secureTextEntry, style.',
|
|
3780
5932
|
);
|
|
3781
5933
|
}
|
|
3782
5934
|
|
|
@@ -3784,17 +5936,8 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
3784
5936
|
// state-driven value re-synced each app_update.
|
|
3785
5937
|
let text = null;
|
|
3786
5938
|
if (valueNode) {
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
text = {
|
|
3790
|
-
dynamic: false,
|
|
3791
|
-
format: (cv == null ? '' : String(cv)).replace(/%/g, '%%'),
|
|
3792
|
-
args: [],
|
|
3793
|
-
};
|
|
3794
|
-
} catch {
|
|
3795
|
-
const e = emitExpr(valueNode, env);
|
|
3796
|
-
text = {dynamic: true, format: printfSpec(e.cType), args: [e.code]};
|
|
3797
|
-
}
|
|
5939
|
+
const f = emitFormat(valueNode, env, scope);
|
|
5940
|
+
text = {dynamic: f.args.length > 0, format: f.format, args: f.args};
|
|
3798
5941
|
}
|
|
3799
5942
|
|
|
3800
5943
|
const isDynamic = dynAssigns.length > 0 || (text && text.dynamic);
|
|
@@ -3862,9 +6005,7 @@ function emitActivityIndicator(el, scope, out, env) {
|
|
|
3862
6005
|
scope,
|
|
3863
6006
|
env,
|
|
3864
6007
|
);
|
|
3865
|
-
const hasField = f =>
|
|
3866
|
-
staticAssigns.some(a => a.field === f) ||
|
|
3867
|
-
dynAssigns.some(a => a.field === f);
|
|
6008
|
+
const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
|
|
3868
6009
|
let size = 36;
|
|
3869
6010
|
for (const attr of el.openingElement.attributes) {
|
|
3870
6011
|
if (attr.type !== 'JSXAttribute')
|
|
@@ -3941,9 +6082,7 @@ function emitModal(el, scope, out, env, state) {
|
|
|
3941
6082
|
scope,
|
|
3942
6083
|
env,
|
|
3943
6084
|
);
|
|
3944
|
-
const hasField = f =>
|
|
3945
|
-
staticAssigns.some(a => a.field === f) ||
|
|
3946
|
-
dynAssigns.some(a => a.field === f);
|
|
6085
|
+
const hasField = f => styleWrites(staticAssigns, dynAssigns, f);
|
|
3947
6086
|
// Overlay defaults: absolute, fill the parent via four 0 insets (the robust "stretch" for an absolute
|
|
3948
6087
|
// node), centre the content. The user's style overrides any of these.
|
|
3949
6088
|
const DEFAULTS = [
|
|
@@ -4214,14 +6353,150 @@ function resolveImageAttrs(el, env, out) {
|
|
|
4214
6353
|
// ---------------------------------------------------------------------------------------------------
|
|
4215
6354
|
// Node emitter — the element dispatcher + the generic host node. emitNodeImpl is the entry point for
|
|
4216
6355
|
// every JSX element: it routes Svg / typed components / FlatList / components to their emitters above,
|
|
4217
|
-
// and handles the generic host nodes (View / Text / Pressable / Image / ScrollView)
|
|
6356
|
+
// and handles the generic host nodes (View / Text / Pressable / TouchableOpacity / Image / ScrollView)
|
|
6357
|
+
// itself — style,
|
|
4218
6358
|
// text, events, refs, children. emitNode wraps it with withLoc so a thrown AOT error gets a location.
|
|
4219
6359
|
// ---------------------------------------------------------------------------------------------------
|
|
4220
6360
|
|
|
6361
|
+
// The JS-only RN wrappers the package exports that this compiler cannot lower yet. Each is a fixed
|
|
6362
|
+
// rewrite over primitives the AOT DOES understand, so the fix is always to write that tree out — the
|
|
6363
|
+
// message says which one, because a stock "unknown element" here is actively misleading (the import
|
|
6364
|
+
// resolved, the simulator renders it, and the name is spelled right).
|
|
6365
|
+
const FLOW_A_ONLY_COMPONENTS = {
|
|
6366
|
+
Button:
|
|
6367
|
+
'<Pressable style={…} onPress={…}><Text style={…}>title</Text></Pressable>.',
|
|
6368
|
+
ImageBackground:
|
|
6369
|
+
"<View style={…}><Image source={…} style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0}} />…children…</View>.",
|
|
6370
|
+
SectionList:
|
|
6371
|
+
'<ScrollView> with the header element and a data.map(…) per section (a section is not one .map, which is why it has no lowering).',
|
|
6372
|
+
};
|
|
6373
|
+
|
|
6374
|
+
// <TouchableOpacity> is a Pressable node plus one synthetic animated value bound to its opacity:
|
|
6375
|
+
// press-in snaps it to activeOpacity, press-out fades it back to whatever the style asks for. Flow A
|
|
6376
|
+
// builds the same thing out of hooks (TouchableOpacity.js); lowering it here means the feedback runs on
|
|
6377
|
+
// the engine's native driver with no JS on the device at all.
|
|
6378
|
+
const TOUCHABLE_ACTIVE_OPACITY = 0.2; // RN's default
|
|
6379
|
+
const TOUCHABLE_RESTORE_MS = 250; // RN's fade-back; the dim itself lands with no ramp
|
|
6380
|
+
|
|
6381
|
+
/** The press events a <TouchableOpacity disabled> drops — RN presses none of them, and dims for none. */
|
|
6382
|
+
const PRESS_EVENTS = new Set([
|
|
6383
|
+
'onPress',
|
|
6384
|
+
'onLongPress',
|
|
6385
|
+
'onPressIn',
|
|
6386
|
+
'onPressOut',
|
|
6387
|
+
]);
|
|
6388
|
+
|
|
6389
|
+
/** A JSX element's named attribute, or undefined. */
|
|
6390
|
+
function namedAttr(openingElement, name) {
|
|
6391
|
+
return openingElement.attributes.find(
|
|
6392
|
+
a => a.type === 'JSXAttribute' && a.name && a.name.name === name,
|
|
6393
|
+
);
|
|
6394
|
+
}
|
|
6395
|
+
|
|
6396
|
+
/** True for `<TouchableOpacity disabled>` / `disabled={SOME_CONST}`. Must fold: `disabled` decides what
|
|
6397
|
+
* the build EMITS — the press handlers and the dim binding — so there is nothing left to decide at runtime. */
|
|
6398
|
+
function touchableIsDisabled(el, scope) {
|
|
6399
|
+
const attr = namedAttr(el.openingElement, 'disabled');
|
|
6400
|
+
if (!attr) return false;
|
|
6401
|
+
return !!evalStaticOrThrow(
|
|
6402
|
+
attrExpr(attr),
|
|
6403
|
+
scope,
|
|
6404
|
+
'AOT: <TouchableOpacity disabled> must be a compile-time constant',
|
|
6405
|
+
'a disabled one still renders — it lowers to a plain <Pressable>, children, layout and style intact — but its press handlers and its dim are not emitted at all, so the AOT has to know at build time. To gate on state, leave it enabled and return early in the handler (`onPress={() => { if (!ready) return; … }}`).',
|
|
6406
|
+
);
|
|
6407
|
+
}
|
|
6408
|
+
|
|
6409
|
+
/** A folded `activeOpacity` as a number in 0..1. Everything else is an error HERE, where the source line
|
|
6410
|
+
* is still in reach: it would otherwise reach floatLit and land in the generated C as a literal that
|
|
6411
|
+
* either does not compile (`NaNf`) or quietly means something the app never asked for — a bare
|
|
6412
|
+
* `activeOpacity` is `true`, so `1.0f`, which is no dim at all; `{false}` is an invisible one. */
|
|
6413
|
+
function opacityLiteralOrThrow(value, attr) {
|
|
6414
|
+
if (
|
|
6415
|
+
typeof value !== 'number' ||
|
|
6416
|
+
!Number.isFinite(value) ||
|
|
6417
|
+
value < 0 ||
|
|
6418
|
+
value > 1
|
|
6419
|
+
) {
|
|
6420
|
+
// JSON.stringify turns NaN into the STRING "null", which reads as a different mistake entirely.
|
|
6421
|
+
const shown =
|
|
6422
|
+
typeof value === 'number'
|
|
6423
|
+
? String(value)
|
|
6424
|
+
: (JSON.stringify(value) ?? String(value));
|
|
6425
|
+
const e = aotError(
|
|
6426
|
+
`AOT: <TouchableOpacity activeOpacity> must be a number between 0 and 1 (got ${shown})`,
|
|
6427
|
+
'it is the opacity the node dims to while held — 0 is invisible, 1 is no dim at all. RN defaults it to 0.2.',
|
|
6428
|
+
);
|
|
6429
|
+
if (attr.loc) e.aotLoc = attr.loc.start;
|
|
6430
|
+
throw e;
|
|
6431
|
+
}
|
|
6432
|
+
return value;
|
|
6433
|
+
}
|
|
6434
|
+
|
|
6435
|
+
/**
|
|
6436
|
+
* Creates a <TouchableOpacity>'s animated value and binds it to the node's opacity. Returns the two
|
|
6437
|
+
* fades as handler-body lines, for the event loop to fold into its press handlers.
|
|
6438
|
+
*/
|
|
6439
|
+
function touchablePressFades(
|
|
6440
|
+
el,
|
|
6441
|
+
v,
|
|
6442
|
+
staticAssigns,
|
|
6443
|
+
dynAssigns,
|
|
6444
|
+
binds,
|
|
6445
|
+
out,
|
|
6446
|
+
scope,
|
|
6447
|
+
) {
|
|
6448
|
+
const animatedOpacity = binds.some(b => b.prop === 'ER_PROP_OPACITY');
|
|
6449
|
+
if (animatedOpacity || dynAssigns.some(a => a.field === 'opacity'))
|
|
6450
|
+
throw aotError(
|
|
6451
|
+
`AOT: <TouchableOpacity> cannot take ${animatedOpacity ? 'an Animated' : 'a state-driven'} opacity`,
|
|
6452
|
+
"the press feedback owns this node's opacity — a second writer does not blend with it, it races it. To animate opacity yourself, use <Pressable>: the dim is just onPressIn/onPressOut driving an Animated.Value (see TouchableOpacity.js for the whole of it).",
|
|
6453
|
+
);
|
|
6454
|
+
// lowerStyle has already scaled a static opacity to 0–255, and that byte IS the resting value. It is
|
|
6455
|
+
// NaN for a style opacity that was not a number — which lowerStyle emits as a `p.opacity = NaN` the C
|
|
6456
|
+
// compiler rejects on its own, so leave that error to it rather than adding a second bad literal here.
|
|
6457
|
+
const restingByte = staticAssigns.find(a => a.field === 'opacity');
|
|
6458
|
+
const restingRaw = restingByte ? Number(restingByte.expr) / 255 : 1;
|
|
6459
|
+
const resting = Number.isFinite(restingRaw) ? restingRaw : 1;
|
|
6460
|
+
|
|
6461
|
+
const activeAttr = namedAttr(el.openingElement, 'activeOpacity');
|
|
6462
|
+
const active = activeAttr
|
|
6463
|
+
? opacityLiteralOrThrow(
|
|
6464
|
+
evalStaticOrThrow(
|
|
6465
|
+
attrExpr(activeAttr),
|
|
6466
|
+
scope,
|
|
6467
|
+
'AOT: <TouchableOpacity activeOpacity> must be a compile-time constant',
|
|
6468
|
+
'the dim target is baked into the generated handler, so it cannot come from state.',
|
|
6469
|
+
),
|
|
6470
|
+
activeAttr,
|
|
6471
|
+
)
|
|
6472
|
+
: TOUCHABLE_ACTIVE_OPACITY;
|
|
6473
|
+
|
|
6474
|
+
const cVar = `s_av_press_${v}`;
|
|
6475
|
+
out.childAnims.push({cVar, initCode: floatLit(resting)});
|
|
6476
|
+
out.build.push(` er_anim_value_bind(${cVar}, ${v}, ER_PROP_OPACITY);`);
|
|
6477
|
+
|
|
6478
|
+
const fade = (to, ms) => [
|
|
6479
|
+
' {',
|
|
6480
|
+
' ERAnimConfig cfg;',
|
|
6481
|
+
' memset(&cfg, 0, sizeof(cfg));',
|
|
6482
|
+
' cfg.type = ER_ANIM_TIMING;',
|
|
6483
|
+
` cfg.duration_ms = ${ms};`,
|
|
6484
|
+
' cfg.easing = ER_EASE_QUAD_IN_OUT;',
|
|
6485
|
+
` er_anim_value_animate(${cVar}, ${floatLit(to)}, &cfg);`,
|
|
6486
|
+
' }',
|
|
6487
|
+
];
|
|
6488
|
+
return {
|
|
6489
|
+
onPressIn: fade(active, 0),
|
|
6490
|
+
onPressOut: fade(resting, TOUCHABLE_RESTORE_MS),
|
|
6491
|
+
};
|
|
6492
|
+
}
|
|
6493
|
+
|
|
4221
6494
|
function emitNodeImpl(el, scope, out, env, state, opts = {}) {
|
|
6495
|
+
el = omitUndefinedAttrs(el, scope, env);
|
|
4222
6496
|
const tag = resolveTag(el.openingElement);
|
|
4223
6497
|
if (tag === 'Svg') return emitSvg(el, scope, out, env, state, opts);
|
|
4224
6498
|
if (tag === 'Switch') return emitSwitch(el, scope, out, env, state);
|
|
6499
|
+
if (tag === 'Dial') return emitDial(el, scope, out, env, state);
|
|
4225
6500
|
if (tag === 'TextInput') return emitTextInput(el, scope, out, env, state);
|
|
4226
6501
|
if (tag === 'ActivityIndicator')
|
|
4227
6502
|
return emitActivityIndicator(el, scope, out, env);
|
|
@@ -4231,23 +6506,49 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
|
|
|
4231
6506
|
if (!nodeType) {
|
|
4232
6507
|
if (out.components.has(tag))
|
|
4233
6508
|
return emitComponent(el, scope, out, env, state, opts);
|
|
6509
|
+
// Exported by the package and rendering fine in the simulator, but with no lowering here yet — so
|
|
6510
|
+
// say that, instead of "unknown element", which reads like a typo and sends people hunting for one.
|
|
6511
|
+
const flowAOnly = FLOW_A_ONLY_COMPONENTS[tag];
|
|
6512
|
+
if (flowAOnly)
|
|
6513
|
+
throw aotError(
|
|
6514
|
+
`AOT: <${tag}> is not supported in Flow B yet`,
|
|
6515
|
+
`it renders in Flow A (the simulator and the QuickJS runtime) but the AOT has no lowering for it. Write it out by hand for the device build: ${flowAOnly}`,
|
|
6516
|
+
);
|
|
4234
6517
|
throw aotError(
|
|
4235
6518
|
`AOT: unknown element <${tag}> (not a built-in or a component in this file)`,
|
|
4236
|
-
`<${tag}> must be a built-in (View / Text / Pressable / Image / ScrollView / Svg + shapes / Animated.*) or a function component defined in THIS file. Check the import/spelling, or define the component here.`,
|
|
6519
|
+
`<${tag}> must be a built-in (View / Text / Pressable / TouchableOpacity / Image / ScrollView / Svg + shapes / Animated.*) or a function component defined in THIS file. Check the import/spelling, or define the component here.`,
|
|
4237
6520
|
);
|
|
4238
6521
|
}
|
|
4239
6522
|
|
|
6523
|
+
// A <TouchableOpacity disabled> lowers to a plain Pressable node — children, layout and style all
|
|
6524
|
+
// intact — with no press handlers and no animated value to dim it with. That is RN's `disabled`, and
|
|
6525
|
+
// it is the whole of it here: the engine has no such node flag, so a node left holding onPress would
|
|
6526
|
+
// still fire, and one left holding the binding would still dim.
|
|
6527
|
+
const touchableOff =
|
|
6528
|
+
tag === 'TouchableOpacity' && touchableIsDisabled(el, scope);
|
|
6529
|
+
|
|
4240
6530
|
// Spread attributes on a host element (`<View {...props} />`) aren't lowered — the style/event loops
|
|
4241
|
-
// below only read named JSXAttributes, so a spread would be SILENTLY dropped.
|
|
4242
|
-
//
|
|
4243
|
-
//
|
|
4244
|
-
|
|
4245
|
-
|
|
4246
|
-
)
|
|
4247
|
-
|
|
6531
|
+
// below only read named JSXAttributes, so a spread would be SILENTLY dropped. The one exception is
|
|
6532
|
+
// `{...pan.panHandlers}`, which the AOT understands as a whole (see emitPanResponder); everything else
|
|
6533
|
+
// is rejected explicitly (the typed components — Switch/TextInput/Modal/… — already throw on spreads).
|
|
6534
|
+
// Pin the location to the spread itself, not the whole element, for a precise code-frame.
|
|
6535
|
+
const panSpreads = [];
|
|
6536
|
+
for (const spread of el.openingElement.attributes) {
|
|
6537
|
+
if (spread.type !== 'JSXSpreadAttribute') continue;
|
|
6538
|
+
let pan;
|
|
6539
|
+
try {
|
|
6540
|
+
pan = panSpreadTarget(spread.argument, env);
|
|
6541
|
+
} catch (e) {
|
|
6542
|
+
if (spread.loc && !e.aotLoc) e.aotLoc = spread.loc.start;
|
|
6543
|
+
throw e;
|
|
6544
|
+
}
|
|
6545
|
+
if (pan) {
|
|
6546
|
+
panSpreads.push(pan);
|
|
6547
|
+
continue;
|
|
6548
|
+
}
|
|
4248
6549
|
const e = aotError(
|
|
4249
6550
|
`AOT: a spread {...} on <${tag}> is not supported`,
|
|
4250
|
-
`list each prop explicitly (e.g. style={…} onPress={…}).
|
|
6551
|
+
`list each prop explicitly (e.g. style={…} onPress={…}). The only spread a host element understands is a PanResponder's ({...pan.panHandlers}); otherwise spread props are supported on a function component instance whose spread object folds to a compile-time constant.`,
|
|
4251
6552
|
);
|
|
4252
6553
|
if (spread.loc) e.aotLoc = spread.loc.start;
|
|
4253
6554
|
throw e;
|
|
@@ -4305,6 +6606,29 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
|
|
|
4305
6606
|
}
|
|
4306
6607
|
}
|
|
4307
6608
|
|
|
6609
|
+
// `delayLongPress` is the hold time before onLongPress fires (RN's prop, same 500 ms default). It has
|
|
6610
|
+
// to fold: the value is baked into the node's props at build time. 0 is the engine's "no preference"
|
|
6611
|
+
// sentinel, so an app asking for 0 gets 1 ms — the next tick, which is what RN's setTimeout(0) means.
|
|
6612
|
+
const delayAttr = namedAttr(el.openingElement, 'delayLongPress');
|
|
6613
|
+
if (delayAttr) {
|
|
6614
|
+
const bad = aotError(
|
|
6615
|
+
`AOT: <${tag} delayLongPress> must fold to a number`,
|
|
6616
|
+
'pass a literal or a module-level constant in milliseconds, e.g. delayLongPress={800}.',
|
|
6617
|
+
);
|
|
6618
|
+
if (delayAttr.value == null) throw bad;
|
|
6619
|
+
let ms;
|
|
6620
|
+
try {
|
|
6621
|
+
ms = Number(evalStatic(attrExpr(delayAttr), scope));
|
|
6622
|
+
} catch {
|
|
6623
|
+
throw bad;
|
|
6624
|
+
}
|
|
6625
|
+
if (!Number.isFinite(ms)) throw bad;
|
|
6626
|
+
staticAssigns.push({
|
|
6627
|
+
field: 'long_press_ms',
|
|
6628
|
+
expr: String(Math.min(65535, Math.max(1, Math.round(ms)))),
|
|
6629
|
+
});
|
|
6630
|
+
}
|
|
6631
|
+
|
|
4308
6632
|
// `displayCode` toggles show/hide for a state-driven conditional: the node is always built, its
|
|
4309
6633
|
// `display` flips between flex and none in app_update (joining any state-driven style assigns).
|
|
4310
6634
|
// Pushed last so an enclosing conditional beats the element's own visible/display — app_update
|
|
@@ -4378,12 +6702,20 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
|
|
|
4378
6702
|
}
|
|
4379
6703
|
});
|
|
4380
6704
|
|
|
6705
|
+
// <TouchableOpacity>'s own opacity binding, on top of any the style asked for.
|
|
6706
|
+
const pressFades =
|
|
6707
|
+
tag === 'TouchableOpacity' && !touchableOff
|
|
6708
|
+
? touchablePressFades(el, v, staticAssigns, dynAssigns, binds, out, scope)
|
|
6709
|
+
: null;
|
|
6710
|
+
|
|
4381
6711
|
emitRefBind(v, el.openingElement, out, env);
|
|
4382
6712
|
|
|
6713
|
+
const fadesWired = new Set();
|
|
4383
6714
|
for (const attr of el.openingElement.attributes) {
|
|
4384
6715
|
if (attr.type !== 'JSXAttribute') continue;
|
|
4385
6716
|
const evt = EVENT_TYPES[attr.name.name];
|
|
4386
6717
|
if (!evt) continue;
|
|
6718
|
+
if (touchableOff && PRESS_EVENTS.has(attr.name.name)) continue;
|
|
4387
6719
|
const fn = attrExpr(attr);
|
|
4388
6720
|
let handlerName;
|
|
4389
6721
|
if (fn.type === 'Identifier' && env.callbacks?.has(fn.name)) {
|
|
@@ -4421,12 +6753,66 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
|
|
|
4421
6753
|
`pass an inline arrow (onPress={() => setX(…)}), a useCallback identifier, or a function prop received by this component.`,
|
|
4422
6754
|
);
|
|
4423
6755
|
}
|
|
6756
|
+
// The app's own press-in/out on a <TouchableOpacity>: wrap it rather than prepend the fade to its
|
|
6757
|
+
// body, which for a shared useCallback handler would dim every OTHER element using it too.
|
|
6758
|
+
const fade = pressFades?.[attr.name.name];
|
|
6759
|
+
if (fade) {
|
|
6760
|
+
const wrapped = `er_handler_${out.handlers.length}`;
|
|
6761
|
+
out.handlers.push({
|
|
6762
|
+
name: wrapped,
|
|
6763
|
+
body: [...fade, ` ${handlerName}(node, data, user_data);`],
|
|
6764
|
+
});
|
|
6765
|
+
handlerName = wrapped;
|
|
6766
|
+
fadesWired.add(attr.name.name);
|
|
6767
|
+
}
|
|
4424
6768
|
out.build.push(` er_event_set(${v}, ${evt}, ${handlerName}, NULL);`);
|
|
4425
6769
|
}
|
|
4426
6770
|
|
|
6771
|
+
// Whichever end of the press the app did not handle itself is the fade on its own.
|
|
6772
|
+
if (pressFades) {
|
|
6773
|
+
for (const key of ['onPressIn', 'onPressOut']) {
|
|
6774
|
+
if (fadesWired.has(key)) continue;
|
|
6775
|
+
const name = `er_handler_${out.handlers.length}`;
|
|
6776
|
+
out.handlers.push({name, body: pressFades[key]});
|
|
6777
|
+
out.build.push(
|
|
6778
|
+
` er_event_set(${v}, ${EVENT_TYPES[key]}, ${name}, NULL);`,
|
|
6779
|
+
);
|
|
6780
|
+
}
|
|
6781
|
+
}
|
|
6782
|
+
|
|
6783
|
+
for (const pan of panSpreads) emitPanResponder(pan, v, out, env, state);
|
|
6784
|
+
|
|
4427
6785
|
if (tag !== 'Text') emitChildren(el.children, v, scope, out, env, state);
|
|
4428
6786
|
return v;
|
|
4429
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
|
+
|
|
4430
6816
|
const emitNode = withLoc(emitNodeImpl);
|
|
4431
6817
|
|
|
4432
6818
|
// ---------------------------------------------------------------------------------------------------
|
|
@@ -4656,6 +7042,93 @@ function stripTypeScript(root) {
|
|
|
4656
7042
|
return root;
|
|
4657
7043
|
}
|
|
4658
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
|
+
|
|
4659
7132
|
/** Parse an app entry to a JS+JSX AST, transparently stripping TypeScript when the entry is .ts/.tsx. */
|
|
4660
7133
|
function parseApp(src, opts = {}) {
|
|
4661
7134
|
const ts = isTsEntry(opts);
|
|
@@ -4668,10 +7141,15 @@ function parseApp(src, opts = {}) {
|
|
|
4668
7141
|
* Compiles a Flow B app's JSX (or TSX) source to C.
|
|
4669
7142
|
* @param {string} src The App.jsx/App.tsx source text.
|
|
4670
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.
|
|
4671
7147
|
* @returns {{c: string, h: string, nodes: number, state: number, handlers: number, updates: number}}
|
|
4672
7148
|
*/
|
|
4673
|
-
function compileSourceImpl(src, demo
|
|
7149
|
+
function compileSourceImpl(src, demo, opts, wide, found) {
|
|
4674
7150
|
const ast = parseApp(src, opts);
|
|
7151
|
+
normalizeUndefined(ast);
|
|
7152
|
+
const shadowedClock = findShadowedClockCalls(ast);
|
|
4675
7153
|
|
|
4676
7154
|
const screen = opts.screen ?? {width: SCREEN_W, height: SCREEN_H};
|
|
4677
7155
|
// Image imports first, so their asset-name strings seed the module scope BEFORE its consts fold (a const
|
|
@@ -4682,27 +7160,38 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4682
7160
|
[...imageImports].map(([local, imp]) => [local, imp.name]),
|
|
4683
7161
|
);
|
|
4684
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};
|
|
4685
7166
|
const component = findComponent(ast.program);
|
|
4686
7167
|
// Fold statically-derived component-local consts (e.g. `const compact = screen.width < 400`) into the
|
|
4687
7168
|
// const scope, so responsive `if` branches and styles can switch on them at compile time. Dynamic consts
|
|
4688
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];
|
|
4689
7173
|
for (const stmt of component.body.body) {
|
|
4690
7174
|
if (stmt.type !== 'VariableDeclaration' || stmt.kind !== 'const') continue;
|
|
4691
7175
|
for (const decl of stmt.declarations) {
|
|
4692
|
-
if (decl.id.type !== 'Identifier' || !decl.init
|
|
4693
|
-
continue;
|
|
7176
|
+
if (decl.id.type !== 'Identifier' || !decl.init) continue;
|
|
4694
7177
|
try {
|
|
4695
|
-
scope[decl.id.name] = evalStatic(decl.init, scope);
|
|
7178
|
+
scope[decl.id.name] = evalStatic(decl.init, withUndefined(scope));
|
|
4696
7179
|
} catch {
|
|
4697
|
-
|
|
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];
|
|
4698
7184
|
}
|
|
4699
7185
|
}
|
|
4700
7186
|
}
|
|
4701
|
-
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];
|
|
4702
7189
|
const rootJSX = findReturnJSX(component.body, scope);
|
|
4703
7190
|
|
|
4704
7191
|
const anims = collectAnims(component.body, scope);
|
|
4705
|
-
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];
|
|
7194
|
+
const pans = collectPanResponders(component.body);
|
|
4706
7195
|
const callbacks = collectCallbacks(component.body);
|
|
4707
7196
|
const memos = collectMemos(component.body);
|
|
4708
7197
|
const helpers = collectHelpers(component.body, ast.program);
|
|
@@ -4713,13 +7202,18 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4713
7202
|
state: state.byName,
|
|
4714
7203
|
locals: new Map(),
|
|
4715
7204
|
consts: scope,
|
|
7205
|
+
moduleConsts, // what an inlined child component sees (see emitComponent)
|
|
4716
7206
|
anims,
|
|
4717
7207
|
refs,
|
|
7208
|
+
pans,
|
|
4718
7209
|
callbacks,
|
|
4719
7210
|
helpers,
|
|
4720
7211
|
imageNames,
|
|
4721
7212
|
svgImports,
|
|
4722
7213
|
svgArtifacts: opts.svgArtifacts || {},
|
|
7214
|
+
wide,
|
|
7215
|
+
found,
|
|
7216
|
+
shadowedClock,
|
|
4723
7217
|
};
|
|
4724
7218
|
// Resolve memos in declaration order: constant-fold into the const scope when possible, else register a
|
|
4725
7219
|
// derived C expression in locals so each reference inlines it (the AOT has no per-render cache — the dep
|
|
@@ -4728,8 +7222,13 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4728
7222
|
try {
|
|
4729
7223
|
scope[name] = evalStatic(expr, scope);
|
|
4730
7224
|
} catch {
|
|
4731
|
-
const e =
|
|
4732
|
-
env.locals.set(name, {
|
|
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
|
|
4733
7232
|
}
|
|
4734
7233
|
}
|
|
4735
7234
|
const out = {
|
|
@@ -4763,6 +7262,9 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4763
7262
|
effectFns: [],
|
|
4764
7263
|
effectDecls: [],
|
|
4765
7264
|
depEffects: [],
|
|
7265
|
+
panN: 0,
|
|
7266
|
+
panDecls: [],
|
|
7267
|
+
queries: [],
|
|
4766
7268
|
};
|
|
4767
7269
|
compileKeyboardConfig(ast.program, out); // module-level setKeyboardConfig({...}) → static ERKeyboardConfig
|
|
4768
7270
|
const appTop = emitNode(rootJSX, scope, out, env, state);
|
|
@@ -4792,7 +7294,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4792
7294
|
? ` char ${f.key}[${LIST_STR_CAP}];`
|
|
4793
7295
|
: ` ${f.kind} ${f.key};`;
|
|
4794
7296
|
const itemInit = (item, struct) =>
|
|
4795
|
-
`{ ${struct.fields.map(f => (f.kind === 'string' ? cstr(String(item[f.key] ?? '')) : f.kind === 'float' ?
|
|
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(', ')} }`;
|
|
4796
7298
|
const listBlocks = listRecords
|
|
4797
7299
|
.map(
|
|
4798
7300
|
s =>
|
|
@@ -4804,7 +7306,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4804
7306
|
const scalarFieldDecl = s =>
|
|
4805
7307
|
s.cType === 'string'
|
|
4806
7308
|
? ` char ${s.cField}[${LIST_STR_CAP}];`
|
|
4807
|
-
: ` ${s.cType
|
|
7309
|
+
: ` ${cScalarType(s.cType)} ${s.cField};`;
|
|
4808
7310
|
const scalarBlock = scalarRecords.length
|
|
4809
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`
|
|
4810
7312
|
: '';
|
|
@@ -4813,8 +7315,14 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4813
7315
|
const handleDecls = out.handles.map(v => `static ERNode* s_${v};`).join('\n');
|
|
4814
7316
|
|
|
4815
7317
|
// Value refs — a plain mutable static each (escape-hatch state that does not trigger a re-render).
|
|
7318
|
+
// Refs the emitted C never touches (e.g. a `useRef(null)` that only holds a JS value) declare nothing,
|
|
7319
|
+
// so consumer builds don't warn about an unused static.
|
|
4816
7320
|
const refDecls = [...refs.values(), ...out.childRefs]
|
|
4817
|
-
.
|
|
7321
|
+
.filter(r => r.used)
|
|
7322
|
+
.map(
|
|
7323
|
+
r =>
|
|
7324
|
+
`static ${r.kind === 'value' ? cScalarType(r.cType) : r.cType} ${r.cVar} = ${r.initCode};`,
|
|
7325
|
+
)
|
|
4818
7326
|
.join('\n');
|
|
4819
7327
|
|
|
4820
7328
|
// Baked vector op-tapes + paint tables (static <Svg> geometry), emitted at file scope.
|
|
@@ -4835,6 +7343,18 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4835
7343
|
out.updates.length > 0 ||
|
|
4836
7344
|
out.svgUpdates.length > 0 ||
|
|
4837
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
|
+
}
|
|
4838
7358
|
const updateBlock = (() => {
|
|
4839
7359
|
if (!hasUpdate) return '';
|
|
4840
7360
|
const lines = ['static void app_update(void)', '{'];
|
|
@@ -4877,6 +7397,16 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4877
7397
|
return lines.join('\n');
|
|
4878
7398
|
})();
|
|
4879
7399
|
|
|
7400
|
+
// PanResponder gesture state (one small block per responder) + the should-set predicates, which are
|
|
7401
|
+
// bool-returning callbacks the engine calls during negotiation rather than ordinary event handlers.
|
|
7402
|
+
const panDeclBlock = out.panDecls.join('\n');
|
|
7403
|
+
const queryDefs = out.queries
|
|
7404
|
+
.map(
|
|
7405
|
+
q =>
|
|
7406
|
+
`static bool ${q.name}(ERNode* node, const EREventData* data, void* user_data)\n{\n (void)node;\n (void)data;\n (void)user_data;\n return ${q.expr};\n}`,
|
|
7407
|
+
)
|
|
7408
|
+
.join('\n\n');
|
|
7409
|
+
|
|
4880
7410
|
const handlerDefs = out.handlers
|
|
4881
7411
|
.map(
|
|
4882
7412
|
h =>
|
|
@@ -4895,8 +7425,9 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
4895
7425
|
.join('\n\n');
|
|
4896
7426
|
|
|
4897
7427
|
// setInterval/setTimeout → a small fixed timer table advanced by er_app_tick(dt) (the host calls it each
|
|
4898
|
-
// frame). The table +
|
|
4899
|
-
//
|
|
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.
|
|
4900
7431
|
const timerTableBlock = out.usesTimers
|
|
4901
7432
|
? `#include <stdbool.h>
|
|
4902
7433
|
|
|
@@ -4908,12 +7439,15 @@ typedef struct
|
|
|
4908
7439
|
{
|
|
4909
7440
|
int interval_ms;
|
|
4910
7441
|
int remaining_ms;
|
|
7442
|
+
int gen;
|
|
4911
7443
|
bool repeat;
|
|
4912
7444
|
bool active;
|
|
4913
7445
|
void (*fn)(void);
|
|
4914
7446
|
} ErTimer;
|
|
4915
7447
|
static ErTimer s_timers[ER_AOT_MAX_TIMERS];
|
|
4916
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. */
|
|
4917
7451
|
static int er_timer_add(int ms, bool repeat, void (*fn)(void))
|
|
4918
7452
|
{
|
|
4919
7453
|
for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
|
|
@@ -4922,21 +7456,14 @@ static int er_timer_add(int ms, bool repeat, void (*fn)(void))
|
|
|
4922
7456
|
{
|
|
4923
7457
|
s_timers[i].interval_ms = ms < 1 ? 1 : ms;
|
|
4924
7458
|
s_timers[i].remaining_ms = s_timers[i].interval_ms;
|
|
7459
|
+
s_timers[i].gen = (s_timers[i].gen + 1) & 0xFFFF;
|
|
4925
7460
|
s_timers[i].repeat = repeat;
|
|
4926
7461
|
s_timers[i].active = true;
|
|
4927
7462
|
s_timers[i].fn = fn;
|
|
4928
|
-
return i;
|
|
7463
|
+
return (s_timers[i].gen * ER_AOT_MAX_TIMERS) + i;
|
|
4929
7464
|
}
|
|
4930
7465
|
}
|
|
4931
7466
|
return -1; /* table full (raise ER_AOT_MAX_TIMERS) */
|
|
4932
|
-
}
|
|
4933
|
-
|
|
4934
|
-
static void er_timer_clear(int id)
|
|
4935
|
-
{
|
|
4936
|
-
if (id >= 0 && id < ER_AOT_MAX_TIMERS)
|
|
4937
|
-
{
|
|
4938
|
-
s_timers[id].active = false;
|
|
4939
|
-
}
|
|
4940
7467
|
}`
|
|
4941
7468
|
: '';
|
|
4942
7469
|
|
|
@@ -4962,10 +7489,15 @@ static void er_timer_clear(int id)
|
|
|
4962
7489
|
)
|
|
4963
7490
|
.join('\n\n');
|
|
4964
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
|
+
: '';
|
|
4965
7497
|
const appTickFn = out.usesTimers
|
|
4966
7498
|
? `void er_app_tick(int dt_ms)
|
|
4967
7499
|
{
|
|
4968
|
-
for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
|
|
7500
|
+
${wallClockRefresh} for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
|
|
4969
7501
|
{
|
|
4970
7502
|
if (!s_timers[i].active)
|
|
4971
7503
|
{
|
|
@@ -4994,7 +7526,7 @@ static void er_timer_clear(int id)
|
|
|
4994
7526
|
}
|
|
4995
7527
|
}
|
|
4996
7528
|
}`
|
|
4997
|
-
: `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}}`;
|
|
4998
7530
|
|
|
4999
7531
|
const mountEffectsBlock = out.mountEffects.length
|
|
5000
7532
|
? '\n /* useEffect(fn, []) — run once on mount. */\n' +
|
|
@@ -5002,16 +7534,59 @@ static void er_timer_clear(int id)
|
|
|
5002
7534
|
'\n'
|
|
5003
7535
|
: '';
|
|
5004
7536
|
|
|
5005
|
-
//
|
|
7537
|
+
// app_round_dim() when a state-driven style value has to be snapped to a whole pixel at runtime.
|
|
7538
|
+
const usesDimRound = /\bapp_round_dim\(/.test(
|
|
7539
|
+
[
|
|
7540
|
+
updateBlock,
|
|
7541
|
+
handlerDefs,
|
|
7542
|
+
queryDefs,
|
|
7543
|
+
effectFnDefs,
|
|
7544
|
+
animCbDefs,
|
|
7545
|
+
timerFnDefs,
|
|
7546
|
+
out.mountEffects.join('\n'),
|
|
7547
|
+
out.build.join('\n'),
|
|
7548
|
+
].join('\n'),
|
|
7549
|
+
);
|
|
7550
|
+
const dimRoundBlock = usesDimRound
|
|
7551
|
+
? `
|
|
7552
|
+
/* Snaps a state-driven style value to a whole pixel the way JavaScript's Math.round does — floor(x + 0.5),
|
|
7553
|
+
halves UP rather than away from zero. ERProps dimensions are int16 and a plain cast would truncate toward
|
|
7554
|
+
zero, which is how the two flows once laid the same app out a pixel apart. Values known at compile time
|
|
7555
|
+
are folded with Math.round; this is that rule's runtime twin, and Flow A's bridge applies the same one. */
|
|
7556
|
+
static int16_t app_round_dim(double v)
|
|
7557
|
+
{
|
|
7558
|
+
/* NaN compares false against everything, so it would slip past both clamps into an undefined cast. */
|
|
7559
|
+
if (v != v)
|
|
7560
|
+
{
|
|
7561
|
+
return 0;
|
|
7562
|
+
}
|
|
7563
|
+
if (v < -32768.0)
|
|
7564
|
+
{
|
|
7565
|
+
return -32768;
|
|
7566
|
+
}
|
|
7567
|
+
if (v > 32767.0)
|
|
7568
|
+
{
|
|
7569
|
+
return 32767;
|
|
7570
|
+
}
|
|
7571
|
+
const double r = v + 0.5;
|
|
7572
|
+
const int32_t t = (int32_t)r; /* truncates toward zero */
|
|
7573
|
+
return (int16_t)(((double)t > r) ? t - 1 : t);
|
|
7574
|
+
}
|
|
7575
|
+
`
|
|
7576
|
+
: '';
|
|
7577
|
+
|
|
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.
|
|
5006
7580
|
const usesMath =
|
|
5007
7581
|
out.needsMath ||
|
|
5008
|
-
/\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(
|
|
5009
7583
|
[
|
|
5010
7584
|
stateBlock,
|
|
5011
7585
|
refDecls,
|
|
5012
7586
|
vectorBuilderBlock,
|
|
5013
7587
|
updateBlock,
|
|
5014
7588
|
handlerDefs,
|
|
7589
|
+
queryDefs,
|
|
5015
7590
|
animCbDefs,
|
|
5016
7591
|
timerFnDefs,
|
|
5017
7592
|
out.mountEffects.join('\n'),
|
|
@@ -5022,19 +7597,322 @@ static void er_timer_clear(int id)
|
|
|
5022
7597
|
// dependent nodes via app_update() (which the host also gets for free — it is the same refresh a JS
|
|
5023
7598
|
// setter would trigger). The host calls e.g. er_app_set_steps(count) once per frame.
|
|
5024
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
|
+
);
|
|
5025
7605
|
const hostSettersBlock = hostRecords
|
|
5026
7606
|
.map(
|
|
5027
7607
|
s =>
|
|
5028
|
-
`void er_app_set_${s.name}(${s.cType
|
|
7608
|
+
`void er_app_set_${s.name}(${cScalarType(s.cType)} v)\n{\n ${s.cMember} = v;\n${hasUpdate ? ' app_update();\n' : ''}}`,
|
|
5029
7609
|
)
|
|
5030
7610
|
.join('\n\n');
|
|
5031
7611
|
const hostSetterProtos = hostRecords
|
|
5032
7612
|
.map(
|
|
5033
7613
|
s =>
|
|
5034
|
-
`/** @brief Host-fed input '${s.name}' (useHostValue): set its value and refresh the display. */\nvoid er_app_set_${s.name}(${s.cType
|
|
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);`,
|
|
5035
7615
|
)
|
|
5036
7616
|
.join('\n\n');
|
|
5037
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
|
+
|
|
5038
7916
|
const body = `/*
|
|
5039
7917
|
* Generated by the embedded-react Flow B AOT compiler (npm run aot -- ${demo}). DO NOT EDIT.
|
|
5040
7918
|
* Builds the app's scene graph + state machine directly against er_scene.h — no QuickJS, no JS runtime.
|
|
@@ -5047,13 +7925,28 @@ static void er_timer_clear(int id)
|
|
|
5047
7925
|
#include <stdio.h>
|
|
5048
7926
|
#include <string.h>
|
|
5049
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
|
+
|
|
5050
7938
|
/* Version-pin: this file was generated by embedded-react ${PKG_VERSION}. The engine ships LOCKSTEP, so its
|
|
5051
7939
|
headers must be the same major.minor — otherwise these generated er_scene.h calls may not match the ABI.
|
|
5052
7940
|
A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
|
|
5053
7941
|
_Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
|
|
5054
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.");
|
|
5055
|
-
${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' : ''}${stateBlock ? '\n' + stateBlock : ''}${refDecls ? '\n' + refDecls + '\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' : ''}${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' : ''}
|
|
5056
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
|
+
}
|
|
5057
7950
|
${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}
|
|
5058
7951
|
void er_app_build(int screen_w, int screen_h)
|
|
5059
7952
|
{
|
|
@@ -5077,12 +7970,41 @@ ${out.kbdSetup ? out.kbdSetup + ' /* app-supplied on-screen keyboard layout/appe
|
|
|
5077
7970
|
#ifndef ER_APP_GEN_H
|
|
5078
7971
|
#define ER_APP_GEN_H
|
|
5079
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
|
+
|
|
5080
7995
|
/** @brief Builds the AOT-compiled app's scene graph + state machine (call once after backend init). */
|
|
5081
7996
|
void er_app_build(int screen_w, int screen_h);
|
|
5082
7997
|
|
|
5083
7998
|
/** @brief Advances app timers (setInterval/setTimeout). Call once per frame with the elapsed ms; a no-op
|
|
5084
7999
|
* for apps that use no timers, so it is always safe to call. */
|
|
5085
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);
|
|
5086
8008
|
${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
|
|
5087
8009
|
#endif
|
|
5088
8010
|
`;
|
|
@@ -5104,11 +8026,37 @@ ${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
|
|
|
5104
8026
|
};
|
|
5105
8027
|
}
|
|
5106
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
|
+
|
|
5107
8055
|
/** Public entry: compile JSX source → { c, h, ... }. On an AOT error, annotate it with file:line:col + a
|
|
5108
8056
|
* source code-frame (+ hint) so the failure points at the exact unsupported construct. */
|
|
5109
8057
|
export function compileSource(src, demo = 'app', opts = {}) {
|
|
5110
8058
|
try {
|
|
5111
|
-
return
|
|
8059
|
+
return compileWidened(src, demo, opts);
|
|
5112
8060
|
} catch (e) {
|
|
5113
8061
|
if (e && typeof e.message === 'string' && e.message.startsWith('AOT:')) {
|
|
5114
8062
|
throw formatAotError(e, src, opts.filename || `demos/${demo}/App.jsx`);
|
|
@@ -5127,12 +8075,12 @@ if (
|
|
|
5127
8075
|
) {
|
|
5128
8076
|
const demo = process.argv[2] || process.env.DEMO || 'thermostat';
|
|
5129
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
|
+
: [];
|
|
5130
8083
|
if (!existsSync(appPath)) {
|
|
5131
|
-
const avail = existsSync(demosDir)
|
|
5132
|
-
? readdirSync(demosDir, {withFileTypes: true})
|
|
5133
|
-
.filter(d => d.isDirectory())
|
|
5134
|
-
.map(d => d.name)
|
|
5135
|
-
: [];
|
|
5136
8084
|
console.error(
|
|
5137
8085
|
`AOT: demo "${demo}" not found (expected ${appPath}). Available: ${avail.join(', ') || '(none)'}`,
|
|
5138
8086
|
);
|
|
@@ -5170,6 +8118,10 @@ if (
|
|
|
5170
8118
|
process.exit(1);
|
|
5171
8119
|
}
|
|
5172
8120
|
}
|
|
8121
|
+
// Flow B has no font imports — every string renders in the engine's built-in font, so check the
|
|
8122
|
+
// app's text and its font sizes against that coverage.
|
|
8123
|
+
warnMissingGlyphs({source: src, jsx: true});
|
|
8124
|
+
warnFontSizes({used: analyzeFontSizes(src)});
|
|
5173
8125
|
const baked = bakeAssets({images: imageJobs, fonts: [], outDir: distDir});
|
|
5174
8126
|
console.log(
|
|
5175
8127
|
`AOT: compiled demo "${demo}" -> dist/app.gen.c (${result.nodes} nodes, ${result.state} state, ` +
|