embedded-react 0.13.0 → 0.14.1
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 +78 -1
- package/aot/compile.mjs +2269 -288
- package/aot/style-map.mjs +20 -1
- package/assets/emit-container.mjs +4 -2
- package/cli.mjs +28 -2
- package/package.json +1 -1
- package/sim/embedded-react.wasm +0 -0
- package/src/embedded-react/PanResponder.js +1 -1
- package/src/embedded-react/index.d.ts +7 -3
- package/src/embedded-react/svg-ops.js +95 -11
- package/src/host-config.js +5 -0
- package/src/props.js +2 -0
- package/src/renderer.js +31 -0
package/aot/compile.mjs
CHANGED
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
// npm run aot # default demo (thermostat) — but use a minimal demo for the slice
|
|
35
35
|
// npm run aot -- watch-face # a specific demo by folder name
|
|
36
36
|
import {parse} from '@babel/parser';
|
|
37
|
+
import {traverse} from '@babel/core';
|
|
37
38
|
import {codeFrameColumns} from '@babel/code-frame';
|
|
38
39
|
import {
|
|
39
40
|
readFileSync,
|
|
@@ -46,6 +47,8 @@ import {resolve, dirname} from 'node:path';
|
|
|
46
47
|
import {fileURLToPath} from 'node:url';
|
|
47
48
|
import {
|
|
48
49
|
lowerStyle,
|
|
50
|
+
isStyleKey,
|
|
51
|
+
STYLE_KEYS,
|
|
49
52
|
NODE_TYPES,
|
|
50
53
|
DYN_FIELDS,
|
|
51
54
|
colorLiteral,
|
|
@@ -103,6 +106,15 @@ const [PKG_MAJOR, PKG_MINOR] = PKG_VERSION.split('.');
|
|
|
103
106
|
// DEEPEST node that failed pins the location; compileSource formats it at the top.
|
|
104
107
|
// ---------------------------------------------------------------------------------------------------
|
|
105
108
|
|
|
109
|
+
/**
|
|
110
|
+
* The `#ifndef` marker a board example guards on, from a demo name. Every character outside [A-Za-z0-9]
|
|
111
|
+
* becomes `_<hex code point>_`, so the result is a C identifier AND the mapping is one-to-one: `foo-bar`
|
|
112
|
+
* is ER_AOT_DEMO_foo_2d_bar and `foo_bar` is ER_AOT_DEMO_foo_5f_bar. Flattening both to `foo_bar` would
|
|
113
|
+
* let a board guard accept the wrong app, from either entry point that generates one.
|
|
114
|
+
*/
|
|
115
|
+
export const demoMarker = demo =>
|
|
116
|
+
`ER_AOT_DEMO_${demo.replace(/[^A-Za-z0-9]/gu, ch => `_${ch.codePointAt(0).toString(16)}_`)}`;
|
|
117
|
+
|
|
106
118
|
/** Throws an AOT error carrying an optional `hint` (a "rewrite it like this" suggestion shown to the user). */
|
|
107
119
|
function aotError(message, hint) {
|
|
108
120
|
const e = new Error(message.startsWith('AOT:') ? message : `AOT: ${message}`);
|
|
@@ -290,16 +302,336 @@ function evalStatic(node, scope) {
|
|
|
290
302
|
const ARITH = new Set(['+', '-', '*', '/', '%']);
|
|
291
303
|
const COMPARE = new Set(['<', '>', '<=', '>=', '==', '!=', '===', '!==']);
|
|
292
304
|
|
|
305
|
+
/**
|
|
306
|
+
* The C helper each whole-number operator lowers to. It saturates at the limit of its type, where C's own
|
|
307
|
+
* signed overflow is undefined behavior; the 64-bit variant appends `64`.
|
|
308
|
+
*/
|
|
309
|
+
const CHECKED_OP = {'+': 'app_add', '-': 'app_sub', '*': 'app_mul'};
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* `scope` minus every name `env` binds at RUNTIME — locals, state, refs, animated values, and the event /
|
|
313
|
+
* gesture params of the handler being compiled. emitExpr resolves those before env.consts, so a fold
|
|
314
|
+
* that consulted the raw scope would silently swap a module const in for the value the code actually
|
|
315
|
+
* uses. Every env-driven constant fold goes through this; the JSX-side folds keep the same rule by
|
|
316
|
+
* deleting a name from their scope copy when they bind it (see emitComponent / emitDynamicMap).
|
|
317
|
+
*/
|
|
318
|
+
function foldScope(env, scope) {
|
|
319
|
+
const bound = new Set([
|
|
320
|
+
...(env.locals?.keys() ?? []),
|
|
321
|
+
...(env.state?.keys() ?? []),
|
|
322
|
+
...(env.refs?.keys() ?? []),
|
|
323
|
+
...(env.anims?.keys() ?? []),
|
|
324
|
+
]);
|
|
325
|
+
if (env.event) bound.add(env.event);
|
|
326
|
+
if (env.gesture) bound.add(env.gesture);
|
|
327
|
+
let shadows = false;
|
|
328
|
+
for (const k of bound)
|
|
329
|
+
if (k in scope) {
|
|
330
|
+
shadows = true;
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
if (!shadows) return scope;
|
|
334
|
+
return Object.fromEntries(
|
|
335
|
+
Object.entries(scope).filter(([k]) => !bound.has(k)),
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const withUndefined = scope => Object.assign(Object.create(scope), {undefined});
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* `e` used as a C condition. JS treats a string as truthy when it is non-empty; a bare char[] in C tests
|
|
343
|
+
* its ADDRESS, which is always true — and real GCC refuses that under -Werror=address.
|
|
344
|
+
*/
|
|
345
|
+
const asCond = e => (e.cType === 'string' ? `(${e.code}[0] != '\\0')` : e.code);
|
|
346
|
+
|
|
347
|
+
/** No state or ref slot widened to 64 bits — the collectors' default. */
|
|
348
|
+
const NO_WIDE = new Set();
|
|
349
|
+
|
|
350
|
+
/** A 64-bit timestamp met a float, which would round it. */
|
|
351
|
+
const mix64Error = () =>
|
|
352
|
+
aotError(
|
|
353
|
+
'AOT: a 64-bit time value cannot be mixed with a float',
|
|
354
|
+
'Date.now() and performance.now() are whole milliseconds in a 64-bit integer, and a float would round them. Keep the arithmetic whole — e.g. Math.floor(ms / 1000), not ms * 0.001.',
|
|
355
|
+
);
|
|
356
|
+
|
|
357
|
+
/** A 64-bit timestamp met a boolean in `&&` / `||` / `?:`, where JS would hand back the boolean itself. */
|
|
358
|
+
const bool64Error = what =>
|
|
359
|
+
aotError(
|
|
360
|
+
`AOT: ${what} cannot mix a boolean with a 64-bit time value`,
|
|
361
|
+
'JS would give back the boolean itself (and false renders as no text), which a 64-bit integer cannot hold. Use a number on both sides, e.g. `on ? Date.now() : 0`.',
|
|
362
|
+
);
|
|
363
|
+
|
|
364
|
+
/** Flow A's lite profile has Date.now() and no Date objects, and so does the AOT. */
|
|
365
|
+
const dateObjectError = () =>
|
|
366
|
+
aotError(
|
|
367
|
+
'AOT: Date objects are not supported — only Date.now()',
|
|
368
|
+
'keep time as milliseconds from Date.now() and do the calendar math on the number.',
|
|
369
|
+
);
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The `Date` / `performance` calls whose name is the app's own binding — a const, a param, an import —
|
|
373
|
+
* rather than the global, so they are not the engine clock. Babel's scopes decide, as JS would.
|
|
374
|
+
*/
|
|
375
|
+
function findShadowedClockCalls(ast) {
|
|
376
|
+
const calls = new WeakSet();
|
|
377
|
+
traverse(ast, {
|
|
378
|
+
'CallExpression|NewExpression'(path) {
|
|
379
|
+
const c = path.node.callee;
|
|
380
|
+
const id = c.type === 'MemberExpression' ? c.object : c;
|
|
381
|
+
if (
|
|
382
|
+
id.type === 'Identifier' &&
|
|
383
|
+
(id.name === 'Date' || id.name === 'performance') &&
|
|
384
|
+
path.scope.getBinding(id.name)
|
|
385
|
+
)
|
|
386
|
+
calls.add(path.node);
|
|
387
|
+
},
|
|
388
|
+
});
|
|
389
|
+
return calls;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** `node` as an integer compile-time constant, or null. */
|
|
393
|
+
function staticInt(node, env) {
|
|
394
|
+
try {
|
|
395
|
+
const v = evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
396
|
+
return Number.isInteger(v) ? v : null;
|
|
397
|
+
} catch {
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const INT_MIN = -(2 ** 31);
|
|
403
|
+
const INT_MAX = 2 ** 31 - 1;
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* A compile-time number as C. A whole number too big for an int is a 64-bit constant (`lit`), so whole-number
|
|
407
|
+
* math keeps it exact; past 64 bits it is a float.
|
|
408
|
+
*/
|
|
409
|
+
function numConst(v) {
|
|
410
|
+
// floatLit refuses NaN and Infinity (a folded `0 / 0`, say), which have no C literal.
|
|
411
|
+
if (!Number.isInteger(v)) return {code: floatLit(v), cType: 'float'};
|
|
412
|
+
if (v < -(2 ** 63) || v >= 2 ** 63)
|
|
413
|
+
return {code: floatLit(v), cType: 'float'};
|
|
414
|
+
if (v < INT_MIN || v > INT_MAX)
|
|
415
|
+
return {code: i64Lit(v), cType: 'i64', lit: true};
|
|
416
|
+
// `-2147483648` is `-` applied to 2147483648, which does not fit an int.
|
|
417
|
+
return {code: v === INT_MIN ? '(-2147483647 - 1)' : String(v), cType: 'int'};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* A whole number in the int64 range as a C literal. `String(v)` is JS's shortest spelling that reads back as the
|
|
422
|
+
* same double, which past 2^53 is not the number itself: 4611686018427387904 prints as 4611686018427388000.
|
|
423
|
+
*/
|
|
424
|
+
function i64Lit(v) {
|
|
425
|
+
// `-9223372036854775808` is `-` applied to 9223372036854775808, which fits no signed type.
|
|
426
|
+
return v === -(2 ** 63) ? '(-9223372036854775807 - 1)' : BigInt(v).toString();
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** `+ - *` or a unary `-`: the operators that can overflow a whole number. */
|
|
430
|
+
const isIntArith = n =>
|
|
431
|
+
(n.type === 'BinaryExpression' && Boolean(CHECKED_OP[n.operator])) ||
|
|
432
|
+
(n.type === 'UnaryExpression' && n.operator === '-');
|
|
433
|
+
|
|
434
|
+
/** The Math functions that keep a whole number whole. */
|
|
435
|
+
const WHOLE_MATH = new Set([
|
|
436
|
+
'floor',
|
|
437
|
+
'ceil',
|
|
438
|
+
'round',
|
|
439
|
+
'trunc',
|
|
440
|
+
'abs',
|
|
441
|
+
'min',
|
|
442
|
+
'max',
|
|
443
|
+
]);
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Whole-number math JS would not cut to 32 bits: `+ - *`, negation, `%`, and the Math functions that keep a
|
|
447
|
+
* whole number whole. Beside a 64-bit value all of it is worked out in 64 bits, however deep it sits.
|
|
448
|
+
*/
|
|
449
|
+
const keepsMath64 = n =>
|
|
450
|
+
isIntArith(n) ||
|
|
451
|
+
(n.type === 'BinaryExpression' && n.operator === '%') ||
|
|
452
|
+
(n.type === 'CallExpression' &&
|
|
453
|
+
n.callee.type === 'MemberExpression' &&
|
|
454
|
+
!n.callee.computed &&
|
|
455
|
+
n.callee.object.type === 'Identifier' &&
|
|
456
|
+
n.callee.object.name === 'Math' &&
|
|
457
|
+
WHOLE_MATH.has(n.callee.property.name));
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* A 64-bit value computed at runtime from a timestamp, as opposed to a 64-bit constant (`lit`) or whole-number
|
|
461
|
+
* math widened to 64 bits beside one (`wide`).
|
|
462
|
+
*/
|
|
463
|
+
const isTime64 = e => e.cType === 'i64' && !e.lit && !e.wide;
|
|
464
|
+
|
|
465
|
+
/** Beside a float, a 64-bit constant is an ordinary number that converts, as in JS; only a timestamp refuses. */
|
|
466
|
+
const litPeers = (...es) =>
|
|
467
|
+
es.some(e => e.cType === 'float')
|
|
468
|
+
? es.map(e => (e.lit ? {code: `((float)${e.code})`, cType: 'float'} : e))
|
|
469
|
+
: es;
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* The divisor of a timestamp's `%` or Math.floor / ceil / round / trunc(a / b), which has to be a constant; for
|
|
473
|
+
* one from state, an app reduces the timestamp first. A constant 0 gives JS's answer as the int math converts it:
|
|
474
|
+
* a remainder of 0, or a quotient saturated by the dividend's sign.
|
|
475
|
+
*/
|
|
476
|
+
function constDivisor(node, env) {
|
|
477
|
+
const m = staticInt(node, env);
|
|
478
|
+
if (m !== null) return m;
|
|
479
|
+
const e = aotError(
|
|
480
|
+
'AOT: a 64-bit time value can only be divided by a constant',
|
|
481
|
+
'the divisor must be known at compile time — e.g. `ms % 1000`, `Math.floor(ms / 60000)`. For a divisor from state, reduce the timestamp first: `(ms % 86400000) / period`.',
|
|
482
|
+
);
|
|
483
|
+
if (node.loc) e.aotLoc = node.loc.start;
|
|
484
|
+
throw e;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* `+ - * %` with a 64-bit value on either side, kept whole. `+ - *` saturate at the int64 limits. With a
|
|
489
|
+
* timestamp in it, `%` takes a constant; whole-number math widened beside one takes any divisor, as the
|
|
490
|
+
* int `%` does. The result narrows back to int when the divisor or the dividend fits one, so `ms % 1000` is an
|
|
491
|
+
* ordinary number again. `/` is refused: JS would give a fraction, and the whole-number division is written
|
|
492
|
+
* Math.floor(a / b).
|
|
493
|
+
*/
|
|
494
|
+
function emitArith64(node, l, r, env) {
|
|
495
|
+
if (l.cType === 'float' || r.cType === 'float') throw mix64Error();
|
|
496
|
+
if (node.operator === '/')
|
|
497
|
+
throw aotError(
|
|
498
|
+
'AOT: `/` on a 64-bit time value is not supported',
|
|
499
|
+
'JS division gives a fraction, which a 64-bit integer cannot hold. Use Math.floor(a / b) for whole units — e.g. Math.floor(ms / 1000) for seconds.',
|
|
500
|
+
);
|
|
501
|
+
const wide = !isTime64(l) && !isTime64(r);
|
|
502
|
+
if (node.operator === '%') {
|
|
503
|
+
const k = staticInt(node.right, env);
|
|
504
|
+
// JS gives NaN for a zero divisor, which is 0 here, as the int `%` has it.
|
|
505
|
+
if (k === 0) return {code: '0', cType: 'int'};
|
|
506
|
+
if (wide && k === null)
|
|
507
|
+
return {
|
|
508
|
+
code: `app_mod64(${l.code}, ${r.code})`,
|
|
509
|
+
cType: 'i64',
|
|
510
|
+
wide: true,
|
|
511
|
+
};
|
|
512
|
+
const m = constDivisor(node.right, env);
|
|
513
|
+
// ±1 leaves no remainder, and INT64_MIN % -1 overflows in C.
|
|
514
|
+
if (m === 1 || m === -1) return {code: '0', cType: 'int'};
|
|
515
|
+
if (Math.abs(m) <= 0x7fffffff || l.cType === 'int')
|
|
516
|
+
return {code: `((int)(${l.code} % ${r.code}))`, cType: 'int'};
|
|
517
|
+
return {code: `(${l.code} % ${r.code})`, cType: 'i64', wide};
|
|
518
|
+
}
|
|
519
|
+
return {
|
|
520
|
+
code: `${CHECKED_OP[node.operator]}64(${l.code}, ${r.code})`,
|
|
521
|
+
cType: 'i64',
|
|
522
|
+
wide,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Math.floor / ceil / round / trunc over `a / b` with a 64-bit timestamp on either side, as exact integer division
|
|
528
|
+
* by a constant (see constDivisor); a zero one saturates by the dividend's sign, as JS's ±Infinity converts. Null
|
|
529
|
+
* when neither side is a timestamp, which leaves it to the whole-number or float path.
|
|
530
|
+
*/
|
|
531
|
+
function emitTimeRoundDiv(fn, args, env) {
|
|
532
|
+
const arg = args[0];
|
|
533
|
+
if (
|
|
534
|
+
!INT_ROUND_DIV.has(fn) ||
|
|
535
|
+
args.length !== 1 ||
|
|
536
|
+
arg.type !== 'BinaryExpression' ||
|
|
537
|
+
arg.operator !== '/'
|
|
538
|
+
)
|
|
539
|
+
return null;
|
|
540
|
+
const l = emitExprWide(arg.left, env);
|
|
541
|
+
const r = emitExprWide(arg.right, env);
|
|
542
|
+
if (!isTime64(l) && !isTime64(r)) return null;
|
|
543
|
+
if (l.cType === 'float' || r.cType === 'float') throw mix64Error();
|
|
544
|
+
if (l.cType === 'string' || r.cType === 'string') return null;
|
|
545
|
+
// Dividing by -1 is a negation, which saturates; C's `/` would overflow on INT64_MIN / -1.
|
|
546
|
+
if (constDivisor(arg.right, env) === -1)
|
|
547
|
+
return {code: `app_neg64(${l.code})`, cType: 'i64'};
|
|
548
|
+
return {
|
|
549
|
+
code: `${INT_ROUND_DIV.get(fn)}64(${l.code}, ${r.code})`,
|
|
550
|
+
cType: 'i64',
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** The helper that rounds `a / b` for two ints the way each Math function does. */
|
|
555
|
+
const INT_ROUND_DIV = new Map([
|
|
556
|
+
['floor', 'app_floordiv'],
|
|
557
|
+
['ceil', 'app_ceildiv'],
|
|
558
|
+
['round', 'app_rounddiv'],
|
|
559
|
+
['trunc', 'app_div'],
|
|
560
|
+
]);
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Math.floor / ceil / round / trunc over `a / b` with two whole numbers, as exact integer division: the float
|
|
564
|
+
* path rounds an operand past 2^24, so Math.floor(16777217 / 1) came out 16777216. A zero divisor keeps JS's
|
|
565
|
+
* answer as app_f2i converts it (±Infinity saturates by the dividend's sign, 0 / 0 is 0), and INT_MIN / -1
|
|
566
|
+
* saturates too. Beside a 64-bit value, or with a 64-bit operand that is not a timestamp (a constant past the int
|
|
567
|
+
* range, or math already widened), it divides in 64 bits, since JS would not cut the operands to 32. Null for
|
|
568
|
+
* anything else, which leaves it to the float path.
|
|
569
|
+
*/
|
|
570
|
+
function emitIntRoundDiv(fn, args, env) {
|
|
571
|
+
const arg = args[0];
|
|
572
|
+
if (
|
|
573
|
+
!INT_ROUND_DIV.has(fn) ||
|
|
574
|
+
args.length !== 1 ||
|
|
575
|
+
arg.type !== 'BinaryExpression' ||
|
|
576
|
+
arg.operator !== '/'
|
|
577
|
+
)
|
|
578
|
+
return null;
|
|
579
|
+
const l = emitExprWide(arg.left, env);
|
|
580
|
+
const r = emitExprWide(arg.right, env);
|
|
581
|
+
if (env.math64 || l.cType === 'i64' || r.cType === 'i64') {
|
|
582
|
+
const whole = e => e.cType === 'int' || (e.cType === 'i64' && !isTime64(e));
|
|
583
|
+
if (!whole(l) || !whole(r)) return null;
|
|
584
|
+
return {
|
|
585
|
+
code: `${INT_ROUND_DIV.get(fn)}64(${l.code}, ${r.code})`,
|
|
586
|
+
cType: 'i64',
|
|
587
|
+
wide: true,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
if (l.cType !== 'int' || r.cType !== 'int') return null;
|
|
591
|
+
return {
|
|
592
|
+
code: `${INT_ROUND_DIV.get(fn)}(${l.code}, ${r.code})`,
|
|
593
|
+
cType: 'int',
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** Math.* over a 64-bit timestamp: only what stays exact in whole numbers. */
|
|
598
|
+
function emitMath64(fn, a) {
|
|
599
|
+
if (a.some(x => x.cType === 'float')) throw mix64Error();
|
|
600
|
+
if (a.every(x => x.cType === 'int' || x.cType === 'i64')) {
|
|
601
|
+
// Whole-number math with no timestamp in it stays whole-number math.
|
|
602
|
+
const wide = !a.some(isTime64);
|
|
603
|
+
// A timestamp is already whole, so rounding leaves it as it is.
|
|
604
|
+
if (
|
|
605
|
+
(fn === 'floor' || fn === 'round' || fn === 'ceil' || fn === 'trunc') &&
|
|
606
|
+
a.length === 1
|
|
607
|
+
)
|
|
608
|
+
return {code: a[0].code, cType: 'i64', wide};
|
|
609
|
+
if (fn === 'abs' && a.length === 1)
|
|
610
|
+
return {code: `app_abs64(${a[0].code})`, cType: 'i64', wide};
|
|
611
|
+
if ((fn === 'min' || fn === 'max') && a.length === 2)
|
|
612
|
+
return {
|
|
613
|
+
code: `app_${fn}64(${a[0].code}, ${a[1].code})`,
|
|
614
|
+
cType: 'i64',
|
|
615
|
+
wide,
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
throw aotError(
|
|
619
|
+
`AOT: Math.${fn}(...) on a 64-bit time value is not supported`,
|
|
620
|
+
'Math.floor / round / ceil / trunc / abs / min / max keep a timestamp exact; for anything else, reduce it to a small number first, e.g. `ms % 1000`.',
|
|
621
|
+
);
|
|
622
|
+
}
|
|
623
|
+
|
|
293
624
|
function emitExprImpl(node, env) {
|
|
625
|
+
// 64-bit int math reaches only through whole-number math (keepsMath64); any other node under it is typed as
|
|
626
|
+
// usual.
|
|
627
|
+
if (env.math64 && !keepsMath64(node)) env = {...env, math64: false};
|
|
294
628
|
switch (node.type) {
|
|
295
629
|
case 'NumericLiteral':
|
|
296
|
-
return
|
|
297
|
-
? {code: String(node.value), cType: 'int'}
|
|
298
|
-
: {code: `${node.value}f`, cType: 'float'};
|
|
630
|
+
return numConst(node.value);
|
|
299
631
|
case 'StringLiteral':
|
|
300
632
|
return {code: cstr(node.value), cType: 'string'};
|
|
301
633
|
case 'BooleanLiteral':
|
|
302
|
-
return {code: node.value ? '1' : '0', cType: 'int'};
|
|
634
|
+
return {code: node.value ? '1' : '0', cType: 'int', isBool: true};
|
|
303
635
|
case 'Identifier': {
|
|
304
636
|
if (env.locals.has(node.name)) return env.locals.get(node.name);
|
|
305
637
|
if (env.state.has(node.name)) {
|
|
@@ -308,38 +640,101 @@ function emitExprImpl(node, env) {
|
|
|
308
640
|
throw new Error(
|
|
309
641
|
`AOT: a list state ("${node.name}") can only be used via .length or .map`,
|
|
310
642
|
);
|
|
311
|
-
return {code: s.cMember, cType: s.cType};
|
|
643
|
+
return {code: s.cMember, cType: s.cType, isBool: s.isBool};
|
|
312
644
|
}
|
|
313
645
|
if (node.name in env.consts) {
|
|
314
646
|
const v = env.consts[node.name];
|
|
315
|
-
if (typeof v === 'number')
|
|
316
|
-
return Number.isInteger(v)
|
|
317
|
-
? {code: String(v), cType: 'int'}
|
|
318
|
-
: {code: `${v}f`, cType: 'float'};
|
|
647
|
+
if (typeof v === 'number') return numConst(v);
|
|
319
648
|
if (typeof v === 'string') return {code: cstr(v), cType: 'string'};
|
|
649
|
+
if (typeof v === 'boolean')
|
|
650
|
+
return {code: v ? '1' : '0', cType: 'int', isBool: true};
|
|
320
651
|
}
|
|
321
652
|
throw new Error(
|
|
322
653
|
`AOT: cannot resolve identifier "${node.name}" in a dynamic expression`,
|
|
323
654
|
);
|
|
324
655
|
}
|
|
325
656
|
case 'UnaryExpression': {
|
|
326
|
-
|
|
327
|
-
|
|
657
|
+
// A constant is negated here, so `-A` is its value and -2147483648 is not an int overflow.
|
|
658
|
+
const neg = node.operator === '-' ? staticInt(node.argument, env) : null;
|
|
659
|
+
if (neg !== null) return numConst(-neg);
|
|
660
|
+
const a = emitExprWide(node.argument, env);
|
|
661
|
+
if (
|
|
662
|
+
(node.operator === '-' || node.operator === '+') &&
|
|
663
|
+
a.cType === 'string'
|
|
664
|
+
)
|
|
665
|
+
throw aotError(
|
|
666
|
+
`AOT: unary "${node.operator}" on a string is not supported`,
|
|
667
|
+
'JS would coerce the string to a number; C has no such coercion. Keep the operand numeric.',
|
|
668
|
+
);
|
|
669
|
+
// Negating the minimum overflows, so a whole number saturates the way `+ - *` do.
|
|
670
|
+
if (node.operator === '-' && (a.cType === 'int' || a.cType === 'i64')) {
|
|
671
|
+
const w = a.cType === 'i64' || env.math64;
|
|
672
|
+
return w
|
|
673
|
+
? {code: `app_neg64(${a.code})`, cType: 'i64', wide: !isTime64(a)}
|
|
674
|
+
: {code: `app_neg(${a.code})`, cType: 'int'};
|
|
675
|
+
}
|
|
676
|
+
// Parenthesize the operand so `-` on a negative operand emits `(-(-x))`, not `(--x)` (a decrement).
|
|
328
677
|
if (
|
|
329
678
|
node.operator === '-' ||
|
|
330
679
|
node.operator === '+' ||
|
|
331
680
|
node.operator === '!'
|
|
332
681
|
)
|
|
682
|
+
// Only `!` yields a boolean. Unary +/- are numeric coercions — `+flag` is 0 or 1 in JS, so the
|
|
683
|
+
// operand's boolean-ness must not survive them.
|
|
333
684
|
return {
|
|
334
|
-
code: `(${node.operator}(${a.code}))`,
|
|
685
|
+
code: `(${node.operator}(${node.operator === '!' ? asCond(a) : a.code}))`,
|
|
335
686
|
cType: node.operator === '!' ? 'int' : a.cType,
|
|
687
|
+
isBool: node.operator === '!',
|
|
336
688
|
};
|
|
337
689
|
throw new Error(`AOT: unsupported unary operator "${node.operator}"`);
|
|
338
690
|
}
|
|
339
691
|
case 'BinaryExpression': {
|
|
340
|
-
|
|
341
|
-
|
|
692
|
+
// `+ - *` over two whole-number constants is worked out here, as JS would, so a product too big for an
|
|
693
|
+
// int (30 * DAY_MS) is an exact 64-bit constant rather than an overflow.
|
|
694
|
+
const lk = CHECKED_OP[node.operator] ? staticInt(node.left, env) : null;
|
|
695
|
+
const rk = lk === null ? null : staticInt(node.right, env);
|
|
696
|
+
if (rk !== null)
|
|
697
|
+
return numConst(
|
|
698
|
+
node.operator === '+'
|
|
699
|
+
? lk + rk
|
|
700
|
+
: node.operator === '-'
|
|
701
|
+
? lk - rk
|
|
702
|
+
: lk * rk,
|
|
703
|
+
);
|
|
704
|
+
let l = emitExprWide(node.left, env);
|
|
705
|
+
let r = emitExprWide(node.right, env);
|
|
706
|
+
// Beside a 64-bit value, whole-number int math is worked out in 64 bits too: JS would not have cut it to 32.
|
|
707
|
+
if (l.cType === 'i64' || r.cType === 'i64') {
|
|
708
|
+
if (l.cType === 'int' && keepsMath64(node.left))
|
|
709
|
+
l = emitExprWide(node.left, {...env, math64: true});
|
|
710
|
+
if (r.cType === 'int' && keepsMath64(node.right))
|
|
711
|
+
r = emitExprWide(node.right, {...env, math64: true});
|
|
712
|
+
}
|
|
713
|
+
[l, r] = litPeers(l, r);
|
|
342
714
|
if (ARITH.has(node.operator)) {
|
|
715
|
+
if (l.cType === 'string' || r.cType === 'string') {
|
|
716
|
+
// `+` over a string builds text, which C cannot express as one value. Where the destination is
|
|
717
|
+
// a char buffer the caller lowers it with emitFormat(); anywhere else there is nothing to lower
|
|
718
|
+
// to.
|
|
719
|
+
if (node.operator === '+')
|
|
720
|
+
throw aotError(
|
|
721
|
+
'AOT: string concatenation is not supported in this position',
|
|
722
|
+
'a `+` chain over strings lowers to a printf format, which only works where the value lands in a text buffer: a <Text> body, a string useState setter, or a <TextInput value>.',
|
|
723
|
+
);
|
|
724
|
+
// JS would coerce the string to a number; C would do pointer arithmetic or refuse to compile.
|
|
725
|
+
throw aotError(
|
|
726
|
+
`AOT: "${node.operator}" on a string is not supported`,
|
|
727
|
+
'keep both operands numeric — a string cannot be coerced to a number here.',
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
// `/` takes a 64-bit constant as an ordinary C number; only a runtime 64-bit value is refused it.
|
|
731
|
+
if (
|
|
732
|
+
isTime64(l) ||
|
|
733
|
+
isTime64(r) ||
|
|
734
|
+
((l.cType === 'i64' || r.cType === 'i64') &&
|
|
735
|
+
(CHECKED_OP[node.operator] || node.operator === '%'))
|
|
736
|
+
)
|
|
737
|
+
return emitArith64(node, l, r, env);
|
|
343
738
|
if (node.operator === '/')
|
|
344
739
|
return {
|
|
345
740
|
code: `((float)(${l.code}) / (float)(${r.code}))`,
|
|
@@ -347,28 +742,96 @@ function emitExprImpl(node, env) {
|
|
|
347
742
|
};
|
|
348
743
|
const cType =
|
|
349
744
|
l.cType === 'float' || r.cType === 'float' ? 'float' : 'int';
|
|
745
|
+
const fn = cType === 'int' && CHECKED_OP[node.operator];
|
|
746
|
+
if (fn)
|
|
747
|
+
return env.math64
|
|
748
|
+
? {code: `${fn}64(${l.code}, ${r.code})`, cType: 'i64', wide: true}
|
|
749
|
+
: {code: `${fn}(${l.code}, ${r.code})`, cType: 'int'};
|
|
750
|
+
// JS gives NaN for `x % 0` (0 here, as a float would convert), and C overflows on INT_MIN % -1, whose
|
|
751
|
+
// answer is 0. A constant divisor other than those two needs no check.
|
|
752
|
+
if (cType === 'int' && node.operator === '%') {
|
|
753
|
+
const k = staticInt(node.right, env);
|
|
754
|
+
if (k === 0 || k === -1) return {code: '0', cType: 'int'};
|
|
755
|
+
if (k === null)
|
|
756
|
+
return {code: `app_mod(${l.code}, ${r.code})`, cType: 'int'};
|
|
757
|
+
}
|
|
758
|
+
// C has no `%` on floats. fmodf is JS's `%` exactly: the dividend's sign, NaN for a zero divisor, and
|
|
759
|
+
// the dividend itself for an infinite one.
|
|
760
|
+
if (cType === 'float' && node.operator === '%')
|
|
761
|
+
return {
|
|
762
|
+
code: `fmodf((float)(${l.code}), (float)(${r.code}))`,
|
|
763
|
+
cType: 'float',
|
|
764
|
+
};
|
|
350
765
|
return {code: `(${l.code} ${node.operator} ${r.code})`, cType};
|
|
351
766
|
}
|
|
352
767
|
if (COMPARE.has(node.operator)) {
|
|
353
|
-
const eqOp =
|
|
354
|
-
node.operator === '===' || node.operator === '=='
|
|
355
|
-
? '=='
|
|
356
|
-
: node.operator === '!==' || node.operator === '!='
|
|
357
|
-
? '!='
|
|
358
|
-
: null;
|
|
359
|
-
// String (in)equality → strcmp; the generated C already includes <string.h>.
|
|
360
|
-
if (eqOp && (l.cType === 'string' || r.cType === 'string'))
|
|
361
|
-
return {
|
|
362
|
-
code: `(strcmp(${l.code}, ${r.code}) ${eqOp} 0)`,
|
|
363
|
-
cType: 'int',
|
|
364
|
-
};
|
|
365
768
|
const op =
|
|
366
769
|
node.operator === '==='
|
|
367
770
|
? '=='
|
|
368
771
|
: node.operator === '!=='
|
|
369
772
|
? '!='
|
|
370
773
|
: node.operator;
|
|
371
|
-
|
|
774
|
+
if (l.cType === 'string' || r.cType === 'string') {
|
|
775
|
+
if (l.cType !== r.cType) {
|
|
776
|
+
// A strict comparison never coerces, so a string against a number is decided statically.
|
|
777
|
+
if (node.operator === '===' || node.operator === '!==')
|
|
778
|
+
return {
|
|
779
|
+
code: node.operator === '===' ? '0' : '1',
|
|
780
|
+
cType: 'int',
|
|
781
|
+
isBool: true,
|
|
782
|
+
};
|
|
783
|
+
throw aotError(
|
|
784
|
+
'AOT: a string cannot be compared with a number',
|
|
785
|
+
`\`${node.operator}\` coerces the string to a number in JS, which C cannot reproduce. Compare like with like, or use === / !== (which never coerce).`,
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
// Equality is byte-exact, which for UTF-8 is exactly JS string equality. Ordering is not: JS
|
|
789
|
+
// orders by UTF-16 code unit and strcmp by UTF-8 byte, and the two disagree once a character
|
|
790
|
+
// lies outside the Basic Multilingual Plane. Refuse rather than silently pick the other branch.
|
|
791
|
+
// (A bare `<` on two char* would compare addresses — real GCC rejects that under -Werror=address.)
|
|
792
|
+
if (op !== '==' && op !== '!=')
|
|
793
|
+
throw aotError(
|
|
794
|
+
`AOT: ordering strings with "${node.operator}" is not supported`,
|
|
795
|
+
'JS orders strings by UTF-16 code unit but the device holds UTF-8, so the order can differ. Use === / !==, or compare numbers.',
|
|
796
|
+
);
|
|
797
|
+
return {
|
|
798
|
+
code: `(strcmp(${l.code}, ${r.code}) ${op} 0)`,
|
|
799
|
+
cType: 'int',
|
|
800
|
+
isBool: true,
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
// A boolean and a number share an int slot, so C would hold `true === 1`; a strict comparison never
|
|
804
|
+
// coerces, so JS never does. Decided only when the other side is surely a number.
|
|
805
|
+
if (
|
|
806
|
+
(l.cType === 'i64' || r.cType === 'i64') &&
|
|
807
|
+
(l.cType === 'float' || r.cType === 'float')
|
|
808
|
+
)
|
|
809
|
+
throw mix64Error();
|
|
810
|
+
const surelyNum = (n, x) =>
|
|
811
|
+
!x.isBool &&
|
|
812
|
+
(x.cType === 'float' ||
|
|
813
|
+
x.cType === 'i64' ||
|
|
814
|
+
n.type === 'NumericLiteral' ||
|
|
815
|
+
(n.type === 'UnaryExpression' &&
|
|
816
|
+
n.argument.type === 'NumericLiteral') ||
|
|
817
|
+
(n.type === 'Identifier' &&
|
|
818
|
+
!env.locals.has(n.name) &&
|
|
819
|
+
env.state.get(n.name)?.isBool === false));
|
|
820
|
+
if (
|
|
821
|
+
(node.operator === '===' || node.operator === '!==') &&
|
|
822
|
+
((l.isBool && surelyNum(node.right, r)) ||
|
|
823
|
+
(r.isBool && surelyNum(node.left, l)))
|
|
824
|
+
)
|
|
825
|
+
return {
|
|
826
|
+
code: node.operator === '===' ? '0' : '1',
|
|
827
|
+
cType: 'int',
|
|
828
|
+
isBool: true,
|
|
829
|
+
};
|
|
830
|
+
return {
|
|
831
|
+
code: `(${l.code} ${op} ${r.code})`,
|
|
832
|
+
cType: 'int',
|
|
833
|
+
isBool: true,
|
|
834
|
+
};
|
|
372
835
|
}
|
|
373
836
|
throw new Error(`AOT: unsupported binary operator "${node.operator}"`);
|
|
374
837
|
}
|
|
@@ -377,32 +840,74 @@ function emitExprImpl(node, env) {
|
|
|
377
840
|
node.operator === '&&' || node.operator === '||' ? node.operator : null;
|
|
378
841
|
if (!op)
|
|
379
842
|
throw new Error(`AOT: unsupported logical operator "${node.operator}"`);
|
|
380
|
-
const l =
|
|
381
|
-
|
|
382
|
-
|
|
843
|
+
const [l, r] = litPeers(
|
|
844
|
+
emitExprWide(node.left, env),
|
|
845
|
+
emitExprWide(node.right, env),
|
|
846
|
+
);
|
|
847
|
+
// JS gives back one of the operands, not true/false. The 0/1 below is only its truth, which would
|
|
848
|
+
// store `1` in place of a timestamp — so with a 64-bit side, keep the operand's value.
|
|
849
|
+
if (l.cType === 'i64' || r.cType === 'i64') {
|
|
850
|
+
if (l.cType === 'float' || r.cType === 'float') throw mix64Error();
|
|
851
|
+
if (l.cType === 'string' || r.cType === 'string')
|
|
852
|
+
throw aotError(
|
|
853
|
+
`AOT: "${op}" cannot mix a 64-bit time value with a string`,
|
|
854
|
+
'keep both sides numbers, or write the branch out: {ms ? ms : 0}.',
|
|
855
|
+
);
|
|
856
|
+
if (l.isBool || r.isBool) throw bool64Error(`"${op}"`);
|
|
857
|
+
// `l` is read twice, which is safe: AOT expressions have no side effects, and the engine clock only
|
|
858
|
+
// moves in er_tick(), so a second Date.now() in the same expression reads the same value.
|
|
859
|
+
return {
|
|
860
|
+
code:
|
|
861
|
+
op === '||'
|
|
862
|
+
? `(${l.code} ? ${l.code} : ${r.code})`
|
|
863
|
+
: `(${l.code} ? ${r.code} : ${l.code})`,
|
|
864
|
+
cType: 'i64',
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
return {
|
|
868
|
+
code: `(${asCond(l)} ${op} ${asCond(r)})`,
|
|
869
|
+
cType: 'int',
|
|
870
|
+
isBool: Boolean(l.isBool && r.isBool),
|
|
871
|
+
};
|
|
383
872
|
}
|
|
384
873
|
case 'ConditionalExpression': {
|
|
385
|
-
const t =
|
|
386
|
-
const c =
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
874
|
+
const t = emitExprWide(node.test, env);
|
|
875
|
+
const [c, a] = litPeers(
|
|
876
|
+
emitExprWide(node.consequent, env),
|
|
877
|
+
emitExprWide(node.alternate, env),
|
|
878
|
+
);
|
|
879
|
+
// `(ok ? 1 : "none")` is ill-typed C (int vs char*) and has no single printf spec either, so it
|
|
880
|
+
// has to be refused here rather than handed to the host compiler.
|
|
881
|
+
if ((c.cType === 'string') !== (a.cType === 'string'))
|
|
882
|
+
throw aotError(
|
|
883
|
+
'AOT: a ternary cannot mix a string branch with a numeric one',
|
|
884
|
+
"both branches must be the same kind — quote the number to keep it text, e.g. {ok ? '1' : 'none'}.",
|
|
885
|
+
);
|
|
886
|
+
const either = k => c.cType === k || a.cType === k;
|
|
887
|
+
if (either('i64') && either('float')) throw mix64Error();
|
|
888
|
+
if (either('i64') && (c.isBool || a.isBool))
|
|
889
|
+
throw bool64Error('a ternary');
|
|
890
|
+
const cType = either('float')
|
|
891
|
+
? 'float'
|
|
892
|
+
: either('i64')
|
|
893
|
+
? 'i64'
|
|
391
894
|
: c.cType === a.cType
|
|
392
895
|
? c.cType
|
|
393
896
|
: 'int';
|
|
394
|
-
return {
|
|
897
|
+
return {
|
|
898
|
+
code: `(${asCond(t)} ? ${c.code} : ${a.code})`,
|
|
899
|
+
cType,
|
|
900
|
+
isBool: Boolean(c.isBool && a.isBool),
|
|
901
|
+
};
|
|
395
902
|
}
|
|
396
903
|
case 'MemberExpression': {
|
|
397
904
|
// Static fold: member access that resolves to a compile-time constant (e.g. a .map item's `.key`).
|
|
398
905
|
try {
|
|
399
|
-
const v = evalStatic(node, env.consts ?? {});
|
|
400
|
-
if (typeof v === 'number')
|
|
401
|
-
return Number.isInteger(v)
|
|
402
|
-
? {code: String(v), cType: 'int'}
|
|
403
|
-
: {code: `${v}f`, cType: 'float'};
|
|
906
|
+
const v = evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
907
|
+
if (typeof v === 'number') return numConst(v);
|
|
404
908
|
if (typeof v === 'string') return {code: cstr(v), cType: 'string'};
|
|
405
|
-
if (typeof v === 'boolean')
|
|
909
|
+
if (typeof v === 'boolean')
|
|
910
|
+
return {code: v ? '1' : '0', cType: 'int', isBool: true};
|
|
406
911
|
} catch {
|
|
407
912
|
/* not static — fall through to the dynamic member forms below */
|
|
408
913
|
}
|
|
@@ -486,26 +991,76 @@ function emitExprImpl(node, env) {
|
|
|
486
991
|
);
|
|
487
992
|
}
|
|
488
993
|
case 'CallExpression': {
|
|
489
|
-
// Math.* helpers → libm (the generated C includes <math.h> when these appear).
|
|
490
994
|
const c = node.callee;
|
|
995
|
+
// Date.now() / performance.now() → the engine clock, as 64-bit whole milliseconds.
|
|
996
|
+
if (
|
|
997
|
+
c.type === 'MemberExpression' &&
|
|
998
|
+
!c.computed &&
|
|
999
|
+
c.object.type === 'Identifier' &&
|
|
1000
|
+
(c.object.name === 'Date' || c.object.name === 'performance') &&
|
|
1001
|
+
!env.shadowedClock?.has(node)
|
|
1002
|
+
) {
|
|
1003
|
+
if (c.property.name === 'now')
|
|
1004
|
+
return {
|
|
1005
|
+
code:
|
|
1006
|
+
c.object.name === 'Date' ? 'app_date_now()' : 'app_perf_now()',
|
|
1007
|
+
cType: 'i64',
|
|
1008
|
+
};
|
|
1009
|
+
if (c.object.name === 'Date') throw dateObjectError();
|
|
1010
|
+
}
|
|
1011
|
+
if (
|
|
1012
|
+
c.type === 'Identifier' &&
|
|
1013
|
+
c.name === 'Date' &&
|
|
1014
|
+
!env.shadowedClock?.has(node)
|
|
1015
|
+
)
|
|
1016
|
+
throw dateObjectError();
|
|
1017
|
+
// Math.* helpers → libm (the generated C includes <math.h> when these appear).
|
|
491
1018
|
if (c.type === 'MemberExpression' && c.object.name === 'Math') {
|
|
492
1019
|
const fn = c.property.name;
|
|
493
|
-
const
|
|
1020
|
+
const timeDiv = emitTimeRoundDiv(fn, node.arguments, env);
|
|
1021
|
+
if (timeDiv) return timeDiv;
|
|
1022
|
+
const intDiv = emitIntRoundDiv(fn, node.arguments, env);
|
|
1023
|
+
if (intDiv) return intDiv;
|
|
1024
|
+
const a = litPeers(...node.arguments.map(x => emitExprWide(x, env)));
|
|
1025
|
+
if (a.some(x => x.cType === 'i64')) return emitMath64(fn, a);
|
|
1026
|
+
// Math.abs / min / max of ints stay whole, as rounding one does: through a float they rounded past 2^24
|
|
1027
|
+
// and printed as %g. Beside a 64-bit value |INT_MIN| is kept, as JS keeps it.
|
|
1028
|
+
if (a.length && a.every(x => x.cType === 'int')) {
|
|
1029
|
+
if (fn === 'abs' && a.length === 1)
|
|
1030
|
+
return env.math64
|
|
1031
|
+
? {code: `app_abs64(${a[0].code})`, cType: 'i64', wide: true}
|
|
1032
|
+
: {code: `app_abs(${a[0].code})`, cType: 'int'};
|
|
1033
|
+
if ((fn === 'min' || fn === 'max') && a.length === 2)
|
|
1034
|
+
return {
|
|
1035
|
+
code: `app_${fn}(${a[0].code}, ${a[1].code})`,
|
|
1036
|
+
cType: 'int',
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
// An int is already whole; app_f2i truncates a float toward zero, with NaN as 0 and the int range
|
|
1040
|
+
// saturated, which is Math.trunc kept as an int.
|
|
1041
|
+
if (fn === 'trunc' && a.length === 1)
|
|
1042
|
+
return a[0].cType === 'int'
|
|
1043
|
+
? {code: a[0].code, cType: 'int'}
|
|
1044
|
+
: {code: `app_f2i((float)(${a[0].code}))`, cType: 'int'};
|
|
494
1045
|
const UNARY = {
|
|
495
1046
|
sin: 'sinf',
|
|
496
1047
|
cos: 'cosf',
|
|
497
1048
|
tan: 'tanf',
|
|
498
1049
|
sqrt: 'sqrtf',
|
|
499
1050
|
abs: 'fabsf',
|
|
500
|
-
round: '
|
|
1051
|
+
round: 'app_roundf',
|
|
501
1052
|
floor: 'floorf',
|
|
502
1053
|
ceil: 'ceilf',
|
|
503
1054
|
};
|
|
504
1055
|
if (UNARY[fn] && a.length === 1) {
|
|
1056
|
+
const whole = fn === 'round' || fn === 'floor' || fn === 'ceil';
|
|
1057
|
+
// An int is already whole, so rounding leaves it as it is; a float round trip would lose digits.
|
|
1058
|
+
if (whole && a[0].cType === 'int')
|
|
1059
|
+
return {code: a[0].code, cType: 'int'};
|
|
505
1060
|
const inner = `${UNARY[fn]}((float)(${a[0].code}))`;
|
|
506
|
-
// round/floor/ceil yield a whole number
|
|
507
|
-
return
|
|
508
|
-
? {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'}
|
|
509
1064
|
: {code: inner, cType: 'float'};
|
|
510
1065
|
}
|
|
511
1066
|
const BINARY = {
|
|
@@ -525,15 +1080,67 @@ function emitExprImpl(node, env) {
|
|
|
525
1080
|
'AOT: unsupported call expression in a dynamic expression',
|
|
526
1081
|
);
|
|
527
1082
|
}
|
|
1083
|
+
case 'NewExpression':
|
|
1084
|
+
if (
|
|
1085
|
+
node.callee.type === 'Identifier' &&
|
|
1086
|
+
node.callee.name === 'Date' &&
|
|
1087
|
+
!env.shadowedClock?.has(node)
|
|
1088
|
+
)
|
|
1089
|
+
throw dateObjectError();
|
|
1090
|
+
break;
|
|
528
1091
|
}
|
|
529
1092
|
throw new Error(
|
|
530
1093
|
`AOT: unsupported expression "${node.type}" in a dynamic context`,
|
|
531
1094
|
);
|
|
532
1095
|
}
|
|
533
|
-
|
|
1096
|
+
/** emitExpr for the destinations that can hold a 64-bit timestamp: state, refs, locals, text, conditions. */
|
|
1097
|
+
const emitExprWide = withLoc(emitExprImpl);
|
|
534
1098
|
|
|
535
|
-
|
|
536
|
-
|
|
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
|
+
);
|
|
537
1144
|
const cTypeOfValue = v =>
|
|
538
1145
|
typeof v === 'string'
|
|
539
1146
|
? 'string'
|
|
@@ -541,6 +1148,140 @@ const cTypeOfValue = v =>
|
|
|
541
1148
|
? 'float'
|
|
542
1149
|
: 'int';
|
|
543
1150
|
|
|
1151
|
+
/** An aotError pinned to the expression that cannot be lowered to text (concatParts is not withLoc-wrapped). */
|
|
1152
|
+
function textShapeError(node, message, hint) {
|
|
1153
|
+
const e = aotError(message, hint);
|
|
1154
|
+
if (node.loc) e.aotLoc = node.loc.start;
|
|
1155
|
+
return e;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/**
|
|
1159
|
+
* Text a constant renders as a standalone JSX child. React draws nothing for null, undefined or a
|
|
1160
|
+
* boolean (see flattenTextChildren in Flow A), which is not how `+` treats the same values — a
|
|
1161
|
+
* concatenation operand goes through String() instead.
|
|
1162
|
+
*/
|
|
1163
|
+
const jsxChildText = v =>
|
|
1164
|
+
v === undefined || v === null || typeof v === 'boolean' ? '' : String(v);
|
|
1165
|
+
|
|
1166
|
+
/**
|
|
1167
|
+
* Splits a string-building `+` chain into printf parts, following JS's own left-to-right typing: a `+`
|
|
1168
|
+
* is a concatenation only once one of its sides is a string, so `n + 1 + ' ms'` still adds before it
|
|
1169
|
+
* appends. Parts are either a `literal` (folded into the format) or a `{spec, code}` pair (a runtime arg).
|
|
1170
|
+
*
|
|
1171
|
+
* @returns {{isString: boolean, parts: Array<{literal?: string, spec?: string, code?: string}>}}
|
|
1172
|
+
*/
|
|
1173
|
+
function concatParts(node, env, scope, operand = false) {
|
|
1174
|
+
// The global `undefined` (the name is reserved — see normalizeUndefined) renders as nothing for a
|
|
1175
|
+
// standalone child and as "undefined" when concatenated. It is handled here, the one place it has a
|
|
1176
|
+
// text meaning, rather than in the shared constant fold, where every prop reader would inherit it.
|
|
1177
|
+
if (node.type === 'Identifier' && node.name === 'undefined')
|
|
1178
|
+
return {isString: false, parts: [{literal: operand ? 'undefined' : ''}]};
|
|
1179
|
+
try {
|
|
1180
|
+
const v = evalStatic(node, scope);
|
|
1181
|
+
return {
|
|
1182
|
+
isString: typeof v === 'string',
|
|
1183
|
+
parts: [{literal: operand ? String(v) : jsxChildText(v)}],
|
|
1184
|
+
};
|
|
1185
|
+
} catch {
|
|
1186
|
+
/* not a compile-time constant — split it below */
|
|
1187
|
+
}
|
|
1188
|
+
if (node.type === 'BinaryExpression' && node.operator === '+') {
|
|
1189
|
+
const l = concatParts(node.left, env, scope, true);
|
|
1190
|
+
const r = concatParts(node.right, env, scope, true);
|
|
1191
|
+
if (l.isString || r.isString)
|
|
1192
|
+
return {isString: true, parts: [...l.parts, ...r.parts]};
|
|
1193
|
+
}
|
|
1194
|
+
// A branch or operand that itself concatenates (`on ? 'a' + s : 'b'`, `ok && 'n=' + n`) would need a
|
|
1195
|
+
// format of its own, and one snprintf has one format. Say that here, before emitExpr's generic "not
|
|
1196
|
+
// supported in this position" fires — its hint that text buffers are fine is exactly wrong here.
|
|
1197
|
+
const concatenates = n =>
|
|
1198
|
+
n.type === 'BinaryExpression' &&
|
|
1199
|
+
n.operator === '+' &&
|
|
1200
|
+
concatParts(n, env, scope, true).isString;
|
|
1201
|
+
if (
|
|
1202
|
+
node.type === 'ConditionalExpression' &&
|
|
1203
|
+
(concatenates(node.test) ||
|
|
1204
|
+
concatenates(node.consequent) ||
|
|
1205
|
+
concatenates(node.alternate))
|
|
1206
|
+
)
|
|
1207
|
+
throw textShapeError(
|
|
1208
|
+
node,
|
|
1209
|
+
'AOT: a ternary in text cannot concatenate inside its test or a branch',
|
|
1210
|
+
"each branch must be a single value — a literal, a state, or a number. Build the joined string first (a string useState set from a handler), or split it: {on ? 'a' : 'b'}{on ? s : ''}.",
|
|
1211
|
+
);
|
|
1212
|
+
if (
|
|
1213
|
+
node.type === 'LogicalExpression' &&
|
|
1214
|
+
(concatenates(node.left) || concatenates(node.right))
|
|
1215
|
+
)
|
|
1216
|
+
throw textShapeError(
|
|
1217
|
+
node,
|
|
1218
|
+
`AOT: "${node.operator}" in text cannot concatenate inside an operand`,
|
|
1219
|
+
"write it with plain values — {ok ? 'n=' : ''}{ok ? n : ''} — or build the joined string first in a string useState.",
|
|
1220
|
+
);
|
|
1221
|
+
const e = emitExprWide(node, env);
|
|
1222
|
+
// JS `&&`/`||` evaluate to one of their OPERANDS, and a ternary to one of its BRANCHES. The generated C
|
|
1223
|
+
// collapses a logical to 0/1 and gives a ternary a single slot, so text can only reproduce JS when the
|
|
1224
|
+
// operands agree in kind. Refuse rather than print a value the app never computed.
|
|
1225
|
+
if (node.type === 'LogicalExpression' && !e.isBool)
|
|
1226
|
+
throw textShapeError(
|
|
1227
|
+
node,
|
|
1228
|
+
`AOT: "${node.operator}" in text evaluates to one of its operands, not to true/false`,
|
|
1229
|
+
`\`a ${node.operator} b\` is a or b unless both sides are already booleans — the generated C only has 0/1. Write the branch out instead: {cond ? 'yes' : ''}.`,
|
|
1230
|
+
);
|
|
1231
|
+
if (
|
|
1232
|
+
node.type === 'ConditionalExpression' &&
|
|
1233
|
+
Boolean(emitExprWide(node.consequent, env).isBool) !==
|
|
1234
|
+
Boolean(emitExprWide(node.alternate, env).isBool)
|
|
1235
|
+
)
|
|
1236
|
+
throw textShapeError(
|
|
1237
|
+
node,
|
|
1238
|
+
'AOT: a ternary in text mixes a boolean branch with a non-boolean one',
|
|
1239
|
+
'JS renders those differently (`cond ? true : 5` is "true" or "5") but they share one C slot here. Make both branches the same kind.',
|
|
1240
|
+
);
|
|
1241
|
+
// A boolean draws nothing as a child but stringifies as an operand — same split as the constants above.
|
|
1242
|
+
// isString stays FALSE either way: a boolean is not a string in JS, so it must not by itself put an
|
|
1243
|
+
// enclosing `+` into concatenation mode (`on + n` adds, giving 0, and only then does `+ 'x'` append).
|
|
1244
|
+
// The %s form below is picked up only when some other operand of that `+` really is a string.
|
|
1245
|
+
if (e.isBool)
|
|
1246
|
+
return operand
|
|
1247
|
+
? {
|
|
1248
|
+
isString: false,
|
|
1249
|
+
parts: [{spec: '%s', code: `((${e.code}) ? "true" : "false")`}],
|
|
1250
|
+
}
|
|
1251
|
+
: {isString: false, parts: [{literal: ''}]};
|
|
1252
|
+
return {
|
|
1253
|
+
isString: e.cType === 'string',
|
|
1254
|
+
parts: [printfPart(e)],
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
/**
|
|
1259
|
+
* Lowers an expression to a printf format + args for a char-buffer destination (a <Text> body, a string
|
|
1260
|
+
* state slot, a <TextInput value>). A string-building `+` chain becomes one spec per dynamic part with
|
|
1261
|
+
* the literals folded into the format; anything else is a single spec over its own value.
|
|
1262
|
+
*
|
|
1263
|
+
* @returns {{format: string, args: string[]}} `format` already has literal `%` escaped as `%%`.
|
|
1264
|
+
*/
|
|
1265
|
+
function emitFormat(node, env, scope = env.consts ?? {}) {
|
|
1266
|
+
const visible = foldScope(env, scope);
|
|
1267
|
+
let format = '';
|
|
1268
|
+
const args = [];
|
|
1269
|
+
for (const part of concatParts(node, env, visible).parts) {
|
|
1270
|
+
if (part.literal !== undefined) format += part.literal.replace(/%/g, '%%');
|
|
1271
|
+
else {
|
|
1272
|
+
format += part.spec;
|
|
1273
|
+
args.push(part.code);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
return {format, args};
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/** Renders an emitFormat() result as snprintf's trailing arguments (a constant string keeps its `%s` form). */
|
|
1280
|
+
const formatArgs = ({format, args}) =>
|
|
1281
|
+
args.length
|
|
1282
|
+
? `${cstr(format)}, ${args.join(', ')}`
|
|
1283
|
+
: `"%s", ${cstr(format.replace(/%%/g, '%'))}`;
|
|
1284
|
+
|
|
544
1285
|
// ---------------------------------------------------------------------------------------------------
|
|
545
1286
|
// AST helpers + collection passes — small predicates (isFn, fnReturnsJSX, …) and the up-front scans
|
|
546
1287
|
// that walk the component body ONCE to gather what later emission needs: the module scope, useState,
|
|
@@ -577,6 +1318,29 @@ const SCREEN_FROM_ENV =
|
|
|
577
1318
|
Number(process.env.ER_AOT_SCREEN_W) > 0 &&
|
|
578
1319
|
Number(process.env.ER_AOT_SCREEN_H) > 0;
|
|
579
1320
|
|
|
1321
|
+
/**
|
|
1322
|
+
* Every name a variable declaration directly in `body` binds, destructuring included. In JS each one
|
|
1323
|
+
* shadows a module binding of that name for the whole function body, not only from its declaration on.
|
|
1324
|
+
*/
|
|
1325
|
+
function declaredNames(body) {
|
|
1326
|
+
const names = [];
|
|
1327
|
+
const walk = p => {
|
|
1328
|
+
if (!p) return;
|
|
1329
|
+
if (p.type === 'Identifier') names.push(p.name);
|
|
1330
|
+
else if (p.type === 'ArrayPattern') p.elements.forEach(walk);
|
|
1331
|
+
else if (p.type === 'ObjectPattern')
|
|
1332
|
+
p.properties.forEach(q =>
|
|
1333
|
+
walk(q.type === 'RestElement' ? q.argument : q.value),
|
|
1334
|
+
);
|
|
1335
|
+
else if (p.type === 'AssignmentPattern') walk(p.left);
|
|
1336
|
+
else if (p.type === 'RestElement') walk(p.argument);
|
|
1337
|
+
};
|
|
1338
|
+
for (const stmt of body)
|
|
1339
|
+
if (stmt.type === 'VariableDeclaration')
|
|
1340
|
+
for (const d of stmt.declarations) walk(d.id);
|
|
1341
|
+
return names;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
580
1344
|
function moduleScope(program, screen, seed = {}) {
|
|
581
1345
|
// `seed` pre-populates the scope (e.g. image imports as their asset-name strings) BEFORE module consts are
|
|
582
1346
|
// folded, so a const that references one — `const DAYS = [{ icon: wxSun }]` — folds correctly.
|
|
@@ -593,7 +1357,7 @@ function moduleScope(program, screen, seed = {}) {
|
|
|
593
1357
|
)
|
|
594
1358
|
continue;
|
|
595
1359
|
try {
|
|
596
|
-
scope[decl.id.name] = evalStatic(decl.init, scope);
|
|
1360
|
+
scope[decl.id.name] = evalStatic(decl.init, withUndefined(scope));
|
|
597
1361
|
} catch {
|
|
598
1362
|
/* not a static const — skip */
|
|
599
1363
|
}
|
|
@@ -647,7 +1411,7 @@ function inferItemStruct(items, name) {
|
|
|
647
1411
|
* lookup keys stay the bare JS names (`count`), but the C field / array / count derive from `cField`
|
|
648
1412
|
* (`<prefix>count`). prefix='' (the App) leaves storage names exactly as the JS names — backward compatible.
|
|
649
1413
|
*/
|
|
650
|
-
function collectState(fnBody, scope, prefix = '') {
|
|
1414
|
+
function collectState(fnBody, scope, prefix = '', wide = NO_WIDE) {
|
|
651
1415
|
const byName = new Map();
|
|
652
1416
|
const bySetter = new Map();
|
|
653
1417
|
for (const stmt of fnBody.body) {
|
|
@@ -716,7 +1480,24 @@ function collectState(fnBody, scope, prefix = '') {
|
|
|
716
1480
|
`AOT: useHostValue("${name}") must be a number — its initial value evaluated to ${JSON.stringify(initVal)}`,
|
|
717
1481
|
'useHostValue(0) / useHostValue(0.0) — the host feeds an int or float; booleans, strings, and objects are not supported.',
|
|
718
1482
|
);
|
|
1483
|
+
// A scalar slot is an int, float, string or boolean. `null` or NaN would otherwise fold into an
|
|
1484
|
+
// initializer like `.value = NaN` — invalid C, with no location.
|
|
1485
|
+
if (
|
|
1486
|
+
initVal === undefined ||
|
|
1487
|
+
initVal === null ||
|
|
1488
|
+
(typeof initVal === 'number' && !Number.isFinite(initVal))
|
|
1489
|
+
) {
|
|
1490
|
+
const e = aotError(
|
|
1491
|
+
`AOT: the initial value of state "${name}" is ${initVal === undefined ? 'undefined' : String(initVal)}`,
|
|
1492
|
+
"give it a concrete starting value: useState(0), useState(''), useState(false).",
|
|
1493
|
+
);
|
|
1494
|
+
if (initArg?.loc) e.aotLoc = initArg.loc.start;
|
|
1495
|
+
throw e;
|
|
1496
|
+
}
|
|
719
1497
|
let cType = cTypeOfValue(initVal);
|
|
1498
|
+
// JS prints a boolean as "true"/"false" and React renders one as nothing, so text lowering has
|
|
1499
|
+
// to tell useState(false) from useState(0) — cTypeOfValue funnels both to 'int'.
|
|
1500
|
+
const isBool = typeof initVal === 'boolean';
|
|
720
1501
|
// A numeric literal written with a decimal point or exponent (e.g. useState(70.0)) forces a FLOAT
|
|
721
1502
|
// slot even though the value is integral — lets the state hold sub-integer values (a smooth drag)
|
|
722
1503
|
// while the UI shows Math.round(value). (70.0 === 70 in JS, so we read the raw source to tell them apart.)
|
|
@@ -728,19 +1509,24 @@ function collectState(fnBody, scope, prefix = '') {
|
|
|
728
1509
|
) {
|
|
729
1510
|
cType = 'float';
|
|
730
1511
|
}
|
|
1512
|
+
// A setter stores a timestamp in it, so it holds 64 bits (see compileWidened).
|
|
1513
|
+
if (cType === 'int' && !isBool && wide.has(cField)) cType = 'i64';
|
|
731
1514
|
// String scalar → a fixed char buffer in ErAppState; setters snprintf into it (see scalarAssign).
|
|
732
1515
|
const initCode =
|
|
733
1516
|
cType === 'string'
|
|
734
1517
|
? cstr(String(initVal))
|
|
735
1518
|
: cType === 'float'
|
|
736
1519
|
? floatLit(initVal)
|
|
737
|
-
:
|
|
1520
|
+
: cType === 'i64'
|
|
1521
|
+
? i64Lit(Number(initVal))
|
|
1522
|
+
: String(Number(initVal));
|
|
738
1523
|
rec = {
|
|
739
1524
|
name,
|
|
740
1525
|
cField,
|
|
741
1526
|
setter,
|
|
742
1527
|
kind: 'scalar',
|
|
743
1528
|
cType,
|
|
1529
|
+
isBool,
|
|
744
1530
|
cMember: `s_state.${cField}`,
|
|
745
1531
|
initCode,
|
|
746
1532
|
host: isHost, // host-fed → also emit a public er_app_set_<name>() setter
|
|
@@ -1083,8 +1869,23 @@ function collectAnims(fnBody, scope, prefix = '') {
|
|
|
1083
1869
|
decl.id.type === 'Identifier'
|
|
1084
1870
|
) {
|
|
1085
1871
|
const initVal = init.arguments[0]
|
|
1086
|
-
?
|
|
1872
|
+
? evalStaticOrThrow(
|
|
1873
|
+
init.arguments[0],
|
|
1874
|
+
scope,
|
|
1875
|
+
`AOT: the initial value of useAnimatedValue "${decl.id.name}" must be a compile-time constant`,
|
|
1876
|
+
'give it a finite starting number: useAnimatedValue(0).',
|
|
1877
|
+
)
|
|
1087
1878
|
: 0;
|
|
1879
|
+
// An animated value is a float slot; null or a non-finite number would reach C as `NaNf`.
|
|
1880
|
+
// Refuse here, at the declaration, with its location.
|
|
1881
|
+
if (typeof initVal !== 'number' || !Number.isFinite(initVal)) {
|
|
1882
|
+
const e = aotError(
|
|
1883
|
+
`AOT: the initial value of useAnimatedValue "${decl.id.name}" is ${initVal === undefined ? 'undefined' : String(initVal)}`,
|
|
1884
|
+
'give it a finite starting number: useAnimatedValue(0).',
|
|
1885
|
+
);
|
|
1886
|
+
if (init.arguments[0]?.loc) e.aotLoc = init.arguments[0].loc.start;
|
|
1887
|
+
throw e;
|
|
1888
|
+
}
|
|
1088
1889
|
anims.set(decl.id.name, {
|
|
1089
1890
|
cVar: `s_av_${prefix}${decl.id.name}`,
|
|
1090
1891
|
initCode: floatLit(initVal),
|
|
@@ -1102,7 +1903,7 @@ function collectAnims(fnBody, scope, prefix = '') {
|
|
|
1102
1903
|
* - NODE ref (`useRef()` / `useRef(null)`): holds an `ERNode*`, captured by `ref={r}` on an element and
|
|
1103
1904
|
* used as the target of imperative calls like updateVector(r, …). kind === 'node'.
|
|
1104
1905
|
*/
|
|
1105
|
-
function collectRefs(fnBody, scope, prefix = '') {
|
|
1906
|
+
function collectRefs(fnBody, scope, prefix = '', wide = NO_WIDE) {
|
|
1106
1907
|
const refs = new Map();
|
|
1107
1908
|
if (fnBody.type !== 'BlockStatement') return refs;
|
|
1108
1909
|
for (const stmt of fnBody.body) {
|
|
@@ -1127,16 +1928,35 @@ function collectRefs(fnBody, scope, prefix = '') {
|
|
|
1127
1928
|
});
|
|
1128
1929
|
continue;
|
|
1129
1930
|
}
|
|
1130
|
-
const v =
|
|
1131
|
-
|
|
1132
|
-
|
|
1931
|
+
const v = evalStaticOrThrow(
|
|
1932
|
+
arg,
|
|
1933
|
+
scope,
|
|
1934
|
+
`AOT: useRef initial for "${decl.id.name}" must be a number (value ref) or null/empty (node ref)`,
|
|
1935
|
+
'a value ref needs a compile-time number: useRef(0).',
|
|
1936
|
+
);
|
|
1937
|
+
if (typeof v !== 'number' || !Number.isFinite(v)) {
|
|
1938
|
+
const e = aotError(
|
|
1133
1939
|
`AOT: useRef initial for "${decl.id.name}" must be a number (value ref) or null/empty (node ref)`,
|
|
1940
|
+
`got ${v === undefined ? 'undefined' : String(v)}.`,
|
|
1134
1941
|
);
|
|
1135
|
-
|
|
1942
|
+
if (arg.loc) e.aotLoc = arg.loc.start;
|
|
1943
|
+
throw e;
|
|
1944
|
+
}
|
|
1945
|
+
// A ref a timestamp is written to holds 64 bits (see compileWidened).
|
|
1946
|
+
const cType = !Number.isInteger(v)
|
|
1947
|
+
? 'float'
|
|
1948
|
+
: wide.has(cVar)
|
|
1949
|
+
? 'i64'
|
|
1950
|
+
: 'int';
|
|
1136
1951
|
refs.set(decl.id.name, {
|
|
1137
1952
|
cVar,
|
|
1138
1953
|
cType,
|
|
1139
|
-
initCode:
|
|
1954
|
+
initCode:
|
|
1955
|
+
cType === 'float'
|
|
1956
|
+
? floatLit(v)
|
|
1957
|
+
: cType === 'i64'
|
|
1958
|
+
? i64Lit(v)
|
|
1959
|
+
: String(v),
|
|
1140
1960
|
kind: 'value',
|
|
1141
1961
|
used: false,
|
|
1142
1962
|
});
|
|
@@ -1174,7 +1994,25 @@ const ANIM_TRANSFORM_PROPS = {
|
|
|
1174
1994
|
/** Formats a number as a valid C float literal (`1` → `1.0f`, not `1f` which doesn't compile). */
|
|
1175
1995
|
function floatLit(n) {
|
|
1176
1996
|
const v = Number(n);
|
|
1177
|
-
|
|
1997
|
+
// `NaNf` / `Infinityf` / `undefinedf` are not C. Every numeric-literal path funnels through here, so a
|
|
1998
|
+
// value that slipped past its own boundary check still fails at generate time, never in the host compiler.
|
|
1999
|
+
if (!Number.isFinite(v))
|
|
2000
|
+
throw aotError(
|
|
2001
|
+
`AOT: a numeric constant folded to ${n === undefined ? 'undefined' : String(n)}, which has no C form`,
|
|
2002
|
+
'the value must be a finite number.',
|
|
2003
|
+
);
|
|
2004
|
+
// Past about 3.4e38 a float literal overflows to Infinity, which C compilers warn about, so it is refused
|
|
2005
|
+
// as Infinity is. One too small for a float, which they also warn about, is written as the 0 it rounds to.
|
|
2006
|
+
const f = Math.fround(v);
|
|
2007
|
+
if (!Number.isFinite(f))
|
|
2008
|
+
throw aotError(
|
|
2009
|
+
`AOT: the numeric constant ${v} is past the float range`,
|
|
2010
|
+
'a float holds up to about 3.4e38.',
|
|
2011
|
+
);
|
|
2012
|
+
if (f === 0 && v !== 0) return v < 0 ? '-0.0f' : '0.0f';
|
|
2013
|
+
// An exponent (`1e+21`) already makes a float literal; `.0` after one would not be C.
|
|
2014
|
+
const s = String(v);
|
|
2015
|
+
return /[.e]/.test(s) ? `${s}f` : `${s}.0f`;
|
|
1178
2016
|
}
|
|
1179
2017
|
|
|
1180
2018
|
/** The polynomial family of an `Easing.quad` / `Easing.cubic` node, for in/out/inOut composition. */
|
|
@@ -1311,12 +2149,12 @@ function argbLiteral(value) {
|
|
|
1311
2149
|
function emitColorExpr(node, env) {
|
|
1312
2150
|
if (node.type === 'StringLiteral') return colorLiteral(node.value);
|
|
1313
2151
|
if (node.type === 'ConditionalExpression') {
|
|
1314
|
-
const t = emitExpr(node.test, env)
|
|
2152
|
+
const t = asCond(emitExpr(node.test, env));
|
|
1315
2153
|
return `((${t}) ? ${emitColorExpr(node.consequent, env)} : ${emitColorExpr(node.alternate, env)})`;
|
|
1316
2154
|
}
|
|
1317
2155
|
// A statically-resolvable color (a const string, or a theme token like `theme.card`) folds to a literal.
|
|
1318
2156
|
try {
|
|
1319
|
-
const s = evalStatic(node, env.consts ?? {});
|
|
2157
|
+
const s = evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
1320
2158
|
if (typeof s === 'string') return colorLiteral(s);
|
|
1321
2159
|
} catch {
|
|
1322
2160
|
/* not static — fall through to the error below */
|
|
@@ -1339,12 +2177,12 @@ function emitEnumExpr(node, table, env) {
|
|
|
1339
2177
|
return c;
|
|
1340
2178
|
}
|
|
1341
2179
|
if (node.type === 'ConditionalExpression') {
|
|
1342
|
-
const t = emitExpr(node.test, env)
|
|
2180
|
+
const t = asCond(emitExpr(node.test, env));
|
|
1343
2181
|
return `((${t}) ? ${emitEnumExpr(node.consequent, table, env)} : ${emitEnumExpr(node.alternate, table, env)})`;
|
|
1344
2182
|
}
|
|
1345
2183
|
// A statically resolvable enum (a const string) folds to its constant.
|
|
1346
2184
|
try {
|
|
1347
|
-
const s = evalStatic(node, env.consts ?? {});
|
|
2185
|
+
const s = evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
1348
2186
|
if (typeof s === 'string' && table[s]) return table[s];
|
|
1349
2187
|
} catch {
|
|
1350
2188
|
/* not static — fall through */
|
|
@@ -1355,9 +2193,41 @@ function emitEnumExpr(node, table, env) {
|
|
|
1355
2193
|
);
|
|
1356
2194
|
}
|
|
1357
2195
|
|
|
2196
|
+
/** The diagnostic for a style key the AOT has no lowering for, static or dynamic. */
|
|
2197
|
+
const unknownStyleKey = key =>
|
|
2198
|
+
aotError(
|
|
2199
|
+
`AOT: style "${key}" is not supported by the AOT (no ERProps lowering)`,
|
|
2200
|
+
`Flow A may accept it; Flow B lowers these: ${STYLE_KEYS.join(', ')}.`,
|
|
2201
|
+
);
|
|
2202
|
+
|
|
2203
|
+
/**
|
|
2204
|
+
* Lowers one STATIC style key/value, telling the two failures apart: a key the AOT has no lowering for
|
|
2205
|
+
* at all, and a known key whose value it rejects. Both used to be indistinguishable from a state-driven
|
|
2206
|
+
* value, because a single `try` covered the constant fold and the lowering together.
|
|
2207
|
+
*/
|
|
2208
|
+
function lowerStyleChecked(key, value) {
|
|
2209
|
+
// `{transform: undefined}` is a no-op in Flow A and in lowerStyle itself; the key is only judged when
|
|
2210
|
+
// there is a value to lower.
|
|
2211
|
+
if (value === undefined || value === null) return [];
|
|
2212
|
+
if (!isStyleKey(key)) throw unknownStyleKey(key);
|
|
2213
|
+
try {
|
|
2214
|
+
return lowerStyle({[key]: value});
|
|
2215
|
+
} catch (e) {
|
|
2216
|
+
// style-map's own value errors already name the key in some cases — don't say it twice.
|
|
2217
|
+
const msg = String(e.message);
|
|
2218
|
+
const why = msg.startsWith(`${key}: `) ? msg.slice(key.length + 2) : msg;
|
|
2219
|
+
throw aotError(`AOT: unsupported value for style "${key}": ${why}`);
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
|
|
1358
2223
|
/** Lowers one dynamic inline-style value to ERProps field assignment(s) (C expressions). */
|
|
1359
2224
|
function lowerDynamicStyleValue(key, valueNode, env) {
|
|
1360
|
-
|
|
2225
|
+
// Own-property only: `DYN_FIELDS.toString` would otherwise hand back Object.prototype's method, look
|
|
2226
|
+
// like a known key, and emit `p.undefined = ...`.
|
|
2227
|
+
const meta = Object.hasOwn(DYN_FIELDS, key) ? DYN_FIELDS[key] : undefined;
|
|
2228
|
+
// An unknown key is unsupported outright — telling the author to "make it static" would only move
|
|
2229
|
+
// them on to the unknown-key error.
|
|
2230
|
+
if (!meta && !isStyleKey(key)) throw unknownStyleKey(key);
|
|
1361
2231
|
if (!meta)
|
|
1362
2232
|
throw aotError(
|
|
1363
2233
|
`AOT: a state-driven value for style "${key}" is not supported (static only)`,
|
|
@@ -1365,23 +2235,23 @@ function lowerDynamicStyleValue(key, valueNode, env) {
|
|
|
1365
2235
|
);
|
|
1366
2236
|
if (meta.kind === 'color')
|
|
1367
2237
|
return [{field: meta.field, code: emitColorExpr(valueNode, env)}];
|
|
1368
|
-
if (meta.kind === 'opacity')
|
|
1369
|
-
return [
|
|
1370
|
-
{
|
|
1371
|
-
field: meta.field,
|
|
1372
|
-
code: `(uint8_t)((${emitExpr(valueNode, env).code}) * 255.0f)`,
|
|
1373
|
-
},
|
|
1374
|
-
];
|
|
1375
2238
|
if (meta.kind === 'enum')
|
|
1376
2239
|
return [
|
|
1377
2240
|
{field: meta.field, code: emitEnumExpr(valueNode, meta.table, env)},
|
|
1378
2241
|
];
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
2242
|
+
// Opacity and every size are numbers; C would take a char[] here as its address, or refuse it.
|
|
2243
|
+
const e = emitExpr(valueNode, env);
|
|
2244
|
+
if (e.cType === 'string') {
|
|
2245
|
+
const err = aotError(
|
|
2246
|
+
`AOT: style "${key}" needs a number, but the value is a string`,
|
|
2247
|
+
"JS would coerce the string; C cannot. Keep the state numeric — useState(10), not useState('10').",
|
|
2248
|
+
);
|
|
2249
|
+
if (valueNode.loc) err.aotLoc = valueNode.loc.start;
|
|
2250
|
+
throw err;
|
|
2251
|
+
}
|
|
2252
|
+
if (meta.kind === 'opacity')
|
|
2253
|
+
return [{field: meta.field, code: `app_opacity(${e.code})`}];
|
|
2254
|
+
return [{field: meta.field, code: `app_round_dim(${e.code})`}]; /* num */
|
|
1385
2255
|
}
|
|
1386
2256
|
|
|
1387
2257
|
/**
|
|
@@ -1431,6 +2301,8 @@ function collectStyleAssigns(openingElement, scope, env) {
|
|
|
1431
2301
|
return null;
|
|
1432
2302
|
};
|
|
1433
2303
|
const apply = expr => {
|
|
2304
|
+
// RN ignores an undefined style or style-array entry; so does Flow A's flattenStyle.
|
|
2305
|
+
if (expr.type === 'Identifier' && expr.name === 'undefined') return;
|
|
1434
2306
|
if (expr.type === 'ArrayExpression') {
|
|
1435
2307
|
for (const e of expr.elements) if (e) apply(e);
|
|
1436
2308
|
return;
|
|
@@ -1444,6 +2316,9 @@ function collectStyleAssigns(openingElement, scope, env) {
|
|
|
1444
2316
|
const key = prop.computed
|
|
1445
2317
|
? evalStatic(prop.key, scope)
|
|
1446
2318
|
: (prop.key.name ?? prop.key.value);
|
|
2319
|
+
// `{transform: undefined}` is a no-op in RN and Flow A.
|
|
2320
|
+
if (prop.value.type === 'Identifier' && prop.value.name === 'undefined')
|
|
2321
|
+
continue;
|
|
1447
2322
|
|
|
1448
2323
|
// Animated value bound directly to a prop (opacity / backgroundColor / color), optionally through
|
|
1449
2324
|
// an .interpolate({ inputRange, outputRange }) mapping.
|
|
@@ -1484,19 +2359,35 @@ function collectStyleAssigns(openingElement, scope, env) {
|
|
|
1484
2359
|
if (handled) continue;
|
|
1485
2360
|
}
|
|
1486
2361
|
|
|
2362
|
+
// Only the FOLD may fall back to the dynamic path. Letting lowerStyle's own failure fall
|
|
2363
|
+
// through too made an unknown style key surface as "state-driven value ... (static only)",
|
|
2364
|
+
// which sends the author looking for state that isn't there.
|
|
2365
|
+
let staticValue;
|
|
1487
2366
|
try {
|
|
1488
|
-
|
|
1489
|
-
fields.set(a.field, {dynamic: false, code: a.expr});
|
|
2367
|
+
staticValue = {v: evalStatic(prop.value, withUndefined(scope))};
|
|
1490
2368
|
} catch {
|
|
2369
|
+
staticValue = null; // references state — lower it as a dynamic value
|
|
2370
|
+
}
|
|
2371
|
+
if (staticValue) {
|
|
2372
|
+
for (const a of lowerStyleChecked(key, staticValue.v))
|
|
2373
|
+
fields.set(a.field, {dynamic: false, code: a.expr});
|
|
2374
|
+
} else {
|
|
1491
2375
|
for (const a of lowerDynamicStyleValue(key, prop.value, env))
|
|
1492
2376
|
fields.set(a.field, {dynamic: true, code: a.code});
|
|
1493
2377
|
}
|
|
1494
2378
|
}
|
|
1495
2379
|
return;
|
|
1496
2380
|
}
|
|
1497
|
-
// A StyleSheet reference / identifier resolving to a static style object.
|
|
1498
|
-
|
|
1499
|
-
|
|
2381
|
+
// A StyleSheet reference / identifier resolving to a static style object. `style={null}` and a false
|
|
2382
|
+
// `cond && s` are valid RN and mean no style — Object.entries would throw on null.
|
|
2383
|
+
const resolved = evalStatic(expr, withUndefined(scope));
|
|
2384
|
+
if (resolved === null || resolved === undefined || resolved === false)
|
|
2385
|
+
return;
|
|
2386
|
+
for (const [k, v] of Object.entries(resolved)) {
|
|
2387
|
+
if (v === undefined || v === null) continue;
|
|
2388
|
+
for (const a of lowerStyleChecked(k, v))
|
|
2389
|
+
fields.set(a.field, {dynamic: false, code: a.expr});
|
|
2390
|
+
}
|
|
1500
2391
|
};
|
|
1501
2392
|
for (const attr of openingElement.attributes) {
|
|
1502
2393
|
if (attr.type !== 'JSXAttribute' || attr.name.name !== 'style') continue;
|
|
@@ -1542,18 +2433,11 @@ function buildText(children, scope, env) {
|
|
|
1542
2433
|
format += t.replace(/%/g, '%%');
|
|
1543
2434
|
} else if (child.type === 'JSXExpressionContainer') {
|
|
1544
2435
|
if (child.expression.type === 'JSXEmptyExpression') continue;
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
);
|
|
1551
|
-
} catch {
|
|
1552
|
-
const e = emitExpr(child.expression, env); // references state → dynamic
|
|
1553
|
-
format += printfSpec(e.cType);
|
|
1554
|
-
args.push(e.code);
|
|
1555
|
-
dynamic = true;
|
|
1556
|
-
}
|
|
2436
|
+
// Constants fold into the literal; anything referencing state contributes a spec + arg.
|
|
2437
|
+
const f = emitFormat(child.expression, env, scope);
|
|
2438
|
+
format += f.format;
|
|
2439
|
+
args.push(...f.args);
|
|
2440
|
+
if (f.args.length) dynamic = true;
|
|
1557
2441
|
} else if (child.type === 'JSXElement') {
|
|
1558
2442
|
throw new Error(
|
|
1559
2443
|
'AOT: nested <Text> / element children inside <Text> not yet supported (spans)',
|
|
@@ -1589,7 +2473,7 @@ function staticTextContent(children, scope) {
|
|
|
1589
2473
|
c.expression.type !== 'JSXEmptyExpression'
|
|
1590
2474
|
) {
|
|
1591
2475
|
const v = evalStatic(c.expression, scope); // throws if it references state
|
|
1592
|
-
|
|
2476
|
+
s += jsxChildText(v);
|
|
1593
2477
|
} else if (c.type === 'JSXElement')
|
|
1594
2478
|
throw aotError(
|
|
1595
2479
|
'AOT: a nested <Text> span may not itself contain another <Text> (one level of spans only)',
|
|
@@ -1637,7 +2521,8 @@ function collectTextSpans(children, scope, env) {
|
|
|
1637
2521
|
'spans must be static; keep dynamic text in its own single <Text> (no nested <Text> siblings).',
|
|
1638
2522
|
);
|
|
1639
2523
|
}
|
|
1640
|
-
|
|
2524
|
+
// React draws nothing for null, undefined, or a boolean child.
|
|
2525
|
+
if (v !== undefined && v !== null && typeof v !== 'boolean')
|
|
1641
2526
|
spans.push(inheritSpan(cstr(String(v))));
|
|
1642
2527
|
} else if (
|
|
1643
2528
|
c.type === 'JSXElement' &&
|
|
@@ -1705,36 +2590,49 @@ function compileListOp(rec, arg, env) {
|
|
|
1705
2590
|
for (const f of struct.fields) {
|
|
1706
2591
|
const valNode = props.get(f.key);
|
|
1707
2592
|
if (!valNode) continue;
|
|
1708
|
-
const e = emitExpr(valNode, env);
|
|
1709
2593
|
if (f.kind === 'string')
|
|
1710
2594
|
lines.push(
|
|
1711
|
-
` snprintf(${arr}[${cnt}].${f.key}, sizeof(${arr}[${cnt}].${f.key}),
|
|
2595
|
+
` snprintf(${arr}[${cnt}].${f.key}, sizeof(${arr}[${cnt}].${f.key}), ${formatArgs(emitFormat(valNode, env))});`,
|
|
2596
|
+
);
|
|
2597
|
+
else
|
|
2598
|
+
lines.push(
|
|
2599
|
+
` ${arr}[${cnt}].${f.key} = ${storeCode(emitExpr(valNode, env), f.kind)};`,
|
|
1712
2600
|
);
|
|
1713
|
-
else lines.push(` ${arr}[${cnt}].${f.key} = ${e.code};`);
|
|
1714
2601
|
}
|
|
1715
2602
|
lines.push(` ${cnt}++;`, ' }');
|
|
1716
2603
|
}
|
|
1717
2604
|
return lines;
|
|
1718
2605
|
}
|
|
1719
|
-
// setItems(items.slice(0,
|
|
2606
|
+
// setItems(items.slice(0, end)) keeps the first items, counted as JS counts them: a negative end counts back
|
|
2607
|
+
// from the length and stops at 0, and an end past the length (or none) keeps every item.
|
|
1720
2608
|
if (
|
|
1721
2609
|
arg.type === 'CallExpression' &&
|
|
1722
2610
|
arg.callee.type === 'MemberExpression' &&
|
|
1723
2611
|
arg.callee.object.name === rec.name &&
|
|
1724
2612
|
arg.callee.property.name === 'slice'
|
|
1725
2613
|
) {
|
|
1726
|
-
const end = arg.arguments
|
|
1727
|
-
if (
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
2614
|
+
const [start, end] = arg.arguments;
|
|
2615
|
+
if (start && staticInt(start, env) !== 0)
|
|
2616
|
+
throw aotError(
|
|
2617
|
+
`AOT: only ${rec.name}.slice(0, end) is supported on a list`,
|
|
2618
|
+
`a list is a fixed C array and a count, so a slice can only drop items from the end — e.g. ${rec.name}.slice(0, -1) drops the last one.`,
|
|
2619
|
+
);
|
|
2620
|
+
if (!end) return [];
|
|
2621
|
+
// A constant end is settled here. Past the capacity it keeps every item either way, so it is clamped
|
|
2622
|
+
// there and never needs 64-bit math.
|
|
2623
|
+
const k = staticInt(end, env);
|
|
2624
|
+
if (k !== null) {
|
|
2625
|
+
const kk = Math.max(-cap, Math.min(cap, k));
|
|
2626
|
+
if (kk === -1) return [` if (${cnt} > 0) ${cnt}--;`];
|
|
2627
|
+
if (kk >= 0) return [` ${cnt} = (${cnt} < ${kk}) ? ${cnt} : ${kk};`];
|
|
2628
|
+
return [` ${cnt} = app_slice_len(${cnt}, ${kk});`];
|
|
2629
|
+
}
|
|
2630
|
+
return [
|
|
2631
|
+
` ${cnt} = app_slice_len(${cnt}, ${asInt(emitExpr(end, env))});`,
|
|
2632
|
+
];
|
|
1735
2633
|
}
|
|
1736
2634
|
throw new Error(
|
|
1737
|
-
`AOT: unsupported list operation on "${rec.name}" (use [...${rec.name}, item], ${rec.name}.slice(0,
|
|
2635
|
+
`AOT: unsupported list operation on "${rec.name}" (use [...${rec.name}, item], ${rec.name}.slice(0, n), or [])`,
|
|
1738
2636
|
);
|
|
1739
2637
|
}
|
|
1740
2638
|
|
|
@@ -1804,11 +2702,8 @@ function emitAnimEntry(entry, env, idx, onCompleteCb) {
|
|
|
1804
2702
|
* `duration` is this node's own run length in ms, used to offset later siblings in a sequence/stagger;
|
|
1805
2703
|
* null = unknown (spring/decay/loop), which is illegal to sequence anything after. */
|
|
1806
2704
|
function flattenAnim(node, env, baseDelay, loop) {
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
node.callee.type !== 'MemberExpression' ||
|
|
1810
|
-
node.callee.object?.name !== 'Animated'
|
|
1811
|
-
)
|
|
2705
|
+
node = resolveAnim(node, env);
|
|
2706
|
+
if (!isAnimatedCall(node))
|
|
1812
2707
|
throw aotError(
|
|
1813
2708
|
'AOT: an animation must be Animated.timing/spring/decay/sequence/parallel/stagger/delay/loop(...)',
|
|
1814
2709
|
);
|
|
@@ -1888,31 +2783,89 @@ function flattenAnim(node, env, baseDelay, loop) {
|
|
|
1888
2783
|
const r = flattenAnim(args[0], env, baseDelay, true);
|
|
1889
2784
|
if (r.entries.length !== 1)
|
|
1890
2785
|
throw aotError(
|
|
1891
|
-
'AOT: Animated.loop
|
|
2786
|
+
'AOT: an Animated.loop inside another composition can only wrap a single Animated.timing/spring/decay',
|
|
2787
|
+
'a loop around a sequence works when the loop is the animation you start: Animated.loop(Animated.sequence([...])).start().',
|
|
1892
2788
|
);
|
|
1893
2789
|
return {entries: r.entries, duration: null};
|
|
1894
2790
|
}
|
|
1895
2791
|
throw aotError(`AOT: Animated.${kind}(...) is not a supported animation`);
|
|
1896
2792
|
}
|
|
1897
2793
|
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
2794
|
+
const ANIM_KINDS = new Set([
|
|
2795
|
+
'timing',
|
|
2796
|
+
'spring',
|
|
2797
|
+
'decay',
|
|
2798
|
+
'sequence',
|
|
2799
|
+
'parallel',
|
|
2800
|
+
'stagger',
|
|
2801
|
+
'delay',
|
|
2802
|
+
'loop',
|
|
2803
|
+
]);
|
|
2804
|
+
|
|
2805
|
+
/** True for an `Animated.timing/spring/…/loop(…)` call: an animation, not a value. */
|
|
2806
|
+
const isAnimatedCall = n =>
|
|
2807
|
+
n?.type === 'CallExpression' &&
|
|
2808
|
+
n.callee.type === 'MemberExpression' &&
|
|
2809
|
+
n.callee.object?.name === 'Animated' &&
|
|
2810
|
+
ANIM_KINDS.has(n.callee.property?.name);
|
|
2811
|
+
|
|
2812
|
+
/** An animation handle (`anim` after `const anim = Animated.loop(…)`) resolved to the call it names. */
|
|
2813
|
+
const resolveAnim = (node, env) =>
|
|
2814
|
+
node?.type === 'Identifier' && env.animLocals?.has(node.name)
|
|
2815
|
+
? env.animLocals.get(node.name)
|
|
2816
|
+
: node;
|
|
2817
|
+
|
|
2818
|
+
/** One Animated.timing/spring/decay call as a chain step, started `extraDelay` ms later than its own delay. */
|
|
2819
|
+
function animStep(node, env, extraDelay) {
|
|
2820
|
+
const kind = node.callee.property.name;
|
|
2821
|
+
const valRef = node.arguments[0];
|
|
2822
|
+
if (valRef?.type !== 'Identifier' || !env.anims?.has(valRef.name))
|
|
2823
|
+
throw aotError(
|
|
2824
|
+
`AOT: Animated.${kind}() first argument must be a useAnimatedValue`,
|
|
2825
|
+
);
|
|
2826
|
+
const get = animConfigGetter(node.arguments[1]);
|
|
2827
|
+
const ownDelay = Math.round(Number(evalStaticOr(get('delay'), env, 0)));
|
|
2828
|
+
return {
|
|
2829
|
+
cVar: env.anims.get(valRef.name).cVar,
|
|
2830
|
+
kind,
|
|
2831
|
+
get,
|
|
2832
|
+
delayMs: extraDelay + ownDelay,
|
|
2833
|
+
loop: false,
|
|
2834
|
+
};
|
|
2835
|
+
}
|
|
2836
|
+
|
|
2837
|
+
/** The C handle of every value an animation drives. */
|
|
2838
|
+
function animValues(node, env, acc = new Set()) {
|
|
2839
|
+
node = resolveAnim(node, env);
|
|
2840
|
+
if (!isAnimatedCall(node))
|
|
2841
|
+
throw aotError(
|
|
2842
|
+
'AOT: an animation must be Animated.timing/spring/decay/sequence/parallel/stagger/delay/loop(...)',
|
|
2843
|
+
);
|
|
2844
|
+
const kind = node.callee.property.name;
|
|
2845
|
+
const args = node.arguments;
|
|
2846
|
+
if (kind === 'timing' || kind === 'spring' || kind === 'decay')
|
|
2847
|
+
acc.add(animStep(node, env, 0).cVar);
|
|
2848
|
+
else if (kind === 'loop') animValues(args[0], env, acc);
|
|
2849
|
+
else if (kind !== 'delay') {
|
|
2850
|
+
const list = kind === 'stagger' ? args[1] : args[0];
|
|
2851
|
+
for (const child of list?.elements ?? [])
|
|
2852
|
+
if (child) animValues(child, env, acc);
|
|
2853
|
+
}
|
|
2854
|
+
return acc;
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
/** The steps of an `Animated.sequence([...])` for an on_complete chain. A delay() folds into the next step's
|
|
2858
|
+
* delay_ms; `trailingDelay` is what follows the last step. A nested parallel/stagger/loop throws. */
|
|
2859
|
+
function sequenceSteps(seqNode, env) {
|
|
1904
2860
|
const list = seqNode.arguments[0];
|
|
1905
2861
|
if (list?.type !== 'ArrayExpression')
|
|
1906
2862
|
throw aotError('AOT: Animated.sequence(...) needs an array of animations');
|
|
1907
2863
|
const steps = [];
|
|
1908
2864
|
let pendingDelay = 0;
|
|
1909
|
-
for (const
|
|
1910
|
-
if (!
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
child.callee.type !== 'MemberExpression' ||
|
|
1914
|
-
child.callee.object?.name !== 'Animated'
|
|
1915
|
-
)
|
|
2865
|
+
for (const el of list.elements) {
|
|
2866
|
+
if (!el) continue;
|
|
2867
|
+
const child = resolveAnim(el, env);
|
|
2868
|
+
if (!isAnimatedCall(child))
|
|
1916
2869
|
throw aotError(
|
|
1917
2870
|
'AOT: Animated.sequence entries must be Animated.timing/spring/decay/delay(...)',
|
|
1918
2871
|
);
|
|
@@ -1927,41 +2880,136 @@ function compileSequenceChain(seqNode, env, ctx, doneCb = null) {
|
|
|
1927
2880
|
throw aotError(
|
|
1928
2881
|
'AOT: Animated.sequence entries must be Animated.timing/spring/decay/delay (a nested parallel/stagger/loop inside a sequence is not yet supported — keep the sequence flat)',
|
|
1929
2882
|
);
|
|
1930
|
-
|
|
1931
|
-
|
|
2883
|
+
steps.push(animStep(child, env, pendingDelay));
|
|
2884
|
+
pendingDelay = 0;
|
|
2885
|
+
}
|
|
2886
|
+
return {steps, trailingDelay: pendingDelay};
|
|
2887
|
+
}
|
|
2888
|
+
|
|
2889
|
+
/**
|
|
2890
|
+
* Emits steps as an on_complete CHAIN: step 0 starts inline and each step's completion callback starts the
|
|
2891
|
+
* next. Unlike the flat delay_ms path this is correct when steps share a value — er_anim_value_animate
|
|
2892
|
+
* cancels the running anim on a value, so starting them together would cancel all but the last — and needs
|
|
2893
|
+
* no fixed duration. A step that is interrupted (finished == false) ends the chain, as it does in JS.
|
|
2894
|
+
*
|
|
2895
|
+
* `loop` makes the last step start the first again: {iterations (negative = forever), resetTo (the value to
|
|
2896
|
+
* put back where it started before each repeat, or null), trailingDelay (ms before each repeat)}.
|
|
2897
|
+
*/
|
|
2898
|
+
function emitAnimChain(steps, env, ctx, doneCb, loop = null) {
|
|
2899
|
+
const seqId = ctx.out.seqN++; // GLOBAL: callback names are file-scope, so must be unique across handlers
|
|
2900
|
+
const cb = i => `er_seqcb_${seqId}_${i}`;
|
|
2901
|
+
const done = finished =>
|
|
2902
|
+
doneCb ? [` ${doneCb}(${finished}, NULL);`] : [];
|
|
2903
|
+
const interrupted = [
|
|
2904
|
+
' if (!finished)',
|
|
2905
|
+
' {',
|
|
2906
|
+
...done('false'),
|
|
2907
|
+
' return;',
|
|
2908
|
+
' }',
|
|
2909
|
+
];
|
|
2910
|
+
const last = loop ? cb(0) : doneCb;
|
|
2911
|
+
// Built from the tail so each step knows its successor's callback name.
|
|
2912
|
+
for (let i = steps.length - 1; i >= 1; i--) {
|
|
2913
|
+
const next = i < steps.length - 1 ? cb(i + 1) : last;
|
|
2914
|
+
ctx.out.animCbs.push({
|
|
2915
|
+
name: cb(i),
|
|
2916
|
+
body: [
|
|
2917
|
+
...interrupted,
|
|
2918
|
+
...emitAnimEntry(steps[i], env, `${seqId}_${i}`, next),
|
|
2919
|
+
],
|
|
2920
|
+
});
|
|
2921
|
+
}
|
|
2922
|
+
const next0 = steps.length > 1 ? cb(1) : last;
|
|
2923
|
+
const first = emitAnimEntry(steps[0], env, `${seqId}_0`, next0);
|
|
2924
|
+
if (!loop) return first;
|
|
2925
|
+
|
|
2926
|
+
// The repeat: cb(0) runs when the last step finishes, and starts step 0 again.
|
|
2927
|
+
const lines = [];
|
|
2928
|
+
const repeat = [...interrupted];
|
|
2929
|
+
if (loop.iterations >= 0) {
|
|
2930
|
+
const n = `s_loop${seqId}_n`;
|
|
2931
|
+
ctx.out.effectDecls.push(`static int ${n};`);
|
|
2932
|
+
lines.push(` ${n} = 1;`);
|
|
2933
|
+
repeat.push(
|
|
2934
|
+
` if (${n} >= ${loop.iterations})`,
|
|
2935
|
+
' {',
|
|
2936
|
+
...done('true'),
|
|
2937
|
+
' return;',
|
|
2938
|
+
' }',
|
|
2939
|
+
` ${n}++;`,
|
|
2940
|
+
);
|
|
2941
|
+
}
|
|
2942
|
+
if (loop.resetTo) {
|
|
2943
|
+
const from = `s_loop${seqId}_from`;
|
|
2944
|
+
ctx.out.effectDecls.push(`static float ${from};`);
|
|
2945
|
+
lines.push(` ${from} = er_anim_value_get(${loop.resetTo});`);
|
|
2946
|
+
repeat.push(` er_anim_value_set(${loop.resetTo}, ${from});`);
|
|
2947
|
+
}
|
|
2948
|
+
const again = {...steps[0], delayMs: steps[0].delayMs + loop.trailingDelay};
|
|
2949
|
+
repeat.push(...emitAnimEntry(again, env, `${seqId}_0`, next0));
|
|
2950
|
+
ctx.out.animCbs.push({name: cb(0), body: repeat});
|
|
2951
|
+
return [...lines, ...first];
|
|
2952
|
+
}
|
|
2953
|
+
|
|
2954
|
+
/**
|
|
2955
|
+
* Compiles `Animated.loop(animation, config?).start()`, or returns null for the flat path. An endless loop of
|
|
2956
|
+
* one timing is the engine's own cfg.loop; anything else (a sequence, a spring or decay, a counted loop) is a
|
|
2957
|
+
* chain whose last step starts the first again. As in JS, a looped single animation goes back to where it
|
|
2958
|
+
* started before each repeat (resetBeforeIteration), and a looped sequence carries on from where it ended.
|
|
2959
|
+
*/
|
|
2960
|
+
function compileLoopStart(loopNode, env, ctx, doneCb) {
|
|
2961
|
+
const inner = resolveAnim(loopNode.arguments[0], env);
|
|
2962
|
+
const kind = isAnimatedCall(inner) ? inner.callee.property.name : null;
|
|
2963
|
+
const get = animConfigGetter(loopNode.arguments[1]);
|
|
2964
|
+
let iterations = -1;
|
|
2965
|
+
if (get('iterations')) {
|
|
2966
|
+
let v;
|
|
2967
|
+
try {
|
|
2968
|
+
v = evalStatic(get('iterations'), foldScope(env, env.consts ?? {}));
|
|
2969
|
+
} catch {
|
|
1932
2970
|
throw aotError(
|
|
1933
|
-
|
|
2971
|
+
'AOT: Animated.loop iterations must be known at build time',
|
|
2972
|
+
'use a number or a module-level constant.',
|
|
1934
2973
|
);
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
2974
|
+
}
|
|
2975
|
+
// JS loops forever on anything but a whole number.
|
|
2976
|
+
iterations = Number.isInteger(v) ? Math.min(v, INT_MAX) : -1;
|
|
2977
|
+
}
|
|
2978
|
+
const reset = evalStaticOr(get('resetBeforeIteration'), env, true) !== false;
|
|
2979
|
+
let steps;
|
|
2980
|
+
let trailingDelay = 0;
|
|
2981
|
+
let resetTo = null;
|
|
2982
|
+
if (kind === 'sequence') {
|
|
2983
|
+
({steps, trailingDelay} = sequenceSteps(inner, env));
|
|
2984
|
+
} else if (kind === 'timing' || kind === 'spring' || kind === 'decay') {
|
|
2985
|
+
if (kind === 'timing' && iterations < 0 && reset) return null;
|
|
2986
|
+
steps = [animStep(inner, env, 0)];
|
|
2987
|
+
if (reset) resetTo = steps[0].cVar;
|
|
2988
|
+
} else {
|
|
2989
|
+
throw aotError(
|
|
2990
|
+
'AOT: Animated.loop can repeat a timing, spring, decay or sequence (looping a parallel/stagger is not yet supported)',
|
|
2991
|
+
);
|
|
1945
2992
|
}
|
|
1946
2993
|
if (!steps.length) return [];
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
//
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
2994
|
+
if (iterations === 0) return doneCb ? [` ${doneCb}(true, NULL);`] : [];
|
|
2995
|
+
// A timing with no duration and no delay completes inside er_anim_value_animate, so a loop made only of
|
|
2996
|
+
// those would restart itself forever without returning.
|
|
2997
|
+
const instant = s =>
|
|
2998
|
+
s.kind === 'timing' &&
|
|
2999
|
+
s.delayMs === 0 &&
|
|
3000
|
+
Math.round(Number(evalStaticOr(s.get('duration'), env, 250))) === 0;
|
|
3001
|
+
if (trailingDelay === 0 && steps.every(instant))
|
|
3002
|
+
throw aotError(
|
|
3003
|
+
'AOT: every step of this Animated.loop finishes instantly, so it would never stop repeating',
|
|
3004
|
+
'give a step a duration or a delay.',
|
|
3005
|
+
);
|
|
3006
|
+
return emitAnimChain(steps, env, ctx, doneCb, {
|
|
3007
|
+
iterations,
|
|
3008
|
+
resetTo,
|
|
3009
|
+
trailingDelay,
|
|
3010
|
+
});
|
|
1959
3011
|
}
|
|
1960
3012
|
|
|
1961
|
-
/** Compiles `<animation>.start()` — a single Animated.timing/spring/decay or a composition
|
|
1962
|
-
* (sequence/parallel/stagger/delay/loop). A top-level sequence chains via on_complete (compileSequenceChain);
|
|
1963
|
-
* everything else flattens to one ERAnimConfig + er_anim_value_animate per atomic entry, composition
|
|
1964
|
-
* expressed through per-entry delay_ms. Native-driven; sets no React state. */
|
|
1965
3013
|
/** Compiles a `.start(onComplete)` completion callback to a file-scope C fn (ERAnimCompleteFn) set as the
|
|
1966
3014
|
* animation's on_complete; its body runs setters/refs/etc. and re-applies state via app_update if needed. */
|
|
1967
3015
|
function emitCompletionCb(fnNode, env, state, ctx) {
|
|
@@ -1985,24 +3033,29 @@ function emitCompletionCb(fnNode, env, state, ctx) {
|
|
|
1985
3033
|
: [{type: 'ExpressionStatement', expression: body}];
|
|
1986
3034
|
const cctx = {stateChanged: false, animIdx: 0, out: ctx.out};
|
|
1987
3035
|
const lines = compileStmts(list, {...env, locals}, state, cctx, ' ');
|
|
1988
|
-
if (cctx.stateChanged) lines.push(
|
|
3036
|
+
if (cctx.stateChanged) lines.push(APP_UPDATE_CALL);
|
|
1989
3037
|
ctx.out.animCbs.push({name, body: lines});
|
|
1990
3038
|
return name;
|
|
1991
3039
|
}
|
|
1992
3040
|
|
|
3041
|
+
/** Compiles `<animation>.start()` — a single Animated.timing/spring/decay or a composition
|
|
3042
|
+
* (sequence/parallel/stagger/delay/loop). A sequence, and a loop the engine cannot repeat on its own, become
|
|
3043
|
+
* an on_complete chain (emitAnimChain); everything else flattens to one ERAnimConfig + er_anim_value_animate
|
|
3044
|
+
* per atomic entry, composition expressed through per-entry delay_ms. Native-driven; sets no React state. */
|
|
1993
3045
|
function compileAnimateStart(expr, env, state, ctx) {
|
|
1994
3046
|
// .start(onComplete?) — an optional completion callback fired when the animation finishes.
|
|
1995
3047
|
const doneCb = isFn(expr.arguments[0])
|
|
1996
3048
|
? emitCompletionCb(expr.arguments[0], env, state, ctx)
|
|
1997
3049
|
: null;
|
|
1998
|
-
const receiver = expr.callee.object;
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
) {
|
|
2005
|
-
|
|
3050
|
+
const receiver = resolveAnim(expr.callee.object, env);
|
|
3051
|
+
const kind = isAnimatedCall(receiver) ? receiver.callee.property.name : null;
|
|
3052
|
+
if (kind === 'sequence') {
|
|
3053
|
+
const {steps} = sequenceSteps(receiver, env);
|
|
3054
|
+
return steps.length ? emitAnimChain(steps, env, ctx, doneCb) : [];
|
|
3055
|
+
}
|
|
3056
|
+
if (kind === 'loop') {
|
|
3057
|
+
const lines = compileLoopStart(receiver, env, ctx, doneCb);
|
|
3058
|
+
if (lines) return lines;
|
|
2006
3059
|
}
|
|
2007
3060
|
const {entries} = flattenAnim(receiver, env, 0, false);
|
|
2008
3061
|
if (doneCb && entries.length > 1)
|
|
@@ -2028,7 +3081,7 @@ function compileAnimateStart(expr, env, state, ctx) {
|
|
|
2028
3081
|
function evalStaticOr(node, env, dflt) {
|
|
2029
3082
|
if (!node) return dflt;
|
|
2030
3083
|
try {
|
|
2031
|
-
return evalStatic(node, env.consts ?? {});
|
|
3084
|
+
return evalStatic(node, foldScope(env, env.consts ?? {}));
|
|
2032
3085
|
} catch {
|
|
2033
3086
|
return dflt;
|
|
2034
3087
|
}
|
|
@@ -2039,11 +3092,78 @@ function blockList(node) {
|
|
|
2039
3092
|
return node.type === 'BlockStatement' ? node.body : [node];
|
|
2040
3093
|
}
|
|
2041
3094
|
|
|
2042
|
-
/**
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
3095
|
+
/** Matches `<member>` as a whole C lvalue, so `s_state.label` does not also match `s_state.label2`. */
|
|
3096
|
+
const readsMember = member =>
|
|
3097
|
+
new RegExp(`(^|[^\\w.])${member.replace(/\./g, '\\.')}(?![\\w])`);
|
|
3098
|
+
|
|
3099
|
+
/**
|
|
3100
|
+
* Checks a value written to a numeric state or ref slot, whose C type came from its initial value. A 64-bit
|
|
3101
|
+
* timestamp written to an int slot is recorded in env.found, and compileWidened compiles again with that
|
|
3102
|
+
* slot widened to int64_t. It cannot go into a float or boolean slot (a 64-bit constant can go into a float
|
|
3103
|
+
* one), and a widened slot takes no floats.
|
|
3104
|
+
*/
|
|
3105
|
+
function storeCheck(e, slotType, isBool, key, what, env) {
|
|
3106
|
+
if (e.cType === 'i64' && slotType !== 'i64') {
|
|
3107
|
+
if (slotType === 'int' && !isBool) {
|
|
3108
|
+
env.found.add(key);
|
|
3109
|
+
return;
|
|
3110
|
+
}
|
|
3111
|
+
if (e.lit && slotType === 'float') return;
|
|
3112
|
+
throw aotError(
|
|
3113
|
+
`AOT: a 64-bit time value cannot be stored in ${what}`,
|
|
3114
|
+
'give it a whole-number initial value — useState(0) or useRef(0) — and it widens to hold the timestamp.',
|
|
3115
|
+
);
|
|
3116
|
+
}
|
|
3117
|
+
if (slotType === 'i64' && e.cType === 'float') throw mix64Error();
|
|
3118
|
+
}
|
|
3119
|
+
|
|
3120
|
+
/**
|
|
3121
|
+
* `e` as C for an int destination. A float goes through app_f2i: C's own conversion is undefined behavior
|
|
3122
|
+
* for NaN or a value past the int range.
|
|
3123
|
+
*/
|
|
3124
|
+
const asInt = e => (e.cType === 'float' ? `app_f2i(${e.code})` : e.code);
|
|
3125
|
+
|
|
3126
|
+
/** `e` as C for a slot of `slotType`: an int slot takes a float the way asInt does. */
|
|
3127
|
+
const storeCode = (e, slotType) => (slotType === 'int' ? asInt(e) : e.code);
|
|
3128
|
+
|
|
3129
|
+
/**
|
|
3130
|
+
* The call a body that set state ends with, to re-apply what reads it. Whether anything reads state is known
|
|
3131
|
+
* only once the whole app is emitted, so the call is dropped then if nothing does.
|
|
3132
|
+
*/
|
|
3133
|
+
const APP_UPDATE_CALL = ' app_update();';
|
|
3134
|
+
|
|
3135
|
+
/** Emits C to write an expression into a scalar state slot: snprintf for a string buffer (so a `+` chain
|
|
3136
|
+
* becomes a format + args), plain assign otherwise. */
|
|
3137
|
+
function scalarAssign(rec, node, env, indent) {
|
|
3138
|
+
if (rec.cType !== 'string') {
|
|
3139
|
+
// A 64-bit slot takes int `+ - *` worked out in 64 bits.
|
|
3140
|
+
const e = emitExprWide(
|
|
3141
|
+
node,
|
|
3142
|
+
rec.cType === 'i64' ? {...env, math64: true} : env,
|
|
3143
|
+
);
|
|
3144
|
+
storeCheck(
|
|
3145
|
+
e,
|
|
3146
|
+
rec.cType,
|
|
3147
|
+
rec.isBool,
|
|
3148
|
+
rec.cField,
|
|
3149
|
+
`state "${rec.name}"`,
|
|
3150
|
+
env,
|
|
3151
|
+
);
|
|
3152
|
+
return `${indent}${rec.cMember} = ${storeCode(e, rec.cType)};`;
|
|
3153
|
+
}
|
|
3154
|
+
const f = emitFormat(node, env);
|
|
3155
|
+
// snprintf's source and destination may not overlap (C11 7.21.6.6), and `setLabel(label + '!')` feeds
|
|
3156
|
+
// the slot its own contents. Build the new value in a temporary first — some embedded libcs write the
|
|
3157
|
+
// destination as they go, which would read back what they just overwrote.
|
|
3158
|
+
if (f.args.some(a => readsMember(rec.cMember).test(a)))
|
|
3159
|
+
return [
|
|
3160
|
+
`${indent}{`,
|
|
3161
|
+
`${indent} char next[sizeof(${rec.cMember})];`,
|
|
3162
|
+
`${indent} snprintf(next, sizeof(next), ${formatArgs(f)});`,
|
|
3163
|
+
`${indent} memcpy(${rec.cMember}, next, strlen(next) + 1);`,
|
|
3164
|
+
`${indent}}`,
|
|
3165
|
+
].join('\n');
|
|
3166
|
+
return `${indent}snprintf(${rec.cMember}, sizeof(${rec.cMember}), ${formatArgs(f)});`;
|
|
2047
3167
|
}
|
|
2048
3168
|
|
|
2049
3169
|
/** True if `node` is a `<ref>.current` member access on a known value ref. */
|
|
@@ -2171,9 +3291,16 @@ function compileUpdateVector(expr, env, ctx, indent) {
|
|
|
2171
3291
|
throw new Error(
|
|
2172
3292
|
'AOT: updateVector dirtyRect must be a [x, y, w, h] array literal',
|
|
2173
3293
|
);
|
|
2174
|
-
const
|
|
3294
|
+
const rect = dirtyArg.elements.slice(0, 4).map(el => emitExpr(el, env));
|
|
3295
|
+
// A float edge can be NaN (a 0/0), which app_vector_dirty turns into no hint at all, so the engine's own
|
|
3296
|
+
// damage applies (what changed in the tape, or the whole node), where a zero-width hint would paint nothing:
|
|
3297
|
+
// the engine damages exactly the hinted rect. An int edge goes straight to the engine, which clips the
|
|
3298
|
+
// rect's corners to the int16 range it keeps them in.
|
|
3299
|
+
const fn = rect.some(e => e.cType === 'float')
|
|
3300
|
+
? 'app_vector_dirty'
|
|
3301
|
+
: 'er_node_set_vector_dirty_rect';
|
|
2175
3302
|
lines.push(
|
|
2176
|
-
`${indent}
|
|
3303
|
+
`${indent}${fn}(${ref.cVar}, ${rect.map(e => e.code).join(', ')});`,
|
|
2177
3304
|
);
|
|
2178
3305
|
}
|
|
2179
3306
|
return lines;
|
|
@@ -2188,7 +3315,16 @@ function compileTimerAdd(expr, env, state, ctx) {
|
|
|
2188
3315
|
'AOT: a setInterval/setTimeout callback must be an inline function',
|
|
2189
3316
|
'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).',
|
|
2190
3317
|
);
|
|
2191
|
-
|
|
3318
|
+
// A delay computed from a timestamp or a float goes through ToInt32 and a floor at 0, as Flow A's setTimeout
|
|
3319
|
+
// does.
|
|
3320
|
+
const delay = expr.arguments[1] ? emitExprWide(expr.arguments[1], env) : null;
|
|
3321
|
+
const ms = !delay
|
|
3322
|
+
? '0'
|
|
3323
|
+
: delay.cType === 'i64'
|
|
3324
|
+
? `app_delay_ms64(${delay.code})`
|
|
3325
|
+
: delay.cType === 'float'
|
|
3326
|
+
? `app_delay_msf(${delay.code})`
|
|
3327
|
+
: delay.code;
|
|
2192
3328
|
const repeat = expr.callee.name === 'setInterval';
|
|
2193
3329
|
const slot = ctx.out.timerFns.length;
|
|
2194
3330
|
const name = `er_timer_fn_${slot}`;
|
|
@@ -2215,8 +3351,13 @@ function inlineHelperCall(name, fn, args, env, state, ctx, indent) {
|
|
|
2215
3351
|
'a helper called from a handler must use plain positional params (e.g. `(a, b) => …`) — destructuring or default params in the signature are not supported.',
|
|
2216
3352
|
);
|
|
2217
3353
|
if (args[i]) {
|
|
2218
|
-
const e =
|
|
2219
|
-
locals.set(p.name, {
|
|
3354
|
+
const e = emitExprWide(args[i], env);
|
|
3355
|
+
locals.set(p.name, {
|
|
3356
|
+
code: e.code,
|
|
3357
|
+
cType: e.cType,
|
|
3358
|
+
isBool: e.isBool,
|
|
3359
|
+
lit: e.lit,
|
|
3360
|
+
});
|
|
2220
3361
|
}
|
|
2221
3362
|
});
|
|
2222
3363
|
const body = fn.body;
|
|
@@ -2224,10 +3365,18 @@ function inlineHelperCall(name, fn, args, env, state, ctx, indent) {
|
|
|
2224
3365
|
body.type === 'BlockStatement'
|
|
2225
3366
|
? body.body
|
|
2226
3367
|
: [{type: 'ExpressionStatement', expression: body}];
|
|
3368
|
+
// The helper's statements are spliced into the CALLER, so its `return` is not the caller's return —
|
|
3369
|
+
// reject it here even when the caller is an effect body, where a `return` would otherwise be allowed.
|
|
3370
|
+
// Both marks are scoped to this call, so they unwind with it rather than outliving a thrown error.
|
|
3371
|
+
const outerAllowReturn = ctx.allowReturn;
|
|
2227
3372
|
ctx.inlining.add(name);
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
3373
|
+
ctx.allowReturn = false;
|
|
3374
|
+
try {
|
|
3375
|
+
return compileStmts(list, {...env, locals}, state, ctx, indent);
|
|
3376
|
+
} finally {
|
|
3377
|
+
ctx.allowReturn = outerAllowReturn;
|
|
3378
|
+
ctx.inlining.delete(name);
|
|
3379
|
+
}
|
|
2231
3380
|
}
|
|
2232
3381
|
|
|
2233
3382
|
function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
@@ -2255,7 +3404,7 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
|
2255
3404
|
expr.callee.name === 'clearTimeout')
|
|
2256
3405
|
) {
|
|
2257
3406
|
return [
|
|
2258
|
-
`${indent}er_timer_clear(${emitExpr(expr.arguments[0], env)
|
|
3407
|
+
`${indent}er_timer_clear(${asInt(emitExpr(expr.arguments[0], env))});`,
|
|
2259
3408
|
];
|
|
2260
3409
|
}
|
|
2261
3410
|
// `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
|
|
@@ -2265,19 +3414,94 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
|
2265
3414
|
throw new Error(
|
|
2266
3415
|
'AOT: the only assignment allowed in a handler is `ref.current = ...`',
|
|
2267
3416
|
);
|
|
3417
|
+
const refEnv = r.cType === 'i64' ? {...env, math64: true} : env;
|
|
3418
|
+
const e = emitExprWide(expr.right, refEnv);
|
|
3419
|
+
if (expr.operator === '/=' && (r.cType === 'i64' || isTime64(e)))
|
|
3420
|
+
throw aotError(
|
|
3421
|
+
'AOT: `/=` on a 64-bit time value is not supported',
|
|
3422
|
+
'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.',
|
|
3423
|
+
);
|
|
3424
|
+
const m =
|
|
3425
|
+
expr.operator === '%=' && (r.cType === 'i64' || isTime64(e))
|
|
3426
|
+
? constDivisor(expr.right, env)
|
|
3427
|
+
: null;
|
|
3428
|
+
storeCheck(
|
|
3429
|
+
e,
|
|
3430
|
+
r.cType,
|
|
3431
|
+
false,
|
|
3432
|
+
r.cVar,
|
|
3433
|
+
`ref "${expr.left.object.name}"`,
|
|
3434
|
+
env,
|
|
3435
|
+
);
|
|
3436
|
+
const whole = r.cType === 'int' || r.cType === 'i64';
|
|
3437
|
+
// `+= -= *=` on a whole-number ref go through the same checked math as `+ - *`, `/=` by a float divides
|
|
3438
|
+
// as floats, and `%=` over a float goes through fmodf as `%` does; a float result is stored the way any
|
|
3439
|
+
// int slot stores one.
|
|
3440
|
+
const step = {'+=': '+', '-=': '-', '*=': '*'}[expr.operator];
|
|
3441
|
+
const floatMod =
|
|
3442
|
+
expr.operator === '%=' && (r.cType === 'float' || e.cType === 'float');
|
|
3443
|
+
if (
|
|
3444
|
+
(whole && (step || (expr.operator === '/=' && e.cType === 'float'))) ||
|
|
3445
|
+
floatMod
|
|
3446
|
+
) {
|
|
3447
|
+
const v = emitExprWide(
|
|
3448
|
+
{
|
|
3449
|
+
type: 'BinaryExpression',
|
|
3450
|
+
operator: step ?? expr.operator.slice(0, -1),
|
|
3451
|
+
left: expr.left,
|
|
3452
|
+
right: expr.right,
|
|
3453
|
+
loc: expr.loc,
|
|
3454
|
+
},
|
|
3455
|
+
refEnv,
|
|
3456
|
+
);
|
|
3457
|
+
return [`${indent}${r.cVar} = ${storeCode(v, r.cType)};`];
|
|
3458
|
+
}
|
|
3459
|
+
// `/=` and `%=` on an int ref by an int give JS's answer, kept whole (app_div / app_mod). A constant
|
|
3460
|
+
// divisor other than 0 and -1 needs no check.
|
|
3461
|
+
if (
|
|
3462
|
+
r.cType === 'int' &&
|
|
3463
|
+
e.cType === 'int' &&
|
|
3464
|
+
(expr.operator === '/=' || expr.operator === '%=')
|
|
3465
|
+
) {
|
|
3466
|
+
const k = staticInt(expr.right, env);
|
|
3467
|
+
if (expr.operator === '/=' && (k === null || k === 0 || k === -1))
|
|
3468
|
+
return [`${indent}${r.cVar} = app_div(${r.cVar}, ${e.code});`];
|
|
3469
|
+
if (expr.operator === '%=' && (k === 0 || k === -1))
|
|
3470
|
+
return [`${indent}${r.cVar} = 0;`];
|
|
3471
|
+
if (expr.operator === '%=' && k === null)
|
|
3472
|
+
return [`${indent}${r.cVar} = app_mod(${r.cVar}, ${e.code});`];
|
|
3473
|
+
}
|
|
3474
|
+
// ±1 leaves no remainder, 0 is JS's NaN, which is 0 here, and INT64_MIN % -1 overflows in C.
|
|
3475
|
+
if (m === 0 || m === 1 || m === -1) return [`${indent}${r.cVar} = 0;`];
|
|
2268
3476
|
return [
|
|
2269
|
-
`${indent}${r.cVar} ${expr.operator} ${
|
|
3477
|
+
`${indent}${r.cVar} ${expr.operator} ${expr.operator === '=' ? storeCode(e, r.cType) : e.code};`,
|
|
2270
3478
|
];
|
|
2271
3479
|
}
|
|
2272
|
-
// `ref.current++` / `ref.current
|
|
3480
|
+
// `ref.current++` / `ref.current--`; a whole-number ref steps through the checked `+ 1` / `- 1`.
|
|
2273
3481
|
if (expr.type === 'UpdateExpression') {
|
|
2274
3482
|
const r = refTarget(expr.argument, env);
|
|
2275
3483
|
if (!r)
|
|
2276
3484
|
throw new Error(
|
|
2277
3485
|
'AOT: the only ++/-- allowed in a handler is on `ref.current`',
|
|
2278
3486
|
);
|
|
3487
|
+
if (r.cType === 'int' || r.cType === 'i64')
|
|
3488
|
+
return [
|
|
3489
|
+
`${indent}${r.cVar} = ${CHECKED_OP[expr.operator[0]]}${r.cType === 'i64' ? '64' : ''}(${r.cVar}, 1);`,
|
|
3490
|
+
];
|
|
2279
3491
|
return [`${indent}${r.cVar}${expr.operator};`];
|
|
2280
3492
|
}
|
|
3493
|
+
// `anim.stop()` stops every value the animation drives where it is. The cancellation reports finished ==
|
|
3494
|
+
// false, which also ends a sequence or loop chain.
|
|
3495
|
+
if (
|
|
3496
|
+
expr.type === 'CallExpression' &&
|
|
3497
|
+
expr.callee.type === 'MemberExpression' &&
|
|
3498
|
+
expr.callee.property.name === 'stop' &&
|
|
3499
|
+
isAnimatedCall(resolveAnim(expr.callee.object, env))
|
|
3500
|
+
) {
|
|
3501
|
+
return [...animValues(expr.callee.object, env)].map(
|
|
3502
|
+
v => `${indent}er_anim_value_set(${v}, er_anim_value_get(${v}));`,
|
|
3503
|
+
);
|
|
3504
|
+
}
|
|
2281
3505
|
// Animated.*(…).start() — single timing/spring/decay OR a sequence/parallel/stagger/delay/loop
|
|
2282
3506
|
// composition; native-driven, sets no React state, needs no app_update.
|
|
2283
3507
|
if (
|
|
@@ -2327,20 +3551,23 @@ function compileHandlerExprImpl(expr, env, state, ctx, indent) {
|
|
|
2327
3551
|
throw new Error(
|
|
2328
3552
|
'AOT: updater function must be a single expression (for now)',
|
|
2329
3553
|
);
|
|
2330
|
-
return [scalarAssign(rec,
|
|
3554
|
+
return [scalarAssign(rec, arg.body, {...env, locals}, indent)];
|
|
2331
3555
|
}
|
|
2332
|
-
return [scalarAssign(rec,
|
|
3556
|
+
return [scalarAssign(rec, arg, env, indent)];
|
|
2333
3557
|
}
|
|
2334
3558
|
const compileHandlerExpr = withLoc(compileHandlerExprImpl);
|
|
2335
3559
|
|
|
2336
3560
|
/**
|
|
2337
3561
|
* Compiles a list of handler statements to C lines. Supports: `const x = expr` (a C local, visible to
|
|
2338
3562
|
* later statements), `if (cond) {...} else {...}`, state setters, and Animated.*(...).start(). `ctx`
|
|
2339
|
-
* accumulates `stateChanged` (→ trailing app_update)
|
|
3563
|
+
* accumulates `stateChanged` (→ trailing app_update), `animIdx` (unique ERAnimConfig locals) and
|
|
3564
|
+
* `usedReturn` (an early `return` was lowered, so the body needs a C function of its own). `ctx.allowReturn`
|
|
3565
|
+
* and `ctx.bodyList` mark which body a `return` may exit and which statement of it is the tail.
|
|
2340
3566
|
*/
|
|
2341
3567
|
function compileStmts(list, env, state, ctx, indent) {
|
|
2342
3568
|
const lines = [];
|
|
2343
|
-
for (
|
|
3569
|
+
for (let si = 0; si < list.length; si++) {
|
|
3570
|
+
const st = list[si];
|
|
2344
3571
|
if (st.type === 'VariableDeclaration') {
|
|
2345
3572
|
for (const decl of st.declarations) {
|
|
2346
3573
|
if (decl.id.type !== 'Identifier')
|
|
@@ -2349,7 +3576,24 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2349
3576
|
);
|
|
2350
3577
|
if (!decl.init)
|
|
2351
3578
|
throw new Error('AOT: a handler local must have an initializer');
|
|
2352
|
-
const
|
|
3579
|
+
// `const anim = Animated.loop(…)` holds no C value: `anim.start()` and `anim.stop()` compile the
|
|
3580
|
+
// animation it names.
|
|
3581
|
+
if (isAnimatedCall(decl.init)) {
|
|
3582
|
+
const locals = new Map(env.locals);
|
|
3583
|
+
locals.delete(decl.id.name);
|
|
3584
|
+
env = {
|
|
3585
|
+
...env,
|
|
3586
|
+
locals,
|
|
3587
|
+
animLocals: new Map(env.animLocals).set(decl.id.name, decl.init),
|
|
3588
|
+
};
|
|
3589
|
+
continue;
|
|
3590
|
+
}
|
|
3591
|
+
// A cleanup closure outlives the call that created it, so when one is emitted (a dep-driven
|
|
3592
|
+
// effect) the body's own locals become file-scope slots instead of C locals.
|
|
3593
|
+
const hoist = ctx.hoist && list === ctx.bodyList;
|
|
3594
|
+
const cName = hoist
|
|
3595
|
+
? `${ctx.hoist.prefix}${decl.id.name}`
|
|
3596
|
+
: `l_${decl.id.name}`;
|
|
2353
3597
|
// `const id = setInterval/setTimeout(…)` → an int timer-id local (so a later clearInterval(id) resolves).
|
|
2354
3598
|
if (
|
|
2355
3599
|
decl.init.type === 'CallExpression' &&
|
|
@@ -2358,8 +3602,9 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2358
3602
|
decl.init.callee.name === 'setTimeout')
|
|
2359
3603
|
) {
|
|
2360
3604
|
// The id is only needed for a later clear*(); a mount effect drops its cleanup, so mark it used.
|
|
3605
|
+
if (hoist) ctx.hoist.decls.push(`static int ${cName};`);
|
|
2361
3606
|
lines.push(
|
|
2362
|
-
`${indent}int ${cName} = ${compileTimerAdd(decl.init, env, state, ctx)};`,
|
|
3607
|
+
`${indent}${hoist ? '' : 'int '}${cName} = ${compileTimerAdd(decl.init, env, state, ctx)};`,
|
|
2363
3608
|
`${indent}(void)${cName};`,
|
|
2364
3609
|
);
|
|
2365
3610
|
env = {
|
|
@@ -2371,28 +3616,79 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2371
3616
|
};
|
|
2372
3617
|
continue;
|
|
2373
3618
|
}
|
|
2374
|
-
const e =
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
3619
|
+
const e = emitExprWide(decl.init, env);
|
|
3620
|
+
if (e.cType === 'string') {
|
|
3621
|
+
// A string local gets a buffer of its own rather than a char* into a state slot: a pointer alias
|
|
3622
|
+
// would let `setLabel(t + '!')` read and write the same bytes behind readsMember's back — and
|
|
3623
|
+
// `int l_t = s_state.label` was never valid C to begin with.
|
|
3624
|
+
if (hoist)
|
|
3625
|
+
ctx.hoist.decls.push(`static char ${cName}[${LIST_STR_CAP}];`);
|
|
3626
|
+
else lines.push(`${indent}char ${cName}[${LIST_STR_CAP}];`);
|
|
3627
|
+
lines.push(
|
|
3628
|
+
`${indent}snprintf(${cName}, sizeof(${cName}), "%s", ${e.code});`,
|
|
3629
|
+
);
|
|
3630
|
+
} else {
|
|
3631
|
+
if (e.cType !== 'int' && e.cType !== 'float' && e.cType !== 'i64')
|
|
3632
|
+
throw aotError(
|
|
3633
|
+
'AOT: a handler local must hold a number, a boolean or a string',
|
|
3634
|
+
'bind the value itself — e.g. `const id = item.id` — rather than a list item or a node ref.',
|
|
3635
|
+
);
|
|
3636
|
+
const cType = cScalarType(e.cType);
|
|
3637
|
+
if (hoist) ctx.hoist.decls.push(`static ${cType} ${cName};`);
|
|
3638
|
+
lines.push(
|
|
3639
|
+
`${indent}${hoist ? '' : cType + ' '}${cName} = ${e.code};`,
|
|
3640
|
+
);
|
|
3641
|
+
}
|
|
2378
3642
|
env = {
|
|
2379
3643
|
...env,
|
|
2380
3644
|
locals: new Map(env.locals).set(decl.id.name, {
|
|
2381
3645
|
code: cName,
|
|
2382
3646
|
cType: e.cType,
|
|
3647
|
+
isBool: e.isBool,
|
|
2383
3648
|
}),
|
|
2384
3649
|
};
|
|
2385
3650
|
}
|
|
2386
3651
|
continue;
|
|
2387
3652
|
}
|
|
2388
|
-
//
|
|
2389
|
-
//
|
|
3653
|
+
// A `return` in an effect body. The LAST statement of the body is the cleanup `return () => …` (or a
|
|
3654
|
+
// bare `return`). A mount effect drops it — the app never unmounts, so it would never run. A dep-driven
|
|
3655
|
+
// effect re-runs, and React runs the previous cleanup first, so `ctx.cleanup` compiles it into a
|
|
3656
|
+
// companion C function and arms it here. Any EARLIER return is a guard that has to actually exit — it
|
|
3657
|
+
// emits `return;` and flags the body so compileEffect gives it a C function of its own.
|
|
2390
3658
|
if (st.type === 'ReturnStatement') {
|
|
2391
|
-
if (ctx.allowReturn)
|
|
2392
|
-
|
|
3659
|
+
if (!ctx.allowReturn) {
|
|
3660
|
+
const e = aotError(
|
|
3661
|
+
'AOT: `return` is only supported inside a useEffect body',
|
|
3662
|
+
'a handler, timer, animation or inlined-helper body cannot return early — flatten the logic into if/else.',
|
|
3663
|
+
);
|
|
3664
|
+
if (st.loc) e.aotLoc = st.loc.start;
|
|
3665
|
+
throw e;
|
|
3666
|
+
}
|
|
3667
|
+
const isTail = list === ctx.bodyList && si === list.length - 1;
|
|
3668
|
+
if (ctx.depDriven && isFn(st.argument) && !isTail) {
|
|
3669
|
+
const e = aotError(
|
|
3670
|
+
'AOT: a useEffect cleanup must be the last statement of the effect body',
|
|
3671
|
+
'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.',
|
|
3672
|
+
);
|
|
3673
|
+
if (st.loc) e.aotLoc = st.loc.start;
|
|
3674
|
+
throw e;
|
|
3675
|
+
}
|
|
3676
|
+
if (isTail) {
|
|
3677
|
+
if (ctx.cleanup && isFn(st.argument)) {
|
|
3678
|
+
ctx.cleanup.emit(st.argument, env);
|
|
3679
|
+
lines.push(`${indent}${ctx.cleanup.armed} = 1;`);
|
|
3680
|
+
}
|
|
3681
|
+
continue;
|
|
3682
|
+
}
|
|
3683
|
+
ctx.usedReturn = true;
|
|
3684
|
+
lines.push(`${indent}return;`);
|
|
3685
|
+
continue;
|
|
2393
3686
|
}
|
|
2394
3687
|
if (st.type === 'IfStatement') {
|
|
2395
|
-
lines.push(
|
|
3688
|
+
lines.push(
|
|
3689
|
+
`${indent}if (${asCond(emitExprWide(st.test, env))})`,
|
|
3690
|
+
`${indent}{`,
|
|
3691
|
+
);
|
|
2396
3692
|
lines.push(
|
|
2397
3693
|
...compileStmts(
|
|
2398
3694
|
blockList(st.consequent),
|
|
@@ -2421,7 +3717,7 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2421
3717
|
if (st.type !== 'ExpressionStatement')
|
|
2422
3718
|
throw aotError(
|
|
2423
3719
|
`AOT: unsupported statement "${st.type}" in event handler`,
|
|
2424
|
-
'a handler supports only `const x = …` locals, `if (…) { … } else { … }`, and expression statements (setters / ref writes / updateVector / Animated…start). Loops (for/while), switch
|
|
3720
|
+
'a handler supports only `const x = …` locals, `if (…) { … } else { … }`, and expression statements (setters / ref writes / updateVector / Animated…start). Loops (for/while), switch and try/catch are not lowered — precompute values or flatten the logic into if/else.',
|
|
2425
3721
|
);
|
|
2426
3722
|
lines.push(...compileHandlerExpr(st.expression, env, state, ctx, indent));
|
|
2427
3723
|
}
|
|
@@ -2435,6 +3731,7 @@ function compileStmts(list, env, state, ctx, indent) {
|
|
|
2435
3731
|
* then again from app_update whenever a SCALAR dep changes (compared against a stored prev). The body is
|
|
2436
3732
|
* compiled WITHOUT a trailing app_update — it runs INSIDE app_update / at mount, so re-applying state it
|
|
2437
3733
|
* sets happens on the next app_update (one-frame), and it can never re-enter app_update (no infinite loop).
|
|
3734
|
+
* A dep-driven `return () => …` becomes `er_effect_N_cleanup()`, run at the top of the next re-run.
|
|
2438
3735
|
*/
|
|
2439
3736
|
function compileEffect(eff, env, state, out) {
|
|
2440
3737
|
const body = eff.fn.body;
|
|
@@ -2446,10 +3743,26 @@ function compileEffect(eff, env, state, out) {
|
|
|
2446
3743
|
!eff.deps ||
|
|
2447
3744
|
(eff.deps.type === 'ArrayExpression' && eff.deps.elements.length === 0);
|
|
2448
3745
|
if (isMount) {
|
|
2449
|
-
const ctx = {
|
|
3746
|
+
const ctx = {
|
|
3747
|
+
stateChanged: false,
|
|
3748
|
+
animIdx: 0,
|
|
3749
|
+
out,
|
|
3750
|
+
allowReturn: true,
|
|
3751
|
+
bodyList: stmts,
|
|
3752
|
+
};
|
|
2450
3753
|
const lines = compileStmts(stmts, env, state, ctx, ' ');
|
|
2451
|
-
if (ctx.
|
|
2452
|
-
|
|
3754
|
+
if (!ctx.usedReturn) {
|
|
3755
|
+
if (ctx.stateChanged) lines.push(APP_UPDATE_CALL);
|
|
3756
|
+
out.mountEffects.push(...lines);
|
|
3757
|
+
return;
|
|
3758
|
+
}
|
|
3759
|
+
// A mount body is normally inlined into er_app_build, where a `return` would skip every later mount
|
|
3760
|
+
// effect — so one with an early return gets a C function of its own, and the app_update it may owe
|
|
3761
|
+
// moves to the call site (past the return, it would otherwise be dead code).
|
|
3762
|
+
const name = `er_effect_${out.effN++}`;
|
|
3763
|
+
out.effectFns.push({name, body: lines});
|
|
3764
|
+
out.mountEffects.push(` ${name}();`);
|
|
3765
|
+
if (ctx.stateChanged) out.mountEffects.push(APP_UPDATE_CALL);
|
|
2453
3766
|
return;
|
|
2454
3767
|
}
|
|
2455
3768
|
if (eff.deps.type !== 'ArrayExpression')
|
|
@@ -2461,25 +3774,67 @@ function compileEffect(eff, env, state, out) {
|
|
|
2461
3774
|
const name = `er_effect_${id}`;
|
|
2462
3775
|
const deps = eff.deps.elements.map(d => {
|
|
2463
3776
|
if (!d) throw aotError('AOT: a useEffect dependency must be an expression');
|
|
2464
|
-
const e =
|
|
2465
|
-
if (
|
|
3777
|
+
const e = emitExprWide(d, env);
|
|
3778
|
+
if (!['int', 'float', 'i64', 'string'].includes(e.cType))
|
|
2466
3779
|
throw aotError(
|
|
2467
3780
|
'AOT: useEffect dependencies must be scalar (number / bool / string)',
|
|
2468
3781
|
'depend on scalar state values; object/array dependencies are not yet supported.',
|
|
2469
3782
|
);
|
|
2470
3783
|
return e;
|
|
2471
3784
|
});
|
|
2472
|
-
|
|
3785
|
+
// React runs the previous cleanup before re-running a dep-driven effect. The cleanup closes over the
|
|
3786
|
+
// body's locals, which have to outlive the call, so they become file-scope slots; an `armed` flag says
|
|
3787
|
+
// whether the last run actually reached its `return () => …` (a guarded run that returned early did not).
|
|
3788
|
+
const tail = stmts[stmts.length - 1];
|
|
3789
|
+
const hasCleanup = tail?.type === 'ReturnStatement' && isFn(tail.argument);
|
|
3790
|
+
const armed = `s_eff${id}_armed`;
|
|
3791
|
+
const ctx = {
|
|
3792
|
+
stateChanged: false,
|
|
3793
|
+
animIdx: 0,
|
|
3794
|
+
out,
|
|
3795
|
+
allowReturn: true,
|
|
3796
|
+
bodyList: stmts,
|
|
3797
|
+
depDriven: true,
|
|
3798
|
+
};
|
|
3799
|
+
if (hasCleanup) {
|
|
3800
|
+
ctx.hoist = {prefix: `s_eff${id}_l_`, decls: out.effectDecls};
|
|
3801
|
+
ctx.cleanup = {
|
|
3802
|
+
armed,
|
|
3803
|
+
emit: (fn, cenv) => {
|
|
3804
|
+
const cbody = fn.body;
|
|
3805
|
+
const clist =
|
|
3806
|
+
cbody.type === 'BlockStatement'
|
|
3807
|
+
? cbody.body
|
|
3808
|
+
: [{type: 'ExpressionStatement', expression: cbody}];
|
|
3809
|
+
const cctx = {stateChanged: false, animIdx: 0, out};
|
|
3810
|
+
out.effectFns.push({
|
|
3811
|
+
name: `${name}_cleanup`,
|
|
3812
|
+
body: compileStmts(clist, cenv, state, cctx, ' '),
|
|
3813
|
+
});
|
|
3814
|
+
},
|
|
3815
|
+
};
|
|
3816
|
+
out.effectDecls.push(`static int ${armed};`);
|
|
3817
|
+
}
|
|
3818
|
+
const bodyLines = compileStmts(stmts, env, state, ctx, ' ');
|
|
2473
3819
|
out.effectFns.push({
|
|
2474
3820
|
name,
|
|
2475
|
-
body:
|
|
3821
|
+
body: hasCleanup
|
|
3822
|
+
? [
|
|
3823
|
+
` if (${armed})`,
|
|
3824
|
+
' {',
|
|
3825
|
+
` ${armed} = 0;`,
|
|
3826
|
+
` ${name}_cleanup();`,
|
|
3827
|
+
' }',
|
|
3828
|
+
...bodyLines,
|
|
3829
|
+
]
|
|
3830
|
+
: bodyLines,
|
|
2476
3831
|
});
|
|
2477
3832
|
// A static "previous value" per dep; snapshot at mount, then app_update detects changes against it.
|
|
2478
3833
|
deps.forEach((d, j) =>
|
|
2479
3834
|
out.effectDecls.push(
|
|
2480
3835
|
d.cType === 'string'
|
|
2481
3836
|
? `static char s_eff${id}_d${j}[${LIST_STR_CAP}];`
|
|
2482
|
-
: `static ${d.cType
|
|
3837
|
+
: `static ${cScalarType(d.cType)} s_eff${id}_d${j};`,
|
|
2483
3838
|
),
|
|
2484
3839
|
);
|
|
2485
3840
|
const snap = (j, d) =>
|
|
@@ -2497,7 +3852,7 @@ function compileEffect(eff, env, state, out) {
|
|
|
2497
3852
|
` if (strcmp(s_eff${id}_d${j}, ${d.code}) != 0) { ${snap(j, d)}; er_changed = 1; }`,
|
|
2498
3853
|
);
|
|
2499
3854
|
else {
|
|
2500
|
-
const t = d.cType
|
|
3855
|
+
const t = cScalarType(d.cType);
|
|
2501
3856
|
check.push(
|
|
2502
3857
|
` ${t} er_d${j} = ${d.code}; if (er_d${j} != s_eff${id}_d${j}) { s_eff${id}_d${j} = er_d${j}; er_changed = 1; }`,
|
|
2503
3858
|
);
|
|
@@ -2526,7 +3881,7 @@ function compileHandler(fnNode, env, state, out, pan = null) {
|
|
|
2526
3881
|
if (gestureParam) henv = {...henv, gesture: gestureParam, pan};
|
|
2527
3882
|
const ctx = {stateChanged: false, animIdx: 0, out};
|
|
2528
3883
|
const stmts = compileStmts(list, henv, state, ctx, ' ');
|
|
2529
|
-
if (ctx.stateChanged) stmts.push(
|
|
3884
|
+
if (ctx.stateChanged) stmts.push(APP_UPDATE_CALL); // re-apply state-dependent props once
|
|
2530
3885
|
return stmts;
|
|
2531
3886
|
}
|
|
2532
3887
|
|
|
@@ -2926,7 +4281,7 @@ function extractProps(openingElement, scope, env) {
|
|
|
2926
4281
|
try {
|
|
2927
4282
|
props[attr.name.name] = {static: true, value: evalStatic(node, scope)};
|
|
2928
4283
|
} catch {
|
|
2929
|
-
props[attr.name.name] = {static: false, ...
|
|
4284
|
+
props[attr.name.name] = {static: false, ...emitExprWide(node, env)};
|
|
2930
4285
|
}
|
|
2931
4286
|
}
|
|
2932
4287
|
return props;
|
|
@@ -3009,8 +4364,14 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
3009
4364
|
childrenRef = {kind: 'props', name: param.name};
|
|
3010
4365
|
}
|
|
3011
4366
|
|
|
3012
|
-
|
|
3013
|
-
const
|
|
4367
|
+
// A child component is a module-level function: its body resolves names against MODULE scope, not the
|
|
4368
|
+
// caller's locals. Copying the caller's scope here would let an App-local const shadow a module one
|
|
4369
|
+
// inside the child, which JavaScript never does.
|
|
4370
|
+
const childScope = {...(env.moduleConsts ?? scope)};
|
|
4371
|
+
// A child is a module-level function: it closes over module scope and receives everything else
|
|
4372
|
+
// through props. Starting from the caller's locals let App's memos and dynamic consts leak in —
|
|
4373
|
+
// and then masked the child's own `const` of the same name.
|
|
4374
|
+
const childLocals = new Map();
|
|
3014
4375
|
// Callback props bound here resolve to the CALLER's function (node + caller env/state) so the child can
|
|
3015
4376
|
// use them as event handlers (onPress={onTap}); inherit any the caller itself received (forwarding).
|
|
3016
4377
|
const fnProps = new Map(env.fnProps);
|
|
@@ -3026,8 +4387,18 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
3026
4387
|
state: d.state ?? state,
|
|
3027
4388
|
});
|
|
3028
4389
|
else if (d.static) childScope[name] = d.value;
|
|
3029
|
-
else
|
|
3030
|
-
childLocals.set(name, {
|
|
4390
|
+
else {
|
|
4391
|
+
childLocals.set(name, {
|
|
4392
|
+
code: d.code,
|
|
4393
|
+
cType: d.cType,
|
|
4394
|
+
struct: d.struct,
|
|
4395
|
+
isBool: d.isBool, // keep boolean-ness across the prop boundary (extractProps supplies it)
|
|
4396
|
+
});
|
|
4397
|
+
// A dynamic prop is a RUNTIME binding. Every constant fold in the child (styles, colors, enums,
|
|
4398
|
+
// svg attrs, text) consults childScope first, so a module const of the same name must not be
|
|
4399
|
+
// left there to win — the fold would silently emit the module value instead of the prop.
|
|
4400
|
+
delete childScope[name];
|
|
4401
|
+
}
|
|
3031
4402
|
}
|
|
3032
4403
|
const children = childNodes.length
|
|
3033
4404
|
? {nodes: childNodes, scope, env, ref: childrenRef}
|
|
@@ -3039,16 +4410,47 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
3039
4410
|
// exactly like a React component — it receives everything else through props. All initials/values fold
|
|
3040
4411
|
// against the child's static-prop scope. prefix is per-instance; the App keeps the bare (unprefixed) names.
|
|
3041
4412
|
const prefix = `c${out.instN++}_`;
|
|
4413
|
+
// Fold the child's own statically-derived body consts, the way compileSourceImpl does for App. Without
|
|
4414
|
+
// this a `const L = …` in a child body either failed to resolve or, when a module const shared the
|
|
4415
|
+
// name, silently rendered the MODULE value — the child's declaration must shadow it.
|
|
4416
|
+
if (fn.body.type === 'BlockStatement') {
|
|
4417
|
+
// As in App: the body's own names, hook bindings included, shadow module ones before anything folds.
|
|
4418
|
+
for (const name of declaredNames(fn.body.body)) delete childScope[name];
|
|
4419
|
+
for (const stmt of fn.body.body) {
|
|
4420
|
+
if (stmt.type !== 'VariableDeclaration' || stmt.kind !== 'const')
|
|
4421
|
+
continue;
|
|
4422
|
+
for (const decl of stmt.declarations) {
|
|
4423
|
+
if (decl.id.type !== 'Identifier' || !decl.init) continue;
|
|
4424
|
+
if (childLocals.has(decl.id.name)) continue; // a dynamic prop of that name is already bound
|
|
4425
|
+
try {
|
|
4426
|
+
childScope[decl.id.name] = evalStatic(
|
|
4427
|
+
decl.init,
|
|
4428
|
+
withUndefined(childScope),
|
|
4429
|
+
);
|
|
4430
|
+
} catch {
|
|
4431
|
+
// Dynamic (state-derived, useMemo, …): the child's binding shadows any module const of the
|
|
4432
|
+
// same name, so that const must not stay visible — a hook initializer or text reading it would
|
|
4433
|
+
// silently get the module value. A memo re-binds it below; anything else is an unresolved name.
|
|
4434
|
+
delete childScope[decl.id.name];
|
|
4435
|
+
}
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
4438
|
+
}
|
|
4439
|
+
|
|
3042
4440
|
const childAnims = collectAnims(fn.body, childScope, prefix);
|
|
3043
|
-
const childRefs = collectRefs(fn.body, childScope, prefix);
|
|
4441
|
+
const childRefs = collectRefs(fn.body, childScope, prefix, env.wide);
|
|
3044
4442
|
const childPans = collectPanResponders(fn.body, prefix);
|
|
3045
4443
|
const childCallbacks = collectCallbacks(fn.body);
|
|
3046
4444
|
const childMemos = collectMemos(fn.body);
|
|
3047
4445
|
let childState = state;
|
|
3048
4446
|
if (usesState(fn)) {
|
|
3049
|
-
childState = collectState(fn.body, childScope, prefix);
|
|
4447
|
+
childState = collectState(fn.body, childScope, prefix, env.wide);
|
|
3050
4448
|
out.childStateRecords.push(...childState.byName.values());
|
|
4449
|
+
for (const name of childState.byName.keys()) delete childScope[name];
|
|
3051
4450
|
}
|
|
4451
|
+
// The child's own refs and animated values are runtime bindings too (see compileSourceImpl).
|
|
4452
|
+
for (const name of [...childAnims.keys(), ...childRefs.keys()])
|
|
4453
|
+
delete childScope[name];
|
|
3052
4454
|
out.childRefs.push(...childRefs.values());
|
|
3053
4455
|
out.childAnims.push(...childAnims.values());
|
|
3054
4456
|
|
|
@@ -3073,8 +4475,13 @@ function emitComponent(el, scope, out, env, state, opts) {
|
|
|
3073
4475
|
try {
|
|
3074
4476
|
childScope[name] = evalStatic(expr, childScope);
|
|
3075
4477
|
} catch {
|
|
3076
|
-
const e =
|
|
3077
|
-
childLocals.set(name, {
|
|
4478
|
+
const e = emitExprWide(expr, childEnv);
|
|
4479
|
+
childLocals.set(name, {
|
|
4480
|
+
code: `(${e.code})`,
|
|
4481
|
+
cType: e.cType,
|
|
4482
|
+
isBool: e.isBool,
|
|
4483
|
+
});
|
|
4484
|
+
delete childScope[name]; // a runtime binding beats a module const of its name in every fold
|
|
3078
4485
|
}
|
|
3079
4486
|
}
|
|
3080
4487
|
for (const eff of collectEffects(fn.body)) {
|
|
@@ -3126,12 +4533,42 @@ function emitMap(call, parentVar, scope, out, env, state) {
|
|
|
3126
4533
|
parentVar,
|
|
3127
4534
|
iterScope,
|
|
3128
4535
|
out,
|
|
3129
|
-
|
|
4536
|
+
rowEnv(env, [itemName, idxName], iterScope),
|
|
3130
4537
|
state,
|
|
3131
4538
|
);
|
|
3132
4539
|
});
|
|
3133
4540
|
}
|
|
3134
4541
|
|
|
4542
|
+
/**
|
|
4543
|
+
* The env for one `.map` row. Its callback params (item, index) shadow every outer binding of the same
|
|
4544
|
+
* name — a JS arrow parameter always does — so those names leave every name-keyed map (state, locals,
|
|
4545
|
+
* callbacks, helpers, …) and the row's own binding wins: in `consts`, or in `ownLocals` for a pooled
|
|
4546
|
+
* row's struct item.
|
|
4547
|
+
*/
|
|
4548
|
+
function rowEnv(env, params, consts, ownLocals = null) {
|
|
4549
|
+
const names = params.filter(Boolean);
|
|
4550
|
+
const drop = m => {
|
|
4551
|
+
if (!m || !names.some(n => m.has(n))) return m;
|
|
4552
|
+
const c = new Map(m);
|
|
4553
|
+
for (const n of names) c.delete(n);
|
|
4554
|
+
return c;
|
|
4555
|
+
};
|
|
4556
|
+
return {
|
|
4557
|
+
...env,
|
|
4558
|
+
consts,
|
|
4559
|
+
state: drop(env.state),
|
|
4560
|
+
refs: drop(env.refs),
|
|
4561
|
+
anims: drop(env.anims),
|
|
4562
|
+
locals: ownLocals ?? drop(env.locals),
|
|
4563
|
+
callbacks: drop(env.callbacks),
|
|
4564
|
+
fnProps: drop(env.fnProps),
|
|
4565
|
+
pans: drop(env.pans),
|
|
4566
|
+
helpers: drop(env.helpers),
|
|
4567
|
+
svgImports: drop(env.svgImports),
|
|
4568
|
+
children: names.includes(env.children?.ref?.name) ? null : env.children,
|
|
4569
|
+
};
|
|
4570
|
+
}
|
|
4571
|
+
|
|
3135
4572
|
/**
|
|
3136
4573
|
* `{listState.map((item, i) => <Row/>)}` over a STATE array of variable length. Pre-allocates a fixed
|
|
3137
4574
|
* pool of `cap` rows (no runtime malloc); each row k binds `item` to `s_<name>[k]` (a struct local) and
|
|
@@ -3146,8 +4583,12 @@ function emitDynamicMap(call, rec, parentVar, scope, out, env, state) {
|
|
|
3146
4583
|
const retJSX = componentReturnJSX(cb);
|
|
3147
4584
|
for (let k = 0; k < rec.cap; k++) {
|
|
3148
4585
|
const iterScope = {...scope};
|
|
4586
|
+
// The item is a runtime local (a struct slot), so a same-named module const must not shadow it
|
|
4587
|
+
// in any fold inside the row — see the dynamic-prop note in emitComponent.
|
|
4588
|
+
if (itemName) delete iterScope[itemName];
|
|
3149
4589
|
if (idxName) iterScope[idxName] = k; // the index is a compile-time literal per pooled row
|
|
3150
4590
|
const locals = new Map(env.locals);
|
|
4591
|
+
if (idxName) locals.delete(idxName); // the index is a per-row literal in iterScope
|
|
3151
4592
|
if (itemName)
|
|
3152
4593
|
locals.set(itemName, {
|
|
3153
4594
|
code: `${rec.arrayName}[${k}]`,
|
|
@@ -3158,7 +4599,7 @@ function emitDynamicMap(call, rec, parentVar, scope, out, env, state) {
|
|
|
3158
4599
|
parentVar,
|
|
3159
4600
|
iterScope,
|
|
3160
4601
|
out,
|
|
3161
|
-
|
|
4602
|
+
rowEnv(env, [itemName, idxName], iterScope, locals),
|
|
3162
4603
|
state,
|
|
3163
4604
|
{
|
|
3164
4605
|
displayCode: `(${k} < ${rec.countMember})`,
|
|
@@ -3196,7 +4637,7 @@ function emitChildren(children, parentVar, scope, out, env, state) {
|
|
|
3196
4637
|
if (cond)
|
|
3197
4638
|
emitElementInto(expr.right, parentVar, scope, out, env, state);
|
|
3198
4639
|
} catch {
|
|
3199
|
-
const code = emitExpr(expr.left, env)
|
|
4640
|
+
const code = asCond(emitExpr(expr.left, env));
|
|
3200
4641
|
emitElementInto(expr.right, parentVar, scope, out, env, state, {
|
|
3201
4642
|
displayCode: code,
|
|
3202
4643
|
});
|
|
@@ -3219,7 +4660,7 @@ function emitChildren(children, parentVar, scope, out, env, state) {
|
|
|
3219
4660
|
state,
|
|
3220
4661
|
);
|
|
3221
4662
|
} catch {
|
|
3222
|
-
const code = emitExpr(expr.test, env)
|
|
4663
|
+
const code = asCond(emitExpr(expr.test, env));
|
|
3223
4664
|
if (expr.consequent.type === 'JSXElement')
|
|
3224
4665
|
emitElementInto(
|
|
3225
4666
|
expr.consequent,
|
|
@@ -3388,8 +4829,15 @@ function svgAttrs(openingElement, scope, env) {
|
|
|
3388
4829
|
else if (vn.type === 'StringLiteral') out[name] = vn.value;
|
|
3389
4830
|
else if (vn.type === 'JSXExpressionContainer') {
|
|
3390
4831
|
try {
|
|
3391
|
-
out[name] = evalStatic(vn.expression, scope);
|
|
4832
|
+
out[name] = evalStatic(vn.expression, withUndefined(scope));
|
|
3392
4833
|
} catch {
|
|
4834
|
+
// A state-driven `d` is unsupported whatever it is built from, and pathEntries carries the
|
|
4835
|
+
// diagnostic that names the fix (use Arc/Circle/Rect/Line). Emitting it first would replace that
|
|
4836
|
+
// with whatever generic reason the expression itself fails for.
|
|
4837
|
+
if (name === 'd') {
|
|
4838
|
+
out[name] = {dyn: null, node: vn.expression};
|
|
4839
|
+
continue;
|
|
4840
|
+
}
|
|
3393
4841
|
// Keep the raw expression node too: color paint attrs (fill/stroke) lower via emitColorExpr (→ ARGB),
|
|
3394
4842
|
// not the generic numeric `dyn` code, so a dynamic color resolves to a uint, not a char*.
|
|
3395
4843
|
out[name] = {
|
|
@@ -3502,13 +4950,13 @@ function gradAttr(v, scope, env, what) {
|
|
|
3502
4950
|
node.consequent.type === 'ObjectExpression' &&
|
|
3503
4951
|
nullish(node.alternate)
|
|
3504
4952
|
) {
|
|
3505
|
-
cond = emitExpr(node.test, env)
|
|
4953
|
+
cond = asCond(emitExpr(node.test, env));
|
|
3506
4954
|
node = node.consequent;
|
|
3507
4955
|
} else if (
|
|
3508
4956
|
node.alternate.type === 'ObjectExpression' &&
|
|
3509
4957
|
nullish(node.consequent)
|
|
3510
4958
|
) {
|
|
3511
|
-
cond = `!(${emitExpr(node.test, env)
|
|
4959
|
+
cond = `!(${asCond(emitExpr(node.test, env))})`;
|
|
3512
4960
|
node = node.alternate;
|
|
3513
4961
|
} else
|
|
3514
4962
|
throw new Error(
|
|
@@ -3519,7 +4967,7 @@ function gradAttr(v, scope, env, what) {
|
|
|
3519
4967
|
node.operator === '&&' &&
|
|
3520
4968
|
node.right.type === 'ObjectExpression'
|
|
3521
4969
|
) {
|
|
3522
|
-
cond = emitExpr(node.left, env)
|
|
4970
|
+
cond = asCond(emitExpr(node.left, env));
|
|
3523
4971
|
node = node.right;
|
|
3524
4972
|
}
|
|
3525
4973
|
const spec = gradSpec(node, scope, env, what);
|
|
@@ -4163,11 +5611,13 @@ function compileValueHandler(
|
|
|
4163
5611
|
out,
|
|
4164
5612
|
cType = 'int',
|
|
4165
5613
|
valueCode2 = null,
|
|
5614
|
+
isBool = false,
|
|
4166
5615
|
) {
|
|
4167
5616
|
const param =
|
|
4168
5617
|
fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
|
|
4169
5618
|
const locals = new Map(env.locals);
|
|
4170
|
-
|
|
5619
|
+
// A <Switch> hands its callback a boolean; carry that so `'on=' + v` prints true/false, not 1/0.
|
|
5620
|
+
if (param) locals.set(param, {code: valueCode, cType, isBool});
|
|
4171
5621
|
// A second parameter (a RANGE <Dial>'s low end) binds the same way, so `onChange={(hi, lo) => …}`
|
|
4172
5622
|
// lowers to data->value / data->value_start with no object allocated on device.
|
|
4173
5623
|
const param2 =
|
|
@@ -4180,7 +5630,7 @@ function compileValueHandler(
|
|
|
4180
5630
|
? body.body
|
|
4181
5631
|
: [{type: 'ExpressionStatement', expression: body}];
|
|
4182
5632
|
const stmts = compileStmts(list, {...env, locals}, state, ctx, ' ');
|
|
4183
|
-
if (ctx.stateChanged) stmts.push(
|
|
5633
|
+
if (ctx.stateChanged) stmts.push(APP_UPDATE_CALL);
|
|
4184
5634
|
return stmts;
|
|
4185
5635
|
}
|
|
4186
5636
|
|
|
@@ -4536,7 +5986,7 @@ function emitSwitch(el, scope, out, env, state) {
|
|
|
4536
5986
|
} catch {
|
|
4537
5987
|
dynAssigns.push({
|
|
4538
5988
|
field: 'switch_value',
|
|
4539
|
-
code: `(uint8_t)((${emitExpr(valueNode, env)
|
|
5989
|
+
code: `(uint8_t)((${asCond(emitExpr(valueNode, env))}) ? 1 : 0)`,
|
|
4540
5990
|
});
|
|
4541
5991
|
}
|
|
4542
5992
|
}
|
|
@@ -4566,10 +6016,19 @@ function emitSwitch(el, scope, out, env, state) {
|
|
|
4566
6016
|
'controlled switch: <Switch value={on} onValueChange={(v) => setOn(v)} />',
|
|
4567
6017
|
);
|
|
4568
6018
|
const handlerName = `er_handler_${out.handlers.length}`;
|
|
4569
|
-
const toggled = `(!(${emitExpr(valueNode, env)
|
|
6019
|
+
const toggled = `(!(${asCond(emitExpr(valueNode, env))}))`; // the engine toggles on press → param is !value
|
|
4570
6020
|
out.handlers.push({
|
|
4571
6021
|
name: handlerName,
|
|
4572
|
-
body: compileValueHandler(
|
|
6022
|
+
body: compileValueHandler(
|
|
6023
|
+
onChangeFn,
|
|
6024
|
+
toggled,
|
|
6025
|
+
env,
|
|
6026
|
+
state,
|
|
6027
|
+
out,
|
|
6028
|
+
'int',
|
|
6029
|
+
null,
|
|
6030
|
+
true,
|
|
6031
|
+
),
|
|
4573
6032
|
});
|
|
4574
6033
|
out.build.push(
|
|
4575
6034
|
` er_event_set(${v}, ER_EVENT_PRESS, ${handlerName}, NULL);`,
|
|
@@ -4617,15 +6076,16 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
4617
6076
|
field: 'cursor_color',
|
|
4618
6077
|
expr: colorLiteral(String(evalStatic(node, scope))),
|
|
4619
6078
|
});
|
|
4620
|
-
else if (name === 'editable') {
|
|
6079
|
+
else if (name === 'editable' || name === 'secureTextEntry') {
|
|
6080
|
+
const field = name === 'editable' ? 'editable' : 'secure_text_entry';
|
|
4621
6081
|
try {
|
|
4622
6082
|
staticAssigns.push({
|
|
4623
|
-
field
|
|
6083
|
+
field,
|
|
4624
6084
|
expr: evalStatic(node, scope) ? '1' : '0',
|
|
4625
6085
|
});
|
|
4626
6086
|
} catch {
|
|
4627
6087
|
dynAssigns.push({
|
|
4628
|
-
field
|
|
6088
|
+
field,
|
|
4629
6089
|
code: `(uint8_t)((${emitExpr(node, env).code}) ? 1 : 0)`,
|
|
4630
6090
|
});
|
|
4631
6091
|
}
|
|
@@ -4633,7 +6093,6 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
4633
6093
|
[
|
|
4634
6094
|
'autoFocus',
|
|
4635
6095
|
'keyboardType',
|
|
4636
|
-
'secureTextEntry',
|
|
4637
6096
|
'maxLength',
|
|
4638
6097
|
'multiline',
|
|
4639
6098
|
'autoCapitalize',
|
|
@@ -4648,7 +6107,7 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
4648
6107
|
} else
|
|
4649
6108
|
throw aotError(
|
|
4650
6109
|
`AOT: <TextInput> prop "${name}" is not supported`,
|
|
4651
|
-
'supported props: value, onChangeText, placeholder, placeholderTextColor, cursorColor, editable, style.',
|
|
6110
|
+
'supported props: value, onChangeText, placeholder, placeholderTextColor, cursorColor, editable, secureTextEntry, style.',
|
|
4652
6111
|
);
|
|
4653
6112
|
}
|
|
4654
6113
|
|
|
@@ -4656,17 +6115,8 @@ function emitTextInput(el, scope, out, env, state) {
|
|
|
4656
6115
|
// state-driven value re-synced each app_update.
|
|
4657
6116
|
let text = null;
|
|
4658
6117
|
if (valueNode) {
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
text = {
|
|
4662
|
-
dynamic: false,
|
|
4663
|
-
format: (cv == null ? '' : String(cv)).replace(/%/g, '%%'),
|
|
4664
|
-
args: [],
|
|
4665
|
-
};
|
|
4666
|
-
} catch {
|
|
4667
|
-
const e = emitExpr(valueNode, env);
|
|
4668
|
-
text = {dynamic: true, format: printfSpec(e.cType), args: [e.code]};
|
|
4669
|
-
}
|
|
6118
|
+
const f = emitFormat(valueNode, env, scope);
|
|
6119
|
+
text = {dynamic: f.args.length > 0, format: f.format, args: f.args};
|
|
4670
6120
|
}
|
|
4671
6121
|
|
|
4672
6122
|
const isDynamic = dynAssigns.length > 0 || (text && text.dynamic);
|
|
@@ -5221,6 +6671,7 @@ function touchablePressFades(
|
|
|
5221
6671
|
}
|
|
5222
6672
|
|
|
5223
6673
|
function emitNodeImpl(el, scope, out, env, state, opts = {}) {
|
|
6674
|
+
el = omitUndefinedAttrs(el, scope, env);
|
|
5224
6675
|
const tag = resolveTag(el.openingElement);
|
|
5225
6676
|
if (tag === 'Svg') return emitSvg(el, scope, out, env, state, opts);
|
|
5226
6677
|
if (tag === 'Switch') return emitSwitch(el, scope, out, env, state);
|
|
@@ -5513,6 +6964,34 @@ function emitNodeImpl(el, scope, out, env, state, opts = {}) {
|
|
|
5513
6964
|
if (tag !== 'Text') emitChildren(el.children, v, scope, out, env, state);
|
|
5514
6965
|
return v;
|
|
5515
6966
|
}
|
|
6967
|
+
/**
|
|
6968
|
+
* `el` without the attributes whose value folds to `undefined` in this scope — typically a prop a child
|
|
6969
|
+
* component was never given. Flow A omits an undefined prop, so every reader has to see it as absent;
|
|
6970
|
+
* read as a value, `visible` hid the node and `placeholder` printed the word "undefined". This is the one
|
|
6971
|
+
* place that rule lives: every element reaches its reader through here. A copy is returned only when
|
|
6972
|
+
* something is dropped, because the same JSX node is emitted once per scope (each .map row, each
|
|
6973
|
+
* component instance) and one scope's answer must not leak into another's.
|
|
6974
|
+
*/
|
|
6975
|
+
function omitUndefinedAttrs(el, scope, env) {
|
|
6976
|
+
const attrs = el.openingElement.attributes;
|
|
6977
|
+
// Built on first use: the runtime-aware scope, plus the global `undefined` (a reserved name — see
|
|
6978
|
+
// normalizeUndefined), so `SHOW ? true : undefined` with SHOW false folds too.
|
|
6979
|
+
let fold = null;
|
|
6980
|
+
const kept = attrs.filter(a => {
|
|
6981
|
+
if (a.type !== 'JSXAttribute' || a.value?.type !== 'JSXExpressionContainer')
|
|
6982
|
+
return true;
|
|
6983
|
+
fold ??= Object.assign(Object.create(foldScope(env, scope)), {undefined});
|
|
6984
|
+
try {
|
|
6985
|
+
return evalStatic(a.value.expression, fold) !== undefined;
|
|
6986
|
+
} catch {
|
|
6987
|
+
return true; // not a compile-time value — its reader decides
|
|
6988
|
+
}
|
|
6989
|
+
});
|
|
6990
|
+
return kept.length === attrs.length
|
|
6991
|
+
? el
|
|
6992
|
+
: {...el, openingElement: {...el.openingElement, attributes: kept}};
|
|
6993
|
+
}
|
|
6994
|
+
|
|
5516
6995
|
const emitNode = withLoc(emitNodeImpl);
|
|
5517
6996
|
|
|
5518
6997
|
// ---------------------------------------------------------------------------------------------------
|
|
@@ -5742,6 +7221,93 @@ function stripTypeScript(root) {
|
|
|
5742
7221
|
return root;
|
|
5743
7222
|
}
|
|
5744
7223
|
|
|
7224
|
+
/**
|
|
7225
|
+
* One pass over the parsed program that fixes what `undefined` means before anything is compiled.
|
|
7226
|
+
*
|
|
7227
|
+
* - A JSX attribute whose value is `{undefined}` is DROPPED. Flow A's buildProps omits an undefined prop
|
|
7228
|
+
* (`props[k] !== undefined`), so the node keeps its default — `visible={undefined}` stays visible. Doing
|
|
7229
|
+
* it here gives the twenty-odd prop readers that view at once, instead of each deciding what an
|
|
7230
|
+
* undefined value means (one hid the node, one crashed on Object.entries(undefined)).
|
|
7231
|
+
* A value that only becomes undefined in some scope — a prop a child was never given — is dropped per
|
|
7232
|
+
* emission by omitUndefinedAttrs. This literal pass still matters for <Svg> shapes, which bypass it.
|
|
7233
|
+
* - A BINDING named `undefined` is refused. JS allows shadowing the global, but Flow B gives `undefined`
|
|
7234
|
+
* a meaning of its own (an omitted prop, empty text), and a shadowing local would silently lose to it.
|
|
7235
|
+
*/
|
|
7236
|
+
function normalizeUndefined(ast) {
|
|
7237
|
+
const reserved = id => {
|
|
7238
|
+
if (id?.type !== 'Identifier' || id.name !== 'undefined') return;
|
|
7239
|
+
const e = aotError(
|
|
7240
|
+
'AOT: `undefined` cannot be used as a name',
|
|
7241
|
+
'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.',
|
|
7242
|
+
);
|
|
7243
|
+
if (id.loc) e.aotLoc = id.loc.start;
|
|
7244
|
+
throw e;
|
|
7245
|
+
};
|
|
7246
|
+
const pattern = p => {
|
|
7247
|
+
if (!p) return;
|
|
7248
|
+
if (p.type === 'Identifier') reserved(p);
|
|
7249
|
+
else if (p.type === 'ArrayPattern') p.elements.forEach(pattern);
|
|
7250
|
+
else if (p.type === 'ObjectPattern')
|
|
7251
|
+
p.properties.forEach(q =>
|
|
7252
|
+
pattern(q.type === 'RestElement' ? q.argument : q.value),
|
|
7253
|
+
);
|
|
7254
|
+
else if (p.type === 'AssignmentPattern') pattern(p.left);
|
|
7255
|
+
else if (p.type === 'RestElement') pattern(p.argument);
|
|
7256
|
+
};
|
|
7257
|
+
const isUndefinedAttr = a =>
|
|
7258
|
+
a.type === 'JSXAttribute' &&
|
|
7259
|
+
a.value?.type === 'JSXExpressionContainer' &&
|
|
7260
|
+
a.value.expression.type === 'Identifier' &&
|
|
7261
|
+
a.value.expression.name === 'undefined';
|
|
7262
|
+
const SKIP = new Set([
|
|
7263
|
+
'loc',
|
|
7264
|
+
'start',
|
|
7265
|
+
'end',
|
|
7266
|
+
'extra',
|
|
7267
|
+
'leadingComments',
|
|
7268
|
+
'trailingComments',
|
|
7269
|
+
'innerComments',
|
|
7270
|
+
]);
|
|
7271
|
+
const visit = node => {
|
|
7272
|
+
if (!node || typeof node.type !== 'string') return;
|
|
7273
|
+
switch (node.type) {
|
|
7274
|
+
case 'VariableDeclarator':
|
|
7275
|
+
pattern(node.id);
|
|
7276
|
+
break;
|
|
7277
|
+
case 'FunctionDeclaration':
|
|
7278
|
+
case 'FunctionExpression':
|
|
7279
|
+
case 'ArrowFunctionExpression':
|
|
7280
|
+
case 'ObjectMethod':
|
|
7281
|
+
case 'ClassMethod':
|
|
7282
|
+
if (node.id) reserved(node.id);
|
|
7283
|
+
node.params.forEach(pattern);
|
|
7284
|
+
break;
|
|
7285
|
+
case 'CatchClause':
|
|
7286
|
+
pattern(node.param);
|
|
7287
|
+
break;
|
|
7288
|
+
case 'ClassDeclaration':
|
|
7289
|
+
case 'ClassExpression':
|
|
7290
|
+
if (node.id) reserved(node.id);
|
|
7291
|
+
break;
|
|
7292
|
+
case 'ImportSpecifier':
|
|
7293
|
+
case 'ImportDefaultSpecifier':
|
|
7294
|
+
case 'ImportNamespaceSpecifier':
|
|
7295
|
+
reserved(node.local);
|
|
7296
|
+
break;
|
|
7297
|
+
case 'JSXOpeningElement':
|
|
7298
|
+
node.attributes = node.attributes.filter(a => !isUndefinedAttr(a));
|
|
7299
|
+
break;
|
|
7300
|
+
}
|
|
7301
|
+
for (const key of Object.keys(node)) {
|
|
7302
|
+
if (SKIP.has(key)) continue;
|
|
7303
|
+
const v = node[key];
|
|
7304
|
+
if (Array.isArray(v)) v.forEach(visit);
|
|
7305
|
+
else if (v && typeof v.type === 'string') visit(v);
|
|
7306
|
+
}
|
|
7307
|
+
};
|
|
7308
|
+
visit(ast);
|
|
7309
|
+
}
|
|
7310
|
+
|
|
5745
7311
|
/** Parse an app entry to a JS+JSX AST, transparently stripping TypeScript when the entry is .ts/.tsx. */
|
|
5746
7312
|
function parseApp(src, opts = {}) {
|
|
5747
7313
|
const ts = isTsEntry(opts);
|
|
@@ -5754,10 +7320,15 @@ function parseApp(src, opts = {}) {
|
|
|
5754
7320
|
* Compiles a Flow B app's JSX (or TSX) source to C.
|
|
5755
7321
|
* @param {string} src The App.jsx/App.tsx source text.
|
|
5756
7322
|
* @param {string} demo Demo name (only used in the generated-by header comment).
|
|
7323
|
+
* @param {object} opts compileSource's options.
|
|
7324
|
+
* @param {Set<string>} wide State/ref slots to declare 64-bit (see compileWidened).
|
|
7325
|
+
* @param {Set<string>} found Collects the int slots a 64-bit timestamp was stored in.
|
|
5757
7326
|
* @returns {{c: string, h: string, nodes: number, state: number, handlers: number, updates: number}}
|
|
5758
7327
|
*/
|
|
5759
|
-
function compileSourceImpl(src, demo
|
|
7328
|
+
function compileSourceImpl(src, demo, opts, wide, found) {
|
|
5760
7329
|
const ast = parseApp(src, opts);
|
|
7330
|
+
normalizeUndefined(ast);
|
|
7331
|
+
const shadowedClock = findShadowedClockCalls(ast);
|
|
5761
7332
|
|
|
5762
7333
|
const screen = opts.screen ?? {width: SCREEN_W, height: SCREEN_H};
|
|
5763
7334
|
// Image imports first, so their asset-name strings seed the module scope BEFORE its consts fold (a const
|
|
@@ -5768,27 +7339,37 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5768
7339
|
[...imageImports].map(([local, imp]) => [local, imp.name]),
|
|
5769
7340
|
);
|
|
5770
7341
|
const scope = moduleScope(ast.program, screen, imageSeed);
|
|
7342
|
+
// Module bindings ALONE, before App's own consts are folded in below. A child component is declared at
|
|
7343
|
+
// module level, so its body closes over these — not over whatever App happens to have shadowed.
|
|
7344
|
+
const moduleConsts = {...scope};
|
|
5771
7345
|
const component = findComponent(ast.program);
|
|
5772
7346
|
// Fold statically-derived component-local consts (e.g. `const compact = screen.width < 400`) into the
|
|
5773
7347
|
// const scope, so responsive `if` branches and styles can switch on them at compile time. Dynamic consts
|
|
5774
7348
|
// (state-derived, useMemo, etc.) throw here and are skipped — they're handled later by memos/emitExpr.
|
|
7349
|
+
// Every name the body declares — a hook's destructured state included — shadows the module binding
|
|
7350
|
+
// before any local folds, or `const copy = r` would capture a module `r` that state `r` hides.
|
|
7351
|
+
for (const name of declaredNames(component.body.body)) delete scope[name];
|
|
5775
7352
|
for (const stmt of component.body.body) {
|
|
5776
7353
|
if (stmt.type !== 'VariableDeclaration' || stmt.kind !== 'const') continue;
|
|
5777
7354
|
for (const decl of stmt.declarations) {
|
|
5778
|
-
if (decl.id.type !== 'Identifier' || !decl.init
|
|
5779
|
-
continue;
|
|
7355
|
+
if (decl.id.type !== 'Identifier' || !decl.init) continue;
|
|
5780
7356
|
try {
|
|
5781
|
-
scope[decl.id.name] = evalStatic(decl.init, scope);
|
|
7357
|
+
scope[decl.id.name] = evalStatic(decl.init, withUndefined(scope));
|
|
5782
7358
|
} catch {
|
|
5783
|
-
|
|
7359
|
+
// Dynamic (state-derived, useMemo, …). A memo is re-bound below and a plain derived const is not
|
|
7360
|
+
// supported — either way a same-named module const must not stay visible to the folds, or the
|
|
7361
|
+
// JSX quietly renders the module value. Mirrors the child-component path.
|
|
7362
|
+
delete scope[decl.id.name];
|
|
5784
7363
|
}
|
|
5785
7364
|
}
|
|
5786
7365
|
}
|
|
5787
|
-
const state = collectState(component.body, scope);
|
|
7366
|
+
const state = collectState(component.body, scope, '', wide);
|
|
7367
|
+
for (const name of state.byName.keys()) delete scope[name];
|
|
5788
7368
|
const rootJSX = findReturnJSX(component.body, scope);
|
|
5789
7369
|
|
|
5790
7370
|
const anims = collectAnims(component.body, scope);
|
|
5791
|
-
const refs = collectRefs(component.body, scope);
|
|
7371
|
+
const refs = collectRefs(component.body, scope, '', wide);
|
|
7372
|
+
for (const name of [...anims.keys(), ...refs.keys()]) delete scope[name];
|
|
5792
7373
|
const pans = collectPanResponders(component.body);
|
|
5793
7374
|
const callbacks = collectCallbacks(component.body);
|
|
5794
7375
|
const memos = collectMemos(component.body);
|
|
@@ -5800,6 +7381,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5800
7381
|
state: state.byName,
|
|
5801
7382
|
locals: new Map(),
|
|
5802
7383
|
consts: scope,
|
|
7384
|
+
moduleConsts, // what an inlined child component sees (see emitComponent)
|
|
5803
7385
|
anims,
|
|
5804
7386
|
refs,
|
|
5805
7387
|
pans,
|
|
@@ -5808,6 +7390,9 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5808
7390
|
imageNames,
|
|
5809
7391
|
svgImports,
|
|
5810
7392
|
svgArtifacts: opts.svgArtifacts || {},
|
|
7393
|
+
wide,
|
|
7394
|
+
found,
|
|
7395
|
+
shadowedClock,
|
|
5811
7396
|
};
|
|
5812
7397
|
// Resolve memos in declaration order: constant-fold into the const scope when possible, else register a
|
|
5813
7398
|
// derived C expression in locals so each reference inlines it (the AOT has no per-render cache — the dep
|
|
@@ -5816,8 +7401,13 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5816
7401
|
try {
|
|
5817
7402
|
scope[name] = evalStatic(expr, scope);
|
|
5818
7403
|
} catch {
|
|
5819
|
-
const e =
|
|
5820
|
-
env.locals.set(name, {
|
|
7404
|
+
const e = emitExprWide(expr, env);
|
|
7405
|
+
env.locals.set(name, {
|
|
7406
|
+
code: `(${e.code})`,
|
|
7407
|
+
cType: e.cType,
|
|
7408
|
+
isBool: e.isBool,
|
|
7409
|
+
});
|
|
7410
|
+
delete scope[name]; // a runtime binding beats a module const of its name in every fold
|
|
5821
7411
|
}
|
|
5822
7412
|
}
|
|
5823
7413
|
const out = {
|
|
@@ -5883,7 +7473,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5883
7473
|
? ` char ${f.key}[${LIST_STR_CAP}];`
|
|
5884
7474
|
: ` ${f.kind} ${f.key};`;
|
|
5885
7475
|
const itemInit = (item, struct) =>
|
|
5886
|
-
`{ ${struct.fields.map(f => (f.kind === 'string' ? cstr(String(item[f.key] ?? '')) : f.kind === 'float' ?
|
|
7476
|
+
`{ ${struct.fields.map(f => (f.kind === 'string' ? cstr(String(item[f.key] ?? '')) : f.kind === 'float' ? floatLit(Number(item[f.key]) || 0) : String(Math.round(Number(item[f.key]) || 0)))).join(', ')} }`;
|
|
5887
7477
|
const listBlocks = listRecords
|
|
5888
7478
|
.map(
|
|
5889
7479
|
s =>
|
|
@@ -5895,7 +7485,7 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5895
7485
|
const scalarFieldDecl = s =>
|
|
5896
7486
|
s.cType === 'string'
|
|
5897
7487
|
? ` char ${s.cField}[${LIST_STR_CAP}];`
|
|
5898
|
-
: ` ${s.cType
|
|
7488
|
+
: ` ${cScalarType(s.cType)} ${s.cField};`;
|
|
5899
7489
|
const scalarBlock = scalarRecords.length
|
|
5900
7490
|
? `typedef struct\n{\n${scalarRecords.map(scalarFieldDecl).join('\n')}\n} ErAppState;\n\nstatic ErAppState s_state = {${scalarRecords.map(s => ` .${s.cField} = ${s.initCode}`).join(',')} };\n`
|
|
5901
7491
|
: '';
|
|
@@ -5908,7 +7498,10 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5908
7498
|
// so consumer builds don't warn about an unused static.
|
|
5909
7499
|
const refDecls = [...refs.values(), ...out.childRefs]
|
|
5910
7500
|
.filter(r => r.used)
|
|
5911
|
-
.map(
|
|
7501
|
+
.map(
|
|
7502
|
+
r =>
|
|
7503
|
+
`static ${r.kind === 'value' ? cScalarType(r.cType) : r.cType} ${r.cVar} = ${r.initCode};`,
|
|
7504
|
+
)
|
|
5912
7505
|
.join('\n');
|
|
5913
7506
|
|
|
5914
7507
|
// Baked vector op-tapes + paint tables (static <Svg> geometry), emitted at file scope.
|
|
@@ -5929,6 +7522,18 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5929
7522
|
out.updates.length > 0 ||
|
|
5930
7523
|
out.svgUpdates.length > 0 ||
|
|
5931
7524
|
out.depEffects.length > 0;
|
|
7525
|
+
// With nothing to re-apply there is no app_update, so the calls queued by setters go too.
|
|
7526
|
+
if (!hasUpdate) {
|
|
7527
|
+
const dropUpdate = lines => lines.filter(l => l !== APP_UPDATE_CALL);
|
|
7528
|
+
for (const f of [
|
|
7529
|
+
...out.handlers,
|
|
7530
|
+
...out.timerFns,
|
|
7531
|
+
...out.animCbs,
|
|
7532
|
+
...out.effectFns,
|
|
7533
|
+
])
|
|
7534
|
+
f.body = dropUpdate(f.body);
|
|
7535
|
+
out.mountEffects = dropUpdate(out.mountEffects);
|
|
7536
|
+
}
|
|
5932
7537
|
const updateBlock = (() => {
|
|
5933
7538
|
if (!hasUpdate) return '';
|
|
5934
7539
|
const lines = ['static void app_update(void)', '{'];
|
|
@@ -5999,8 +7604,9 @@ function compileSourceImpl(src, demo = 'app', opts = {}) {
|
|
|
5999
7604
|
.join('\n\n');
|
|
6000
7605
|
|
|
6001
7606
|
// setInterval/setTimeout → a small fixed timer table advanced by er_app_tick(dt) (the host calls it each
|
|
6002
|
-
// frame). The table +
|
|
6003
|
-
//
|
|
7607
|
+
// frame). The table + er_timer_add are emitted only when timers are used (er_timer_clear only when
|
|
7608
|
+
// something calls it — see timerClearBlock); er_app_tick is always defined (a no-op otherwise) so a host
|
|
7609
|
+
// can call it unconditionally. Timer callbacks become parameterless C functions.
|
|
6004
7610
|
const timerTableBlock = out.usesTimers
|
|
6005
7611
|
? `#include <stdbool.h>
|
|
6006
7612
|
|
|
@@ -6012,12 +7618,15 @@ typedef struct
|
|
|
6012
7618
|
{
|
|
6013
7619
|
int interval_ms;
|
|
6014
7620
|
int remaining_ms;
|
|
7621
|
+
int gen;
|
|
6015
7622
|
bool repeat;
|
|
6016
7623
|
bool active;
|
|
6017
7624
|
void (*fn)(void);
|
|
6018
7625
|
} ErTimer;
|
|
6019
7626
|
static ErTimer s_timers[ER_AOT_MAX_TIMERS];
|
|
6020
7627
|
|
|
7628
|
+
/* An id carries the slot AND the generation that owns it, so clearing an id whose timer has already
|
|
7629
|
+
finished (a one-shot, or an earlier clear) cannot kill whatever took the slot next. */
|
|
6021
7630
|
static int er_timer_add(int ms, bool repeat, void (*fn)(void))
|
|
6022
7631
|
{
|
|
6023
7632
|
for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
|
|
@@ -6026,21 +7635,14 @@ static int er_timer_add(int ms, bool repeat, void (*fn)(void))
|
|
|
6026
7635
|
{
|
|
6027
7636
|
s_timers[i].interval_ms = ms < 1 ? 1 : ms;
|
|
6028
7637
|
s_timers[i].remaining_ms = s_timers[i].interval_ms;
|
|
7638
|
+
s_timers[i].gen = (s_timers[i].gen + 1) & 0xFFFF;
|
|
6029
7639
|
s_timers[i].repeat = repeat;
|
|
6030
7640
|
s_timers[i].active = true;
|
|
6031
7641
|
s_timers[i].fn = fn;
|
|
6032
|
-
return i;
|
|
7642
|
+
return (s_timers[i].gen * ER_AOT_MAX_TIMERS) + i;
|
|
6033
7643
|
}
|
|
6034
7644
|
}
|
|
6035
7645
|
return -1; /* table full (raise ER_AOT_MAX_TIMERS) */
|
|
6036
|
-
}
|
|
6037
|
-
|
|
6038
|
-
static void er_timer_clear(int id)
|
|
6039
|
-
{
|
|
6040
|
-
if (id >= 0 && id < ER_AOT_MAX_TIMERS)
|
|
6041
|
-
{
|
|
6042
|
-
s_timers[id].active = false;
|
|
6043
|
-
}
|
|
6044
7646
|
}`
|
|
6045
7647
|
: '';
|
|
6046
7648
|
|
|
@@ -6066,10 +7668,15 @@ static void er_timer_clear(int id)
|
|
|
6066
7668
|
)
|
|
6067
7669
|
.join('\n\n');
|
|
6068
7670
|
|
|
7671
|
+
// A wall-clock change is applied here, on the app loop, rather than in the setter: the host may set the
|
|
7672
|
+
// time before er_app_build(), when there is nothing to update yet.
|
|
7673
|
+
const wallClockRefresh = hasUpdate
|
|
7674
|
+
? ' if (s_wall_clock_changed)\n {\n s_wall_clock_changed = 0;\n app_update();\n }\n'
|
|
7675
|
+
: '';
|
|
6069
7676
|
const appTickFn = out.usesTimers
|
|
6070
7677
|
? `void er_app_tick(int dt_ms)
|
|
6071
7678
|
{
|
|
6072
|
-
for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
|
|
7679
|
+
${wallClockRefresh} for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
|
|
6073
7680
|
{
|
|
6074
7681
|
if (!s_timers[i].active)
|
|
6075
7682
|
{
|
|
@@ -6098,7 +7705,7 @@ static void er_timer_clear(int id)
|
|
|
6098
7705
|
}
|
|
6099
7706
|
}
|
|
6100
7707
|
}`
|
|
6101
|
-
: `void er_app_tick(int dt_ms)\n{\n (void)dt_ms;\n}`;
|
|
7708
|
+
: `void er_app_tick(int dt_ms)\n{\n (void)dt_ms;\n${wallClockRefresh}}`;
|
|
6102
7709
|
|
|
6103
7710
|
const mountEffectsBlock = out.mountEffects.length
|
|
6104
7711
|
? '\n /* useEffect(fn, []) — run once on mount. */\n' +
|
|
@@ -6147,10 +7754,11 @@ static int16_t app_round_dim(double v)
|
|
|
6147
7754
|
`
|
|
6148
7755
|
: '';
|
|
6149
7756
|
|
|
6150
|
-
// <math.h> when any libm symbol appears (Svg arc trig, or Math.* in expressions/handlers/timer callbacks)
|
|
7757
|
+
// <math.h> when any libm symbol appears (Svg arc trig, or Math.* in expressions/handlers/timer callbacks), or
|
|
7758
|
+
// a call to a helper whose body uses one.
|
|
6151
7759
|
const usesMath =
|
|
6152
7760
|
out.needsMath ||
|
|
6153
|
-
/\b(sinf|cosf|tanf|sqrtf|fabsf|roundf|floorf|ceilf|fminf|fmaxf|atan2f|powf|M_PI)\b/.test(
|
|
7761
|
+
/\b(sinf|cosf|tanf|sqrtf|fabsf|roundf|floorf|ceilf|fminf|fmaxf|atan2f|powf|fmodf|isfinite|app_roundf|app_ftoa|app_vector_dirty|M_PI)\b/.test(
|
|
6154
7762
|
[
|
|
6155
7763
|
stateBlock,
|
|
6156
7764
|
refDecls,
|
|
@@ -6168,19 +7776,322 @@ static int16_t app_round_dim(double v)
|
|
|
6168
7776
|
// dependent nodes via app_update() (which the host also gets for free — it is the same refresh a JS
|
|
6169
7777
|
// setter would trigger). The host calls e.g. er_app_set_steps(count) once per frame.
|
|
6170
7778
|
const hostRecords = scalarRecords.filter(s => s.host);
|
|
7779
|
+
if (hostRecords.some(s => s.name === 'wall_clock'))
|
|
7780
|
+
throw aotError(
|
|
7781
|
+
'AOT: useHostValue("wall_clock") would collide with er_app_set_wall_clock()',
|
|
7782
|
+
'rename the host value — every app exports er_app_set_wall_clock() for Date.now().',
|
|
7783
|
+
);
|
|
6171
7784
|
const hostSettersBlock = hostRecords
|
|
6172
7785
|
.map(
|
|
6173
7786
|
s =>
|
|
6174
|
-
`void er_app_set_${s.name}(${s.cType
|
|
7787
|
+
`void er_app_set_${s.name}(${cScalarType(s.cType)} v)\n{\n ${s.cMember} = v;\n${hasUpdate ? ' app_update();\n' : ''}}`,
|
|
6175
7788
|
)
|
|
6176
7789
|
.join('\n\n');
|
|
6177
7790
|
const hostSetterProtos = hostRecords
|
|
6178
7791
|
.map(
|
|
6179
7792
|
s =>
|
|
6180
|
-
`/** @brief Host-fed input '${s.name}' (useHostValue): set its value and refresh the display. */\nvoid er_app_set_${s.name}(${s.cType
|
|
7793
|
+
`/** @brief Host-fed input '${s.name}' (useHostValue): set its value and refresh the display. */\nvoid er_app_set_${s.name}(${cScalarType(s.cType)} v);`,
|
|
6181
7794
|
)
|
|
6182
7795
|
.join('\n\n');
|
|
6183
7796
|
|
|
7797
|
+
// Date.now() / performance.now() read the engine clock as 64-bit whole milliseconds. The offset and its
|
|
7798
|
+
// setter are always emitted, so a host can set the time whether or not the app reads it; the readers, the
|
|
7799
|
+
// checked whole-number math and the 64-bit Math helpers only when something calls them.
|
|
7800
|
+
const APP_HELPERS = [
|
|
7801
|
+
[
|
|
7802
|
+
'app_perf_now',
|
|
7803
|
+
'static int64_t app_perf_now(void)\n{\n return (int64_t)er_now_ms64();\n}',
|
|
7804
|
+
],
|
|
7805
|
+
[
|
|
7806
|
+
'app_date_now',
|
|
7807
|
+
'static int64_t app_date_now(void)\n{\n return s_wall_offset_ms + (int64_t)er_now_ms64();\n}',
|
|
7808
|
+
],
|
|
7809
|
+
...Object.entries(CHECKED_OP).map(([op, name]) => [
|
|
7810
|
+
name,
|
|
7811
|
+
`/* a ${op} b, saturated to the int range: C leaves a signed overflow undefined. */\n` +
|
|
7812
|
+
`static int ${name}(int a, int b)\n{\n const int64_t v = (int64_t)a ${op} b;\n` +
|
|
7813
|
+
' return v > INT_MAX ? INT_MAX : v < INT_MIN ? INT_MIN : (int)v;\n}',
|
|
7814
|
+
]),
|
|
7815
|
+
[
|
|
7816
|
+
'app_neg',
|
|
7817
|
+
'/* -a, saturated: -INT_MIN does not fit an int. */\n' +
|
|
7818
|
+
'static int app_neg(int a)\n{\n return a == INT_MIN ? INT_MAX : -a;\n}',
|
|
7819
|
+
],
|
|
7820
|
+
[
|
|
7821
|
+
'app_mod',
|
|
7822
|
+
"/* a % b as JS computes it, kept whole: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
|
|
7823
|
+
' for b == 0, which is 0 here, and INT_MIN % -1 is 0, where C would overflow. */\n' +
|
|
7824
|
+
'static int app_mod(int a, int b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
|
|
7825
|
+
],
|
|
7826
|
+
[
|
|
7827
|
+
'app_abs',
|
|
7828
|
+
'/* Math.abs of an int, saturated: -INT_MIN does not fit an int. */\n' +
|
|
7829
|
+
'static int app_abs(int v)\n{\n return v >= 0 ? v : v == INT_MIN ? INT_MAX : -v;\n}',
|
|
7830
|
+
],
|
|
7831
|
+
[
|
|
7832
|
+
'app_min',
|
|
7833
|
+
'static int app_min(int a, int b)\n{\n return a < b ? a : b;\n}',
|
|
7834
|
+
],
|
|
7835
|
+
[
|
|
7836
|
+
'app_max',
|
|
7837
|
+
'static int app_max(int a, int b)\n{\n return a > b ? a : b;\n}',
|
|
7838
|
+
],
|
|
7839
|
+
[
|
|
7840
|
+
'app_div',
|
|
7841
|
+
'/* a / b as JS computes it, kept whole: truncated toward zero, and saturated where JS gives +-Infinity\n' +
|
|
7842
|
+
' (b == 0) or a result past the int range (INT_MIN / -1). 0 / 0 is NaN, which is 0. */\n' +
|
|
7843
|
+
'static int app_div(int a, int b)\n{\n' +
|
|
7844
|
+
' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
|
|
7845
|
+
' if (b == -1)\n {\n return a == INT_MIN ? INT_MAX : -a;\n }\n' +
|
|
7846
|
+
' return a / b;\n}',
|
|
7847
|
+
],
|
|
7848
|
+
[
|
|
7849
|
+
'app_floordiv',
|
|
7850
|
+
"/* Math.floor(a / b) for two ints, exactly: C's `/` rounds toward zero where floor rounds down, and a float\n" +
|
|
7851
|
+
' quotient would round an operand past 2^24. JS gives +-Infinity for b == 0, which saturates by the sign\n' +
|
|
7852
|
+
' of a (0 / 0 is NaN, which is 0); INT_MIN / -1 saturates too, so the quotient is taken in 64 bits. */\n' +
|
|
7853
|
+
'static int app_floordiv(int a, int b)\n{\n' +
|
|
7854
|
+
' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
|
|
7855
|
+
' const int64_t q = (int64_t)a / b;\n' +
|
|
7856
|
+
' const int64_t f = ((int64_t)a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n' +
|
|
7857
|
+
' return f > INT_MAX ? INT_MAX : (int)f;\n}',
|
|
7858
|
+
],
|
|
7859
|
+
[
|
|
7860
|
+
'app_ceildiv',
|
|
7861
|
+
'/* Math.ceil(a / b) for two ints, exactly, with the zero divisor and INT_MIN / -1 as app_floordiv has them. */\n' +
|
|
7862
|
+
'static int app_ceildiv(int a, int b)\n{\n' +
|
|
7863
|
+
' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
|
|
7864
|
+
' const int64_t q = (int64_t)a / b;\n' +
|
|
7865
|
+
' const int64_t c = ((int64_t)a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n' +
|
|
7866
|
+
' return c > INT_MAX ? INT_MAX : (int)c;\n}',
|
|
7867
|
+
],
|
|
7868
|
+
[
|
|
7869
|
+
'app_rounddiv',
|
|
7870
|
+
'/* Math.round(a / b) for two ints, exactly: floor(a / b + 1/2), halves up as JS rounds, which is\n' +
|
|
7871
|
+
' floor((2a + b) / 2b) once b is made positive. The zero divisor and the range go as in app_floordiv. */\n' +
|
|
7872
|
+
'static int app_rounddiv(int a, int b)\n{\n' +
|
|
7873
|
+
' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
|
|
7874
|
+
' const int64_t n = b < 0 ? -(int64_t)a : a;\n' +
|
|
7875
|
+
' const int64_t d = b < 0 ? -(int64_t)b : b;\n' +
|
|
7876
|
+
' const int64_t num = 2 * n + d, den = 2 * d;\n' +
|
|
7877
|
+
' const int64_t q = num / den;\n' +
|
|
7878
|
+
' const int64_t r = (num % den != 0 && num < 0) ? q - 1 : q;\n' +
|
|
7879
|
+
' return r > INT_MAX ? INT_MAX : r < INT_MIN ? INT_MIN : (int)r;\n}',
|
|
7880
|
+
],
|
|
7881
|
+
[
|
|
7882
|
+
'app_f2i',
|
|
7883
|
+
'/* A float kept as an int: truncated toward zero like a C cast, but saturated at the int range and NaN as\n' +
|
|
7884
|
+
' 0, where the cast would be undefined behavior. */\n' +
|
|
7885
|
+
'static int app_f2i(float v)\n{\n' +
|
|
7886
|
+
' if (v != v)\n {\n return 0;\n }\n' +
|
|
7887
|
+
' if (v >= 2147483648.0f)\n {\n return INT_MAX;\n }\n' +
|
|
7888
|
+
' if (v <= -2147483648.0f)\n {\n return INT_MIN;\n }\n' +
|
|
7889
|
+
' return (int)v;\n}',
|
|
7890
|
+
],
|
|
7891
|
+
[
|
|
7892
|
+
'app_roundf',
|
|
7893
|
+
"/* Math.round as JS rounds: to the nearest whole number, halves up (toward +Infinity). C's roundf takes\n" +
|
|
7894
|
+
' halves away from zero, which gives -3 for -2.5 where JS gives -2. */\n' +
|
|
7895
|
+
'static float app_roundf(float v)\n{\n' +
|
|
7896
|
+
' const float f = floorf(v);\n return v - f >= 0.5f ? f + 1.0f : f;\n}',
|
|
7897
|
+
],
|
|
7898
|
+
[
|
|
7899
|
+
'app_ftoa',
|
|
7900
|
+
"/* A float as JS's String() spells it where %g does not: Infinity, -Infinity and NaN for what %g prints as\n" +
|
|
7901
|
+
' inf, -inf and nan, and 0 for negative zero, which %g prints as -0. Anything else is %g, into `buf`,\n' +
|
|
7902
|
+
' which the caller lends (16 chars, room for any float). All ASCII, which every font bakes. */\n' +
|
|
7903
|
+
'static const char* app_ftoa(char* buf, float v)\n{\n' +
|
|
7904
|
+
' if (v != v)\n {\n return "NaN";\n }\n' +
|
|
7905
|
+
' if (isinf(v))\n {\n return v > 0.0f ? "Infinity" : "-Infinity";\n }\n' +
|
|
7906
|
+
' if (v == 0.0f)\n {\n return "0";\n }\n' +
|
|
7907
|
+
' snprintf(buf, 16, "%g", (double)v);\n return buf;\n}',
|
|
7908
|
+
],
|
|
7909
|
+
[
|
|
7910
|
+
'app_opacity',
|
|
7911
|
+
"/* A state-driven opacity as the engine's 0-255 byte: clamped to 0..1 and rounded, as Flow A's bridge and\n" +
|
|
7912
|
+
' the compile-time fold do, with NaN as 0. */\n' +
|
|
7913
|
+
'static uint8_t app_opacity(float v)\n{\n' +
|
|
7914
|
+
' if (!(v > 0.0f))\n {\n return 0;\n }\n' +
|
|
7915
|
+
' if (v >= 1.0f)\n {\n return 255;\n }\n' +
|
|
7916
|
+
' return (uint8_t)(v * 255.0f + 0.5f);\n}',
|
|
7917
|
+
],
|
|
7918
|
+
[
|
|
7919
|
+
'app_add64',
|
|
7920
|
+
'/* a + b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
|
|
7921
|
+
'static int64_t app_add64(int64_t a, int64_t b)\n{\n' +
|
|
7922
|
+
' if (b > 0 ? a > INT64_MAX - b : a < INT64_MIN - b)\n {\n' +
|
|
7923
|
+
' return b > 0 ? INT64_MAX : INT64_MIN;\n }\n return a + b;\n}',
|
|
7924
|
+
],
|
|
7925
|
+
[
|
|
7926
|
+
'app_sub64',
|
|
7927
|
+
'/* a - b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
|
|
7928
|
+
'static int64_t app_sub64(int64_t a, int64_t b)\n{\n' +
|
|
7929
|
+
' if (b < 0 ? a > INT64_MAX + b : a < INT64_MIN + b)\n {\n' +
|
|
7930
|
+
' return b < 0 ? INT64_MAX : INT64_MIN;\n }\n return a - b;\n}',
|
|
7931
|
+
],
|
|
7932
|
+
[
|
|
7933
|
+
'app_mul64',
|
|
7934
|
+
'/* a * b, saturated to the int64 range: C leaves a signed overflow undefined. GCC and Clang test for\n' +
|
|
7935
|
+
' the overflow with a builtin; anywhere else (MSVC) the limits are checked by division first. */\n' +
|
|
7936
|
+
'static int64_t app_mul64(int64_t a, int64_t b)\n{\n' +
|
|
7937
|
+
'#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ >= 5)\n' +
|
|
7938
|
+
' int64_t v;\n if (!__builtin_mul_overflow(a, b, &v))\n {\n return v;\n }\n' +
|
|
7939
|
+
'#else\n' +
|
|
7940
|
+
' if (a == 0 || b == 0 ||\n' +
|
|
7941
|
+
' (a > 0 ? (b > 0 ? a <= INT64_MAX / b : b >= INT64_MIN / a)\n' +
|
|
7942
|
+
' : (b > 0 ? a >= INT64_MIN / b : a >= INT64_MAX / b)))\n {\n' +
|
|
7943
|
+
' return a * b;\n }\n' +
|
|
7944
|
+
'#endif\n' +
|
|
7945
|
+
' return (a < 0) == (b < 0) ? INT64_MAX : INT64_MIN;\n}',
|
|
7946
|
+
],
|
|
7947
|
+
[
|
|
7948
|
+
'app_neg64',
|
|
7949
|
+
'/* -a, saturated: -INT64_MIN does not fit an int64_t. */\n' +
|
|
7950
|
+
'static int64_t app_neg64(int64_t a)\n{\n return a == INT64_MIN ? INT64_MAX : -a;\n}',
|
|
7951
|
+
],
|
|
7952
|
+
[
|
|
7953
|
+
'app_floordiv64',
|
|
7954
|
+
"/* Math.floor(a / b) in whole numbers: C's `/` rounds toward zero where floor rounds down. JS gives\n" +
|
|
7955
|
+
' +-Infinity for b == 0, which saturates by the sign of a (0 / 0 is NaN, which is 0), and INT64_MIN / -1\n' +
|
|
7956
|
+
' is past the range, so it saturates too. */\n' +
|
|
7957
|
+
'static int64_t app_floordiv64(int64_t a, int64_t b)\n{\n' +
|
|
7958
|
+
' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
|
|
7959
|
+
' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
|
|
7960
|
+
' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n}',
|
|
7961
|
+
],
|
|
7962
|
+
[
|
|
7963
|
+
'app_ceildiv64',
|
|
7964
|
+
'/* Math.ceil(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as app_floordiv64 has them. */\n' +
|
|
7965
|
+
'static int64_t app_ceildiv64(int64_t a, int64_t b)\n{\n' +
|
|
7966
|
+
' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
|
|
7967
|
+
' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
|
|
7968
|
+
' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n}',
|
|
7969
|
+
],
|
|
7970
|
+
[
|
|
7971
|
+
'app_rounddiv64',
|
|
7972
|
+
'/* Math.round(a / b) in whole numbers, halves up as JS rounds: floor(a / b), plus one when what is left is at\n' +
|
|
7973
|
+
' least half of b. Nothing is doubled, which could overflow; the zero divisor and INT64_MIN / -1 go as in\n' +
|
|
7974
|
+
' app_floordiv64. */\n' +
|
|
7975
|
+
'static int64_t app_rounddiv64(int64_t a, int64_t b)\n{\n' +
|
|
7976
|
+
' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
|
|
7977
|
+
' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
|
|
7978
|
+
' int64_t q = a / b;\n int64_t r = a % b;\n' +
|
|
7979
|
+
' if (r != 0 && (r < 0) != (b < 0))\n {\n q -= 1;\n r += b;\n }\n' +
|
|
7980
|
+
' return (b > 0 ? r >= b - r : r <= b - r) ? q + 1 : q;\n}',
|
|
7981
|
+
],
|
|
7982
|
+
[
|
|
7983
|
+
'app_div64',
|
|
7984
|
+
'/* Math.trunc(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as app_floordiv64 has them. */\n' +
|
|
7985
|
+
'static int64_t app_div64(int64_t a, int64_t b)\n{\n' +
|
|
7986
|
+
' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
|
|
7987
|
+
' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
|
|
7988
|
+
' return a / b;\n}',
|
|
7989
|
+
],
|
|
7990
|
+
[
|
|
7991
|
+
'app_mod64',
|
|
7992
|
+
"/* a % b in whole numbers, as JS computes it: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
|
|
7993
|
+
' for b == 0, which is 0 here, and INT64_MIN % -1 is 0, where C would overflow. */\n' +
|
|
7994
|
+
'static int64_t app_mod64(int64_t a, int64_t b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
|
|
7995
|
+
],
|
|
7996
|
+
[
|
|
7997
|
+
'app_abs64',
|
|
7998
|
+
'/* |v|, saturated: -INT64_MIN does not fit an int64_t. */\n' +
|
|
7999
|
+
'static int64_t app_abs64(int64_t v)\n{\n return v >= 0 ? v : v == INT64_MIN ? INT64_MAX : -v;\n}',
|
|
8000
|
+
],
|
|
8001
|
+
[
|
|
8002
|
+
'app_min64',
|
|
8003
|
+
'static int64_t app_min64(int64_t a, int64_t b)\n{\n return a < b ? a : b;\n}',
|
|
8004
|
+
],
|
|
8005
|
+
[
|
|
8006
|
+
'app_max64',
|
|
8007
|
+
'static int64_t app_max64(int64_t a, int64_t b)\n{\n return a > b ? a : b;\n}',
|
|
8008
|
+
],
|
|
8009
|
+
[
|
|
8010
|
+
'app_delay_ms64',
|
|
8011
|
+
'/* A timer delay computed from a timestamp: ToInt32 (wrap to 32 bits), then a negative delay is 0 — the\n' +
|
|
8012
|
+
" conversion Flow A's setTimeout applies. */\n" +
|
|
8013
|
+
'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}',
|
|
8014
|
+
],
|
|
8015
|
+
[
|
|
8016
|
+
'app_delay_msf',
|
|
8017
|
+
'/* A timer delay computed as a float, converted as app_delay_ms64 converts one: ToInt32 (NaN and +-Infinity\n' +
|
|
8018
|
+
' 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' +
|
|
8019
|
+
'static int app_delay_msf(float v)\n{\n' +
|
|
8020
|
+
' if (!(v > -9223372036854775808.0f && v < 9223372036854775808.0f))\n {\n return 0;\n }\n' +
|
|
8021
|
+
' const uint32_t u = (uint32_t)(int64_t)v;\n return u > 0x7FFFFFFFu ? 0 : (int)u;\n}',
|
|
8022
|
+
],
|
|
8023
|
+
[
|
|
8024
|
+
'app_slice_len',
|
|
8025
|
+
'/* The length items.slice(0, end) leaves, as JS counts it: a negative end counts back from the length and\n' +
|
|
8026
|
+
' stops at 0, and an end past the length keeps every item. */\n' +
|
|
8027
|
+
'static int app_slice_len(int len, int end)\n{\n' +
|
|
8028
|
+
' if (end < 0)\n {\n return end <= -len ? 0 : len + end;\n }\n' +
|
|
8029
|
+
' return end < len ? end : len;\n}',
|
|
8030
|
+
],
|
|
8031
|
+
[
|
|
8032
|
+
'app_vector_dirty',
|
|
8033
|
+
"/* updateVector's damage hint from float math. A NaN or infinite edge (a 0/0 in app math) gives no hint,\n" +
|
|
8034
|
+
" so the engine's own damage applies (what changed in the tape, or the whole node), where a zero-width\n" +
|
|
8035
|
+
' one would leave the new drawing unpainted. The rest is rounded out to whole pixels and its edges, not\n' +
|
|
8036
|
+
' its lengths, are bounded well inside the int range, so a rect reaching past the bound is not cut\n' +
|
|
8037
|
+
" short; the engine clips the rect's corners from there. */\n" +
|
|
8038
|
+
'static void app_vector_dirty(ERNode* node, float x, float y, float w, float h)\n{\n' +
|
|
8039
|
+
' if (!(isfinite(x) && isfinite(y) && isfinite(w) && isfinite(h)))\n {\n return;\n }\n' +
|
|
8040
|
+
' const float e[4] = {floorf(x), floorf(y), ceilf(x + w), ceilf(y + h)};\n int c[4];\n' +
|
|
8041
|
+
' for (int k = 0; k < 4; k++)\n {\n' +
|
|
8042
|
+
' c[k] = (int)(e[k] < -1e9f ? -1e9f : (e[k] > 1e9f ? 1e9f : e[k]));\n }\n' +
|
|
8043
|
+
' er_node_set_vector_dirty_rect(node, c[0], c[1], c[2] - c[0], c[3] - c[1]);\n}',
|
|
8044
|
+
],
|
|
8045
|
+
];
|
|
8046
|
+
// The generated code that can call a file-local helper, with literals and comments blanked so a
|
|
8047
|
+
// `<Text>app_date_now(</Text>` is not a call. Each static helper is emitted only when this calls it, since
|
|
8048
|
+
// an unused static function warns under -Wall.
|
|
8049
|
+
const helperCallers = stripCLiterals(
|
|
8050
|
+
[
|
|
8051
|
+
stateBlock,
|
|
8052
|
+
refDecls,
|
|
8053
|
+
vectorBuilderBlock,
|
|
8054
|
+
updateBlock,
|
|
8055
|
+
handlerDefs,
|
|
8056
|
+
queryDefs,
|
|
8057
|
+
effectFnDefs,
|
|
8058
|
+
animCbDefs,
|
|
8059
|
+
timerFnDefs,
|
|
8060
|
+
out.mountEffects.join('\n'),
|
|
8061
|
+
out.build.join('\n'),
|
|
8062
|
+
].join('\n'),
|
|
8063
|
+
);
|
|
8064
|
+
const clockBlock = [
|
|
8065
|
+
'/* Date.now() is the engine clock plus this offset, so it reads as uptime until the host calls\n' +
|
|
8066
|
+
' er_app_set_wall_clock(). performance.now() is the engine clock alone. */\n' +
|
|
8067
|
+
'static int64_t s_wall_offset_ms;' +
|
|
8068
|
+
(hasUpdate
|
|
8069
|
+
? '\n/* Set by er_app_set_wall_clock(); the next er_app_tick() re-applies what reads the clock. */\n' +
|
|
8070
|
+
'static int s_wall_clock_changed;'
|
|
8071
|
+
: ''),
|
|
8072
|
+
...APP_HELPERS.filter(([name]) => helperCallers.includes(`${name}(`)).map(
|
|
8073
|
+
([, def]) => def,
|
|
8074
|
+
),
|
|
8075
|
+
].join('\n\n');
|
|
8076
|
+
const usesLimits = /\bINT_M(?:AX|IN)\b/.test(clockBlock);
|
|
8077
|
+
// A mount effect's cleanup is dropped (the app never unmounts), so an app whose only clearInterval lives
|
|
8078
|
+
// there calls er_timer_clear from nowhere.
|
|
8079
|
+
const timerClearBlock =
|
|
8080
|
+
out.usesTimers && helperCallers.includes('er_timer_clear(')
|
|
8081
|
+
? `static void er_timer_clear(int id)
|
|
8082
|
+
{
|
|
8083
|
+
if (id < 0)
|
|
8084
|
+
{
|
|
8085
|
+
return;
|
|
8086
|
+
}
|
|
8087
|
+
int i = id % ER_AOT_MAX_TIMERS;
|
|
8088
|
+
if (s_timers[i].active && s_timers[i].gen == id / ER_AOT_MAX_TIMERS)
|
|
8089
|
+
{
|
|
8090
|
+
s_timers[i].active = false;
|
|
8091
|
+
}
|
|
8092
|
+
}`
|
|
8093
|
+
: '';
|
|
8094
|
+
|
|
6184
8095
|
const body = `/*
|
|
6185
8096
|
* Generated by the embedded-react Flow B AOT compiler (npm run aot -- ${demo}). DO NOT EDIT.
|
|
6186
8097
|
* Builds the app's scene graph + state machine directly against er_scene.h — no QuickJS, no JS runtime.
|
|
@@ -6193,13 +8104,28 @@ static int16_t app_round_dim(double v)
|
|
|
6193
8104
|
#include <stdio.h>
|
|
6194
8105
|
#include <string.h>
|
|
6195
8106
|
|
|
8107
|
+
/* Every string this file writes goes into a FIXED-SIZE slot (a state buffer, ERProps.text), so an
|
|
8108
|
+
over-long value is truncated by design — the app cannot grow the buffer the way JS grows a string.
|
|
8109
|
+
GCC's -Wformat-truncation reports exactly that intent for any format combining %s with anything else,
|
|
8110
|
+
and ESP-IDF compiles with -Werror, so leaving it on would fail the build for ordinary text like
|
|
8111
|
+
{'n=' + name}. Clang does not implement the warning; the guard keeps its "unknown warning group"
|
|
8112
|
+
diagnostic from firing there. */
|
|
8113
|
+
#if defined(__GNUC__) && !defined(__clang__)
|
|
8114
|
+
#pragma GCC diagnostic ignored "-Wformat-truncation"
|
|
8115
|
+
#endif
|
|
8116
|
+
|
|
6196
8117
|
/* Version-pin: this file was generated by embedded-react ${PKG_VERSION}. The engine ships LOCKSTEP, so its
|
|
6197
8118
|
headers must be the same major.minor — otherwise these generated er_scene.h calls may not match the ABI.
|
|
6198
8119
|
A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
|
|
6199
8120
|
_Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
|
|
6200
8121
|
"embedded-react version mismatch: app.gen.c was generated by ${PKG_VERSION} but the engine header (er_version.h) is a different major.minor. Regenerate the app with 'npm run aot', or align the engine and npm versions.");
|
|
6201
|
-
${usesMath ? '#include <math.h>\n/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles under -std=c99 / MSVC. */\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n' : ''}${dimRoundBlock}${stateBlock ? '\n' + stateBlock : ''}${refDecls ? '\n' + refDecls + '\n' : ''}${panDeclBlock ? '\n' + panDeclBlock + '\n' : ''}${effectDeclsBlock ? '\n' + effectDeclsBlock + '\n' : ''}${vectorBlock ? '\n' + vectorBlock + '\n' : ''}${vectorBuilderBlock ? '\n' + vectorBuilderBlock + '\n' : ''}${animDecls ? '\n' + animDecls + '\n' : ''}${handleDecls ? '\n' + handleDecls + '\n' : ''}${timerTableBlock ? '\n' + timerTableBlock + '\n' : ''}${effectFwdDecls ? '\n' + effectFwdDecls + '\n' : ''}${updateBlock ? '\n' + updateBlock + '\n' : ''}${timerFnFwdDecls ? '\n' + timerFnFwdDecls + '\n' : ''}${animCbDecls ? '\n' + animCbDecls + '\n' : ''}${handlerDefs ? '\n' + handlerDefs + '\n' : ''}${queryDefs ? '\n' + queryDefs + '\n' : ''}${effectFnDefs ? '\n' + effectFnDefs + '\n' : ''}${animCbDefs ? '\n' + animCbDefs + '\n' : ''}${timerFnDefs ? '\n' + timerFnDefs + '\n' : ''}${out.kbdData ? '\n' + out.kbdData + '\n' : ''}
|
|
8122
|
+
${usesMath ? '#include <math.h>\n/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles under -std=c99 / MSVC. */\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n' : ''}${usesLimits ? '#include <limits.h>\n' : ''}${dimRoundBlock}\n${clockBlock}\n${stateBlock ? '\n' + stateBlock : ''}${refDecls ? '\n' + refDecls + '\n' : ''}${panDeclBlock ? '\n' + panDeclBlock + '\n' : ''}${effectDeclsBlock ? '\n' + effectDeclsBlock + '\n' : ''}${vectorBlock ? '\n' + vectorBlock + '\n' : ''}${vectorBuilderBlock ? '\n' + vectorBuilderBlock + '\n' : ''}${animDecls ? '\n' + animDecls + '\n' : ''}${handleDecls ? '\n' + handleDecls + '\n' : ''}${timerTableBlock ? '\n' + timerTableBlock + '\n' : ''}${timerClearBlock ? '\n' + timerClearBlock + '\n' : ''}${effectFwdDecls ? '\n' + effectFwdDecls + '\n' : ''}${updateBlock ? '\n' + updateBlock + '\n' : ''}${timerFnFwdDecls ? '\n' + timerFnFwdDecls + '\n' : ''}${animCbDecls ? '\n' + animCbDecls + '\n' : ''}${handlerDefs ? '\n' + handlerDefs + '\n' : ''}${queryDefs ? '\n' + queryDefs + '\n' : ''}${effectFnDefs ? '\n' + effectFnDefs + '\n' : ''}${animCbDefs ? '\n' + animCbDefs + '\n' : ''}${timerFnDefs ? '\n' + timerFnDefs + '\n' : ''}${out.kbdData ? '\n' + out.kbdData + '\n' : ''}
|
|
6202
8123
|
${appTickFn}
|
|
8124
|
+
|
|
8125
|
+
void er_app_set_wall_clock(int64_t epoch_ms)
|
|
8126
|
+
{
|
|
8127
|
+
s_wall_offset_ms = epoch_ms - (int64_t)er_now_ms64();${hasUpdate ? '\n s_wall_clock_changed = 1;' : ''}
|
|
8128
|
+
}
|
|
6203
8129
|
${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}
|
|
6204
8130
|
void er_app_build(int screen_w, int screen_h)
|
|
6205
8131
|
{
|
|
@@ -6223,12 +8149,41 @@ ${out.kbdSetup ? out.kbdSetup + ' /* app-supplied on-screen keyboard layout/appe
|
|
|
6223
8149
|
#ifndef ER_APP_GEN_H
|
|
6224
8150
|
#define ER_APP_GEN_H
|
|
6225
8151
|
|
|
8152
|
+
#include <stdint.h>
|
|
8153
|
+
|
|
8154
|
+
/*
|
|
8155
|
+
* What this file was generated FOR. er_app_build() takes the screen size at runtime, but a responsive app
|
|
8156
|
+
* folds its \`screen.width\`/\`screen.height\` branching at GENERATE time — so the layout in here is already
|
|
8157
|
+
* committed to these dimensions and no runtime argument can change it.
|
|
8158
|
+
*
|
|
8159
|
+
* Every board example consumes the same dist/app.gen.c, so generating for one board and then building
|
|
8160
|
+
* another produces firmware that compiles, links, boots, and lays out wrong. Boards \`_Static_assert\` these
|
|
8161
|
+
* against their own panel size to turn that into a compile error; see each board example's main.c.
|
|
8162
|
+
*
|
|
8163
|
+
* WHICH demo is recorded the same way, as a marker macro named ER_AOT_DEMO_<demo> with every character
|
|
8164
|
+
* outside [A-Za-z0-9] encoded as _<hex>_ (so \`watch-face\` defines ER_AOT_DEMO_watch_2d_face). The encoding
|
|
8165
|
+
* is one-to-one, so no two app names can ever share a marker. A board that
|
|
8166
|
+
* needs a particular demo's useHostValue setters guards on \`#ifndef\` of its own marker, which names the
|
|
8167
|
+
* mismatch instead of leaving a pile of implicit-declaration errors for those setters.
|
|
8168
|
+
*/
|
|
8169
|
+
#define ER_AOT_SCREEN_W ${screen.width}
|
|
8170
|
+
#define ER_AOT_SCREEN_H ${screen.height}
|
|
8171
|
+
#define ER_AOT_DEMO ${cstr(demo)}
|
|
8172
|
+
#define ${demoMarker(demo)} 1
|
|
8173
|
+
|
|
6226
8174
|
/** @brief Builds the AOT-compiled app's scene graph + state machine (call once after backend init). */
|
|
6227
8175
|
void er_app_build(int screen_w, int screen_h);
|
|
6228
8176
|
|
|
6229
8177
|
/** @brief Advances app timers (setInterval/setTimeout). Call once per frame with the elapsed ms; a no-op
|
|
6230
8178
|
* for apps that use no timers, so it is always safe to call. */
|
|
6231
8179
|
void er_app_tick(int dt_ms);
|
|
8180
|
+
|
|
8181
|
+
/** @brief Tells the app the current time, which Date.now() counts on from. Until it is called Date.now()
|
|
8182
|
+
* reads as uptime; a later call re-anchors it, the next er_app_tick() re-applies what reads the
|
|
8183
|
+
* clock, and performance.now() never moves with it. Call it from the loop that calls
|
|
8184
|
+
* er_app_tick(), before or after er_app_build(); safe whether or not the app reads the clock.
|
|
8185
|
+
* @param[in] epoch_ms Current time, in milliseconds since the Unix epoch. */
|
|
8186
|
+
void er_app_set_wall_clock(int64_t epoch_ms);
|
|
6232
8187
|
${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
|
|
6233
8188
|
#endif
|
|
6234
8189
|
`;
|
|
@@ -6250,11 +8205,37 @@ ${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
|
|
|
6250
8205
|
};
|
|
6251
8206
|
}
|
|
6252
8207
|
|
|
8208
|
+
/**
|
|
8209
|
+
* A state or ref slot is typed from its initial value, so `useState(0)` is an int until a setter stores
|
|
8210
|
+
* Date.now() in it. A compile reports such slots (env.found); this compiles again with them widened to
|
|
8211
|
+
* int64_t until none are new, so every read of a slot sees its final type.
|
|
8212
|
+
*/
|
|
8213
|
+
function compileWidened(src, demo, opts) {
|
|
8214
|
+
const wide = new Set();
|
|
8215
|
+
for (;;) {
|
|
8216
|
+
const found = new Set();
|
|
8217
|
+
let result;
|
|
8218
|
+
let error;
|
|
8219
|
+
try {
|
|
8220
|
+
result = compileSourceImpl(src, demo, opts, wide, found);
|
|
8221
|
+
} catch (e) {
|
|
8222
|
+
error = e;
|
|
8223
|
+
}
|
|
8224
|
+
const fresh = [...found].filter(key => !wide.has(key));
|
|
8225
|
+
// A failed pass that still had slots to widen may have failed on the narrow type, so retry it first.
|
|
8226
|
+
if (!fresh.length) {
|
|
8227
|
+
if (error) throw error;
|
|
8228
|
+
return result;
|
|
8229
|
+
}
|
|
8230
|
+
for (const key of fresh) wide.add(key);
|
|
8231
|
+
}
|
|
8232
|
+
}
|
|
8233
|
+
|
|
6253
8234
|
/** Public entry: compile JSX source → { c, h, ... }. On an AOT error, annotate it with file:line:col + a
|
|
6254
8235
|
* source code-frame (+ hint) so the failure points at the exact unsupported construct. */
|
|
6255
8236
|
export function compileSource(src, demo = 'app', opts = {}) {
|
|
6256
8237
|
try {
|
|
6257
|
-
return
|
|
8238
|
+
return compileWidened(src, demo, opts);
|
|
6258
8239
|
} catch (e) {
|
|
6259
8240
|
if (e && typeof e.message === 'string' && e.message.startsWith('AOT:')) {
|
|
6260
8241
|
throw formatAotError(e, src, opts.filename || `demos/${demo}/App.jsx`);
|
|
@@ -6273,12 +8254,12 @@ if (
|
|
|
6273
8254
|
) {
|
|
6274
8255
|
const demo = process.argv[2] || process.env.DEMO || 'thermostat';
|
|
6275
8256
|
const appPath = resolve(demosDir, demo, 'App.jsx');
|
|
8257
|
+
const avail = existsSync(demosDir)
|
|
8258
|
+
? readdirSync(demosDir, {withFileTypes: true})
|
|
8259
|
+
.filter(d => d.isDirectory())
|
|
8260
|
+
.map(d => d.name)
|
|
8261
|
+
: [];
|
|
6276
8262
|
if (!existsSync(appPath)) {
|
|
6277
|
-
const avail = existsSync(demosDir)
|
|
6278
|
-
? readdirSync(demosDir, {withFileTypes: true})
|
|
6279
|
-
.filter(d => d.isDirectory())
|
|
6280
|
-
.map(d => d.name)
|
|
6281
|
-
: [];
|
|
6282
8263
|
console.error(
|
|
6283
8264
|
`AOT: demo "${demo}" not found (expected ${appPath}). Available: ${avail.join(', ') || '(none)'}`,
|
|
6284
8265
|
);
|