embedded-react 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/aot/compile.mjs +173 -8272
  2. package/aot/compiler/animations.mjs +1001 -0
  3. package/aot/compiler/assemble.mjs +806 -0
  4. package/aot/compiler/c/animations.mjs +362 -0
  5. package/aot/compiler/c/expressions.mjs +215 -0
  6. package/aot/compiler/c/functions.mjs +268 -0
  7. package/aot/compiler/c/keyboard.mjs +96 -0
  8. package/aot/compiler/c/nodes.mjs +282 -0
  9. package/aot/compiler/c/pan-responder.mjs +136 -0
  10. package/aot/compiler/c/statements.mjs +242 -0
  11. package/aot/compiler/c/text.mjs +83 -0
  12. package/aot/compiler/c/vectors.mjs +381 -0
  13. package/aot/compiler/c-syntax.mjs +127 -0
  14. package/aot/compiler/check.mjs +165 -0
  15. package/aot/compiler/collect.mjs +743 -0
  16. package/aot/compiler/control-flow.mjs +683 -0
  17. package/aot/compiler/diagnostics.mjs +137 -0
  18. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  19. package/aot/compiler/elements/dial.mjs +343 -0
  20. package/aot/compiler/elements/flat-list.mjs +139 -0
  21. package/aot/compiler/elements/image.mjs +151 -0
  22. package/aot/compiler/elements/modal.mjs +158 -0
  23. package/aot/compiler/elements/props.mjs +474 -0
  24. package/aot/compiler/elements/switch.mjs +183 -0
  25. package/aot/compiler/elements/text-input.mjs +171 -0
  26. package/aot/compiler/expressions.mjs +1479 -0
  27. package/aot/compiler/handlers.mjs +1072 -0
  28. package/aot/compiler/ir/animations.mjs +16 -0
  29. package/aot/compiler/ir/app.mjs +16 -0
  30. package/aot/compiler/ir/expressions.mjs +16 -0
  31. package/aot/compiler/ir/functions.mjs +16 -0
  32. package/aot/compiler/ir/keyboard.mjs +16 -0
  33. package/aot/compiler/ir/nodes.mjs +83 -0
  34. package/aot/compiler/ir/pan-responder.mjs +16 -0
  35. package/aot/compiler/ir/source.mjs +16 -0
  36. package/aot/compiler/ir/statements.mjs +16 -0
  37. package/aot/compiler/ir/text.mjs +16 -0
  38. package/aot/compiler/ir/types.mjs +185 -0
  39. package/aot/compiler/ir/vectors.mjs +16 -0
  40. package/aot/compiler/keyboard.mjs +152 -0
  41. package/aot/compiler/lower.mjs +282 -0
  42. package/aot/compiler/nodes.mjs +683 -0
  43. package/aot/compiler/options.mjs +55 -0
  44. package/aot/compiler/out.mjs +94 -0
  45. package/aot/compiler/pan-responder.mjs +354 -0
  46. package/aot/compiler/parse.mjs +300 -0
  47. package/aot/compiler/static-eval.mjs +228 -0
  48. package/aot/compiler/style-text.mjs +648 -0
  49. package/aot/compiler/svg.mjs +1167 -0
  50. package/aot/compiler/types.mjs +16 -0
  51. package/aot/screenshot-smoke.mjs +95 -55
  52. package/aot/style-map.mjs +366 -304
  53. package/cli.mjs +5 -8
  54. package/package.json +14 -6
  55. package/sim/embedded-react.wasm +0 -0
  56. package/src/embedded-react/FlatList.js +4 -4
  57. package/src/props.js +1 -1
@@ -0,0 +1,1479 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { attemptLowering, checkNumber } from './check.mjs';
20
+ import { traverse } from '@babel/core';
21
+ import { aotError, locateError, withLoc } from './diagnostics.mjs';
22
+ import { evalStatic, foldScope } from './static-eval.mjs';
23
+ import { lowerGestureField } from './pan-responder.mjs';
24
+ import { toCExpr } from './c/expressions.mjs';
25
+ import { printText } from './c/text.mjs';
26
+ import { BOOL, FLOAT, INT, INT64_NUMBER, INT64_MATH, STRING, TIME, isBoolean, isConvertible64, isIntSlot, isTime, int64Join, int64Of, stateType, refType, slotOf, typeOfCExpr, typeOfSlot, } from './ir/types.mjs';
27
+ /*----------------------------------------------------------------------------------------------------------------------
28
+ - Constants
29
+ ---------------------------------------------------------------------------------------------------------------------*/
30
+ /** The binary operators lowered as arithmetic, and those lowered as comparisons. */
31
+ const ARITH = new Set(['+', '-', '*', '/', '%']);
32
+ const COMPARE = new Set(['<', '>', '<=', '>=', '==', '!=', '===', '!==']);
33
+ /**
34
+ * The C helper each whole-number operator lowers to. It saturates at the limit of its type, where C's own
35
+ * signed overflow is undefined behavior; the 64-bit variant appends `64`.
36
+ */
37
+ export const CHECKED_OP = {
38
+ '+': 'app_add',
39
+ '-': 'app_sub',
40
+ '*': 'app_mul',
41
+ };
42
+ /** The saturating helper each whole-number operator lowers to in the IR. */
43
+ const CHECKED_HELPER = {
44
+ '+': 'add',
45
+ '-': 'sub',
46
+ '*': 'mul',
47
+ };
48
+ /** The range of a C int. */
49
+ const INT_MIN = -(2 ** 31);
50
+ export const INT_MAX = 2 ** 31 - 1;
51
+ /** The Math functions that keep a whole number whole. */
52
+ const WHOLE_MATH = new Set([
53
+ 'floor',
54
+ 'ceil',
55
+ 'round',
56
+ 'trunc',
57
+ 'abs',
58
+ 'min',
59
+ 'max',
60
+ ]);
61
+ /** The helper that rounds `a / b` for two whole numbers the way each Math function does. */
62
+ const INT_ROUND_DIV = new Map([
63
+ ['floor', 'floordiv'],
64
+ ['ceil', 'ceildiv'],
65
+ ['round', 'rounddiv'],
66
+ ['trunc', 'div'],
67
+ ]);
68
+ /** The Math functions of one argument, and of two, that are worked out on floats. */
69
+ const FLOAT_MATH_UNARY = new Set([
70
+ 'sin',
71
+ 'cos',
72
+ 'tan',
73
+ 'sqrt',
74
+ 'abs',
75
+ 'round',
76
+ 'floor',
77
+ 'ceil',
78
+ ]);
79
+ const FLOAT_MATH_BINARY = new Set(['min', 'max', 'atan2', 'pow']);
80
+ /** While the typing pass infers slot widths: the slots it takes to hold 64 bits, and what each holds. */
81
+ let assumedWide = null;
82
+ /** The fields of an onLayout rect. */
83
+ const LAYOUT_FIELDS = new Set(['x', 'y', 'width', 'height']);
84
+ /*----------------------------------------------------------------------------------------------------------------------
85
+ - Implementation
86
+ ---------------------------------------------------------------------------------------------------------------------*/
87
+ // The modules that still build C from a lowered expression or text import asCond and formatArgs from here.
88
+ export { asCond } from './c/expressions.mjs';
89
+ export { formatArgs } from './c/text.mjs';
90
+ /**
91
+ * A 64-bit timestamp met a float, which would round it.
92
+ *
93
+ * @returns The error, for the caller to throw.
94
+ */
95
+ export const mix64Error = () => aotError('AOT: a 64-bit time value cannot be mixed with a float', 'Date.now() and performance.now() are whole milliseconds in a 64-bit integer, and a ' +
96
+ 'float would round them. Keep the arithmetic whole — e.g. Math.floor(ms / 1000), not ' +
97
+ 'ms * 0.001.');
98
+ /**
99
+ * A 64-bit timestamp met a boolean in `&&` / `||` / `?:`, where JS would hand back the boolean itself.
100
+ *
101
+ * @param what The construct, for the message.
102
+ *
103
+ * @returns The error, for the caller to throw.
104
+ */
105
+ const bool64Error = (what) => aotError(`AOT: ${what} cannot mix a boolean with a 64-bit time value`, 'JS would give back the boolean itself (and false renders as no text), which a 64-bit ' +
106
+ 'integer cannot hold. Use a number on both sides, e.g. `on ? Date.now() : 0`.');
107
+ /**
108
+ * Flow A's lite profile has Date.now() and no Date objects, and so does the AOT.
109
+ *
110
+ * @returns The error, for the caller to throw.
111
+ */
112
+ const dateObjectError = () => aotError('AOT: Date objects are not supported — only Date.now()', 'keep time as milliseconds from Date.now() and do the calendar math on the number.');
113
+ /**
114
+ * The `Date` / `performance` calls whose name is the app's own binding — a const, a param, an import —
115
+ * rather than the global, so they are not the engine clock. Babel's scopes decide, as JS would.
116
+ *
117
+ * @param ast The parsed app.
118
+ *
119
+ * @returns The shadowed calls.
120
+ */
121
+ export function findShadowedClockCalls(ast) {
122
+ const calls = new WeakSet();
123
+ traverse(ast, {
124
+ 'CallExpression|NewExpression'(path) {
125
+ const callee = path.node.callee;
126
+ const id = callee.type === 'MemberExpression' ? callee.object : callee;
127
+ if (id.type === 'Identifier' &&
128
+ (id.name === 'Date' || id.name === 'performance') &&
129
+ path.scope.getBinding(id.name)) {
130
+ calls.add(path.node);
131
+ }
132
+ },
133
+ });
134
+ return calls;
135
+ }
136
+ /**
137
+ * `node` as an integer compile-time constant, or null.
138
+ *
139
+ * @param node The expression.
140
+ * @param env The expression environment.
141
+ *
142
+ * @returns The integer, or null when the expression is not one.
143
+ */
144
+ export function staticInt(node, env) {
145
+ try {
146
+ const value = evalStatic(node, foldScope(env, env.consts ?? {}));
147
+ return Number.isInteger(value) ? value : null;
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ }
153
+ /**
154
+ * A compile-time number, typed. A whole number too big for an int is a 64-bit constant, so whole-number math
155
+ * keeps it exact; past 64 bits it is a float.
156
+ *
157
+ * @param value The number.
158
+ *
159
+ * @returns Its constant.
160
+ */
161
+ function numConst(value) {
162
+ if (!Number.isInteger(value) || value < -(2 ** 63) || value >= 2 ** 63) {
163
+ return { kind: 'number', value, type: FLOAT };
164
+ }
165
+ if (value < INT_MIN || value > INT_MAX) {
166
+ return { kind: 'number', value, type: INT64_NUMBER };
167
+ }
168
+ return { kind: 'number', value, type: INT };
169
+ }
170
+ /**
171
+ * A compile-time number as written. One that ends up a float (a fraction, or past 64 bits) is checked by the
172
+ * check pass, at the expression: a float holds no NaN or Infinity, a folded `0 / 0` say.
173
+ *
174
+ * @param value The number.
175
+ * @param loc Where it is.
176
+ *
177
+ * @returns Its source.
178
+ */
179
+ function numberSource(value, loc) {
180
+ if (numConst(value).type.kind === 'float') {
181
+ checkNumber(value);
182
+ }
183
+ return { kind: 'number', value, loc };
184
+ }
185
+ /**
186
+ * A compile-time string.
187
+ *
188
+ * @param value The string.
189
+ *
190
+ * @returns Its constant.
191
+ */
192
+ const stringConst = (value) => ({
193
+ kind: 'string',
194
+ value,
195
+ type: STRING,
196
+ });
197
+ /**
198
+ * A compile-time boolean, held in an int slot.
199
+ *
200
+ * @param value The boolean.
201
+ *
202
+ * @returns Its constant.
203
+ */
204
+ const boolConst = (value) => ({
205
+ kind: 'boolean',
206
+ value,
207
+ type: BOOL,
208
+ });
209
+ /**
210
+ * A read of a local, typed as the local is.
211
+ *
212
+ * @param local The local.
213
+ *
214
+ * @returns The read.
215
+ */
216
+ const localRead = (local) => ({
217
+ kind: 'local',
218
+ local,
219
+ type: typeOfCExpr(local),
220
+ });
221
+ /**
222
+ * Whole-number math JS would not cut to 32 bits: `+ - *`, negation, `%`, and the Math functions that keep a
223
+ * whole number whole. Beside a 64-bit value all of it is worked out in 64 bits, however deep it sits.
224
+ *
225
+ * @param node The expression.
226
+ *
227
+ * @returns Whether it is such math.
228
+ */
229
+ const keepsMath64Node = (node) => (node.type === 'BinaryExpression' &&
230
+ (Boolean(CHECKED_HELPER[node.operator]) || node.operator === '%')) ||
231
+ (node.type === 'UnaryExpression' && node.operator === '-') ||
232
+ (node.type === 'CallExpression' &&
233
+ node.callee.type === 'MemberExpression' &&
234
+ !node.callee.computed &&
235
+ node.callee.object.type === 'Identifier' &&
236
+ node.callee.object.name === 'Math' &&
237
+ WHOLE_MATH.has(node.callee.property.name));
238
+ /**
239
+ * keepsMath64Node, for a source expression.
240
+ *
241
+ * @param source The expression.
242
+ *
243
+ * @returns Whether it is whole-number math JS would not cut to 32 bits.
244
+ */
245
+ const keepsMath64 = (source) => (source.kind === 'binary' &&
246
+ (Boolean(CHECKED_HELPER[source.op]) || source.op === '%')) ||
247
+ (source.kind === 'unary' && source.op === '-') ||
248
+ (source.kind === 'math' && source.wholeMath);
249
+ /**
250
+ * A 64-bit value computed at runtime from a timestamp, as opposed to a 64-bit constant or whole-number math
251
+ * widened to 64 bits beside one.
252
+ *
253
+ * @param expr The lowered expression.
254
+ *
255
+ * @returns Whether it is a timestamp.
256
+ */
257
+ export const isTime64 = (expr) => isTime(expr.type);
258
+ /**
259
+ * Besides a float, a 64-bit number that is not a time converts, as in JS; only a timestamp refuses.
260
+ *
261
+ * @param operands The operands.
262
+ *
263
+ * @returns The operands, with any such number converted to float when one of them is a float.
264
+ */
265
+ const litPeers = (...operands) => operands.some(operand => operand.type.kind === 'float')
266
+ ? operands.map((operand) => isConvertible64(operand.type)
267
+ ? { kind: 'toFloat', operand, type: FLOAT }
268
+ : operand)
269
+ : operands;
270
+ /**
271
+ * The error for a divisor that is not a constant where a time's has to be one.
272
+ *
273
+ * @param loc Where the divisor is.
274
+ *
275
+ * @returns The error, for the caller to throw.
276
+ */
277
+ function nonConstantDivisorError(loc) {
278
+ const error = aotError('AOT: a 64-bit time value can only be divided by a constant', 'the divisor must be known at compile time — e.g. `ms % 1000`, `Math.floor(ms / ' +
279
+ '60000)`. For a divisor from state, reduce the timestamp first: `(ms % 86400000) / ' +
280
+ 'period`.');
281
+ if (loc) {
282
+ error.aotLoc = loc;
283
+ }
284
+ return error;
285
+ }
286
+ /**
287
+ * The divisor of a timestamp's `%` or Math.floor / ceil / round / trunc(a / b), which has to be a constant;
288
+ * for one from state, an app reduces the timestamp first. A constant 0 gives JS's answer as the int math
289
+ * converts it: a remainder of 0, or a quotient saturated by the dividend's sign.
290
+ *
291
+ * @param node The divisor.
292
+ * @param env The expression environment.
293
+ *
294
+ * @returns The divisor's value.
295
+ */
296
+ export function constDivisor(node, env) {
297
+ const divisor = staticInt(node, env);
298
+ if (divisor !== null)
299
+ return divisor;
300
+ throw nonConstantDivisorError(node.loc?.start);
301
+ }
302
+ /**
303
+ * The divisor a source expression records, which has to be a constant (see constDivisor).
304
+ *
305
+ * @param divisor The divisor.
306
+ *
307
+ * @returns Its value.
308
+ */
309
+ function sourceDivisor(divisor) {
310
+ if (divisor.constant !== null)
311
+ return divisor.constant;
312
+ throw nonConstantDivisorError(divisor.loc);
313
+ }
314
+ /**
315
+ * `+ - * %` with a 64-bit value on either side, kept whole. `+ - *` saturate at the int64 limits. With a
316
+ * timestamp in it, `%` takes a constant; whole-number math widened beside one takes any divisor, as the int
317
+ * `%` does. The result narrows back to int when the divisor or the dividend fits one, so `ms % 1000` is an
318
+ * ordinary number again. `/` is refused: JS would give a fraction, and the whole-number division is written
319
+ * Math.floor(a / b).
320
+ *
321
+ * @param source The binary expression.
322
+ * @param left Its typed left operand.
323
+ * @param right Its typed right operand.
324
+ *
325
+ * @returns The typed expression.
326
+ */
327
+ function typeArith64(source, left, right) {
328
+ if (left.type.kind === 'float' || right.type.kind === 'float') {
329
+ throw mix64Error();
330
+ }
331
+ if (source.op === '/') {
332
+ throw aotError('AOT: `/` on a 64-bit time value is not supported', 'JS division gives a fraction, which a 64-bit integer cannot hold. Use Math.floor(a / ' +
333
+ 'b) for whole units — e.g. Math.floor(ms / 1000) for seconds.');
334
+ }
335
+ // With no timestamp on either side, this is whole-number math widened to 64 bits.
336
+ const isWide = !isTime64(left) && !isTime64(right);
337
+ // `%`: zero/±1 divisors give 0, a timestamp needs a constant divisor, and the result narrows to int if it fits.
338
+ if (source.op === '%') {
339
+ const staticDivisor = source.divisor.constant;
340
+ // JS gives NaN for a zero divisor, which is 0 here, as the int `%` has it.
341
+ if (staticDivisor === 0)
342
+ return numConst(0);
343
+ if (isWide && staticDivisor === null) {
344
+ return {
345
+ kind: 'helper',
346
+ helper: 'mod',
347
+ bits: 64,
348
+ args: [left, right],
349
+ type: INT64_MATH,
350
+ };
351
+ }
352
+ const divisor = sourceDivisor(source.divisor);
353
+ // ±1 leaves no remainder, and INT64_MIN % -1 overflows in C.
354
+ if (divisor === 1 || divisor === -1)
355
+ return numConst(0);
356
+ if (Math.abs(divisor) <= 0x7fffffff || isIntSlot(left.type)) {
357
+ return { kind: 'narrowRemainder', left, right, type: INT };
358
+ }
359
+ return {
360
+ kind: 'arithmetic',
361
+ op: '%',
362
+ left,
363
+ right,
364
+ type: isWide ? INT64_MATH : TIME,
365
+ };
366
+ }
367
+ // `+ - *`: the saturating 64-bit helper.
368
+ return {
369
+ kind: 'helper',
370
+ helper: CHECKED_HELPER[source.op],
371
+ bits: 64,
372
+ args: [left, right],
373
+ type: isWide ? INT64_MATH : TIME,
374
+ };
375
+ }
376
+ /**
377
+ * Math.floor / ceil / round / trunc over `a / b` with a 64-bit timestamp on either side, as exact integer
378
+ * division by a constant (see constDivisor); a zero one saturates by the dividend's sign, as JS's ±Infinity
379
+ * converts. Null when neither side is a timestamp, which leaves it to the whole-number or float path.
380
+ *
381
+ * @param fn The Math function's name.
382
+ * @param division Its one argument, the division.
383
+ * @param math64 Whole-number math is worked out in 64 bits here.
384
+ *
385
+ * @returns The typed call, or null when it is not this case.
386
+ */
387
+ function typeTimeRoundDiv(fn, division, math64) {
388
+ const dividend = typeSource(division.left, math64);
389
+ const divisor = typeSource(division.right, math64);
390
+ if (!isTime64(dividend) && !isTime64(divisor))
391
+ return null;
392
+ if (dividend.type.kind === 'float' || divisor.type.kind === 'float') {
393
+ throw mix64Error();
394
+ }
395
+ if (dividend.type.kind === 'string' || divisor.type.kind === 'string')
396
+ return null;
397
+ // Dividing by -1 is a negation, which saturates; C's `/` would overflow on INT64_MIN / -1.
398
+ if (sourceDivisor(division.divisor) === -1) {
399
+ return {
400
+ kind: 'helper',
401
+ helper: 'neg',
402
+ bits: 64,
403
+ args: [dividend],
404
+ type: TIME,
405
+ };
406
+ }
407
+ return {
408
+ kind: 'helper',
409
+ helper: INT_ROUND_DIV.get(fn),
410
+ bits: 64,
411
+ args: [dividend, divisor],
412
+ type: TIME,
413
+ };
414
+ }
415
+ /**
416
+ * Math.floor / ceil / round / trunc over `a / b` with two whole numbers, as exact integer division: the float
417
+ * path rounds an operand past 2^24, so Math.floor(16777217 / 1) would come out 16777216. A zero divisor keeps
418
+ * JS's answer as app_f2i converts it (±Infinity saturates by the dividend's sign, 0 / 0 is 0), and
419
+ * INT_MIN / -1 saturates too. Beside a 64-bit value, or with a 64-bit operand that is not a timestamp (a
420
+ * constant past the int range, or math already widened), it divides in 64 bits, since JS would not cut the
421
+ * operands to 32. Null for anything else, which leaves it to the float path.
422
+ *
423
+ * @param fn The Math function's name.
424
+ * @param division Its one argument, the division.
425
+ * @param math64 Whole-number math is worked out in 64 bits here.
426
+ *
427
+ * @returns The typed call, or null when it is not this case.
428
+ */
429
+ function typeIntRoundDiv(fn, division, math64) {
430
+ // Divide in 64 bits beside a 64-bit value, when both operands are whole numbers and neither is a timestamp.
431
+ const dividend = typeSource(division.left, math64);
432
+ const divisor = typeSource(division.right, math64);
433
+ if (math64 ||
434
+ dividend.type.kind === 'int64' ||
435
+ divisor.type.kind === 'int64') {
436
+ const isWhole = (operand) => isIntSlot(operand.type) ||
437
+ (operand.type.kind === 'int64' && !isTime64(operand));
438
+ if (!isWhole(dividend) || !isWhole(divisor))
439
+ return null;
440
+ return {
441
+ kind: 'helper',
442
+ helper: INT_ROUND_DIV.get(fn),
443
+ bits: 64,
444
+ args: [dividend, divisor],
445
+ type: INT64_MATH,
446
+ };
447
+ }
448
+ // Otherwise divide two ints in 32 bits; anything else is left to the float path.
449
+ if (!isIntSlot(dividend.type) || !isIntSlot(divisor.type))
450
+ return null;
451
+ return {
452
+ kind: 'helper',
453
+ helper: INT_ROUND_DIV.get(fn),
454
+ bits: 32,
455
+ args: [dividend, divisor],
456
+ type: INT,
457
+ };
458
+ }
459
+ /**
460
+ * Math.* over a 64-bit timestamp: only what stays exact in whole numbers.
461
+ *
462
+ * @param fn The Math function's name.
463
+ * @param argExprs Its typed arguments, at least one of them 64-bit.
464
+ *
465
+ * @returns The typed call.
466
+ */
467
+ function typeMath64(fn, argExprs) {
468
+ if (argExprs.some(argExpr => argExpr.type.kind === 'float')) {
469
+ throw mix64Error();
470
+ }
471
+ if (argExprs.every(argExpr => isIntSlot(argExpr.type) || argExpr.type.kind === 'int64')) {
472
+ // Whole-number math with no timestamp in it stays whole-number math.
473
+ const isWide = !argExprs.some(isTime64);
474
+ // A timestamp is already whole, so rounding leaves it as it is.
475
+ if ((fn === 'floor' || fn === 'round' || fn === 'ceil' || fn === 'trunc') &&
476
+ argExprs.length === 1) {
477
+ return {
478
+ kind: 'wholeRound',
479
+ operand: argExprs[0],
480
+ type: isWide ? INT64_MATH : TIME,
481
+ };
482
+ }
483
+ if (fn === 'abs' && argExprs.length === 1) {
484
+ return {
485
+ kind: 'helper',
486
+ helper: 'abs',
487
+ bits: 64,
488
+ args: [argExprs[0]],
489
+ type: isWide ? INT64_MATH : TIME,
490
+ };
491
+ }
492
+ if ((fn === 'min' || fn === 'max') && argExprs.length === 2) {
493
+ return {
494
+ kind: 'helper',
495
+ helper: fn,
496
+ bits: 64,
497
+ args: [argExprs[0], argExprs[1]],
498
+ type: isWide ? INT64_MATH : TIME,
499
+ };
500
+ }
501
+ }
502
+ throw aotError(`AOT: Math.${fn}(...) on a 64-bit time value is not supported`, 'Math.floor / round / ceil / trunc / abs / min / max keep a timestamp exact; for ' +
503
+ 'anything else, reduce it to a small number first, e.g. `ms % 1000`.');
504
+ }
505
+ /**
506
+ * Types a unary expression: a whole number negates through the saturating helper, anything else as itself.
507
+ *
508
+ * @param source The expression.
509
+ * @param math64 Whole-number math is worked out in 64 bits here.
510
+ *
511
+ * @returns The typed expression.
512
+ */
513
+ function typeUnary(source, math64) {
514
+ const operand = typeSource(source.operand, math64);
515
+ if ((source.op === '-' || source.op === '+') &&
516
+ operand.type.kind === 'string') {
517
+ throw aotError(`AOT: unary "${source.op}" on a string is not supported`, 'JS would coerce the string to a number; C has no such coercion. Keep the operand numeric.');
518
+ }
519
+ // Negating the minimum overflows, so a whole number saturates the way `+ - *` do.
520
+ if (source.op === '-' &&
521
+ (isIntSlot(operand.type) || operand.type.kind === 'int64')) {
522
+ const is64Bit = operand.type.kind === 'int64' || math64;
523
+ return is64Bit
524
+ ? {
525
+ kind: 'helper',
526
+ helper: 'neg',
527
+ bits: 64,
528
+ args: [operand],
529
+ type: operand.type.kind === 'int64' ? operand.type : INT64_MATH,
530
+ }
531
+ : {
532
+ kind: 'helper',
533
+ helper: 'neg',
534
+ bits: 32,
535
+ args: [operand],
536
+ type: INT,
537
+ };
538
+ }
539
+ // Only `!` yields a boolean; unary +/- coerce to a number, so `+flag` drops its boolean-ness.
540
+ return {
541
+ kind: 'unary',
542
+ op: source.op,
543
+ operand,
544
+ type: source.op === '!' ? BOOL : isBoolean(operand.type) ? INT : operand.type,
545
+ };
546
+ }
547
+ /**
548
+ * Types a binary expression: arithmetic (whole numbers saturate, 64-bit beside a time, floats as floats) or a
549
+ * comparison. Beside a 64-bit value, whole-number math on either side is typed again in 64 bits, as JS never
550
+ * cuts it to 32.
551
+ *
552
+ * @param source The expression.
553
+ * @param math64 Whole-number math is worked out in 64 bits here.
554
+ *
555
+ * @returns The typed expression.
556
+ */
557
+ function typeBinary(source, math64) {
558
+ let left = typeSource(source.left, math64);
559
+ let right = typeSource(source.right, math64);
560
+ if (left.type.kind === 'int64' || right.type.kind === 'int64') {
561
+ if (isIntSlot(left.type) && keepsMath64(source.left)) {
562
+ left = typeSource(source.left, true);
563
+ }
564
+ if (isIntSlot(right.type) && keepsMath64(source.right)) {
565
+ right = typeSource(source.right, true);
566
+ }
567
+ }
568
+ [left, right] = litPeers(left, right);
569
+ // Arithmetic: refuse strings, hand 64-bit math to typeArith64, and saturate whole-number `+ - *`.
570
+ if (ARITH.has(source.op)) {
571
+ if (left.type.kind === 'string' || right.type.kind === 'string') {
572
+ // String `+` has no single C value; only a char-buffer destination can lower it, via emitFormat().
573
+ if (source.op === '+') {
574
+ throw aotError('AOT: string concatenation is not supported in this position', 'a `+` chain over strings lowers to a printf format, which only works where the value ' +
575
+ 'lands in a text buffer: a <Text> body, a string useState setter, or a <TextInput ' +
576
+ 'value>.');
577
+ }
578
+ // JS would coerce the string to a number; C would do pointer arithmetic or refuse to compile.
579
+ throw aotError(`AOT: "${source.op}" on a string is not supported`, 'keep both operands numeric — a string cannot be coerced to a number here.');
580
+ }
581
+ // `/` takes a 64-bit constant as an ordinary C number; only a runtime 64-bit value is refused it.
582
+ if (isTime64(left) ||
583
+ isTime64(right) ||
584
+ ((left.type.kind === 'int64' || right.type.kind === 'int64') &&
585
+ (CHECKED_HELPER[source.op] || source.op === '%'))) {
586
+ return typeArith64(source, left, right);
587
+ }
588
+ if (source.op === '/') {
589
+ return { kind: 'floatDivide', left, right, type: FLOAT };
590
+ }
591
+ const isFloat = left.type.kind === 'float' || right.type.kind === 'float';
592
+ const checkedHelper = !isFloat && CHECKED_HELPER[source.op];
593
+ if (checkedHelper) {
594
+ return math64
595
+ ? {
596
+ kind: 'helper',
597
+ helper: checkedHelper,
598
+ bits: 64,
599
+ args: [left, right],
600
+ type: INT64_MATH,
601
+ }
602
+ : {
603
+ kind: 'helper',
604
+ helper: checkedHelper,
605
+ bits: 32,
606
+ args: [left, right],
607
+ type: INT,
608
+ };
609
+ }
610
+ // A 0 divisor (NaN in JS) or -1 (INT_MIN % -1 overflows C) gives 0; other constants need no check.
611
+ if (!isFloat && source.op === '%') {
612
+ const staticDivisor = source.divisor.constant;
613
+ if (staticDivisor === 0 || staticDivisor === -1) {
614
+ return numConst(0);
615
+ }
616
+ if (staticDivisor === null) {
617
+ return {
618
+ kind: 'helper',
619
+ helper: 'mod',
620
+ bits: 32,
621
+ args: [left, right],
622
+ type: INT,
623
+ };
624
+ }
625
+ }
626
+ // C has no float `%`; fmodf matches JS's `%` exactly, zero and infinite divisors included.
627
+ if (isFloat && source.op === '%') {
628
+ return {
629
+ kind: 'floatMath',
630
+ fn: 'mod',
631
+ args: [left, right],
632
+ type: FLOAT,
633
+ };
634
+ }
635
+ return {
636
+ kind: 'arithmetic',
637
+ op: source.op,
638
+ left,
639
+ right,
640
+ type: isFloat ? FLOAT : INT,
641
+ };
642
+ }
643
+ // Comparisons: strings through strcmp, everything else as a plain C comparison yielding a boolean.
644
+ if (COMPARE.has(source.op)) {
645
+ const cOperator = source.op === '===' ? '==' : source.op === '!==' ? '!=' : source.op;
646
+ if (left.type.kind === 'string' || right.type.kind === 'string') {
647
+ if (slotOf(left.type) !== slotOf(right.type)) {
648
+ // A strict comparison never coerces, so a string against a number is decided statically.
649
+ if (source.op === '===' || source.op === '!==') {
650
+ return boolConst(source.op === '!==');
651
+ }
652
+ throw aotError('AOT: a string cannot be compared with a number', `\`${source.op}\` coerces the string to a number in JS, which C cannot reproduce. ` +
653
+ `Compare like with like, or use === / !== (which never coerce).`);
654
+ }
655
+ // Equality is exact, but strcmp's UTF-8 order can differ from JS's UTF-16 order, so refuse ordering.
656
+ if (cOperator !== '==' && cOperator !== '!=') {
657
+ throw aotError(`AOT: ordering strings with "${source.op}" is not supported`, 'JS orders strings by UTF-16 code unit but the device holds UTF-8, so the order can ' +
658
+ 'differ. Use === / !==, or compare numbers.');
659
+ }
660
+ return {
661
+ kind: 'stringEquals',
662
+ op: cOperator,
663
+ left,
664
+ right,
665
+ type: BOOL,
666
+ };
667
+ }
668
+ // A float compared with a timestamp would round it.
669
+ if ((left.type.kind === 'int64' || right.type.kind === 'int64') &&
670
+ (left.type.kind === 'float' || right.type.kind === 'float')) {
671
+ throw mix64Error();
672
+ }
673
+ // `true === 1` is false in JS but true in C's int slot; fold it when the other side is surely a number.
674
+ const isSurelyNumber = (isWrittenAsNumber, operand) => !isBoolean(operand.type) &&
675
+ (operand.type.kind === 'float' ||
676
+ operand.type.kind === 'int64' ||
677
+ isWrittenAsNumber);
678
+ if ((source.op === '===' || source.op === '!==') &&
679
+ ((isBoolean(left.type) && isSurelyNumber(source.rightIsNumber, right)) ||
680
+ (isBoolean(right.type) && isSurelyNumber(source.leftIsNumber, left)))) {
681
+ return boolConst(source.op === '!==');
682
+ }
683
+ return {
684
+ kind: 'compare',
685
+ op: cOperator,
686
+ left,
687
+ right,
688
+ type: BOOL,
689
+ };
690
+ }
691
+ throw new Error(`AOT: unsupported binary operator "${source.op}"`);
692
+ }
693
+ /**
694
+ * Types `&&` / `||`. JS returns an operand, so with a 64-bit side the value is kept instead of collapsing it
695
+ * to 0/1.
696
+ *
697
+ * @param source The expression.
698
+ * @param math64 Whole-number math is worked out in 64 bits here.
699
+ *
700
+ * @returns The typed expression.
701
+ */
702
+ function typeLogical(source, math64) {
703
+ const [left, right] = litPeers(typeSource(source.left, math64), typeSource(source.right, math64));
704
+ if (left.type.kind === 'int64' || right.type.kind === 'int64') {
705
+ if (left.type.kind === 'float' || right.type.kind === 'float') {
706
+ throw mix64Error();
707
+ }
708
+ if (left.type.kind === 'string' || right.type.kind === 'string') {
709
+ throw aotError(`AOT: "${source.op}" cannot mix a 64-bit time value with a string`, 'keep both sides numbers, or write the branch out: {ms ? ms : 0}.');
710
+ }
711
+ if (isBoolean(left.type) || isBoolean(right.type)) {
712
+ throw bool64Error(`"${source.op}"`);
713
+ }
714
+ return {
715
+ kind: 'pick',
716
+ op: source.op,
717
+ left,
718
+ right,
719
+ type: int64Join(left.type, right.type),
720
+ };
721
+ }
722
+ // Otherwise the C result is the truth of the expression, a boolean only when both operands are.
723
+ return {
724
+ kind: 'logical',
725
+ op: source.op,
726
+ left,
727
+ right,
728
+ type: isBoolean(left.type) && isBoolean(right.type) ? BOOL : INT,
729
+ };
730
+ }
731
+ /**
732
+ * Types `test ? consequent : alternate`. Both branches share one C slot: float or 64-bit if either is, and a
733
+ * 64-bit branch beside a float or a boolean one is refused.
734
+ *
735
+ * @param source The expression.
736
+ * @param math64 Whole-number math is worked out in 64 bits here.
737
+ *
738
+ * @returns The typed expression.
739
+ */
740
+ function typeConditional(source, math64) {
741
+ const test = typeSource(source.test, math64);
742
+ const [consequent, alternate] = litPeers(typeSource(source.consequent, math64), typeSource(source.alternate, math64));
743
+ // A string branch beside a numeric one is ill-typed C with no single printf spec, so refuse it here.
744
+ if ((consequent.type.kind === 'string') !==
745
+ (alternate.type.kind === 'string')) {
746
+ throw aotError('AOT: a ternary cannot mix a string branch with a numeric one', "both branches must be the same kind — quote the number to keep it text, e.g. {ok ? '1' : 'none'}.");
747
+ }
748
+ const eitherIs = (kind) => slotOf(consequent.type) === kind || slotOf(alternate.type) === kind;
749
+ if (eitherIs('i64') && eitherIs('float')) {
750
+ throw mix64Error();
751
+ }
752
+ if (eitherIs('i64') &&
753
+ (isBoolean(consequent.type) || isBoolean(alternate.type))) {
754
+ throw bool64Error('a ternary');
755
+ }
756
+ const slot = eitherIs('float')
757
+ ? 'float'
758
+ : eitherIs('i64')
759
+ ? 'i64'
760
+ : slotOf(consequent.type) === slotOf(alternate.type)
761
+ ? slotOf(consequent.type)
762
+ : 'int';
763
+ return {
764
+ kind: 'conditional',
765
+ test,
766
+ consequent,
767
+ alternate,
768
+ type: slot === 'i64'
769
+ ? int64Join(consequent.type, alternate.type)
770
+ : typeOfSlot(slot, isBoolean(consequent.type) && isBoolean(alternate.type)),
771
+ };
772
+ }
773
+ /**
774
+ * Types a Math call: exact integer division first, then 64-bit math, then whole-int abs/min/max/trunc, then
775
+ * floats.
776
+ *
777
+ * @param source The call.
778
+ * @param math64 Whole-number math is worked out in 64 bits here.
779
+ *
780
+ * @returns The typed call.
781
+ */
782
+ function typeMath(source, math64) {
783
+ const { fn } = source;
784
+ if (source.exactDivision) {
785
+ const division = source.args[0];
786
+ const timeDiv = typeTimeRoundDiv(fn, division, math64);
787
+ if (timeDiv)
788
+ return timeDiv;
789
+ const intDiv = typeIntRoundDiv(fn, division, math64);
790
+ if (intDiv)
791
+ return intDiv;
792
+ }
793
+ let argExprs = litPeers(...source.args.map(arg => typeSource(arg, math64)));
794
+ if (argExprs.some(argExpr => argExpr.type.kind === 'int64')) {
795
+ // Whole-number Math keeps a 64-bit value exact, and a time takes nothing else; the rest works on floats.
796
+ if (WHOLE_MATH.has(fn) || argExprs.some(isTime64)) {
797
+ return typeMath64(fn, argExprs);
798
+ }
799
+ argExprs = argExprs.map((argExpr) => argExpr.type.kind === 'int64'
800
+ ? { kind: 'toFloat', operand: argExpr, type: FLOAT }
801
+ : argExpr);
802
+ }
803
+ // Keep int abs/min/max whole (a float rounds past 2^24); with math64, abs widens to keep |INT_MIN|.
804
+ if (argExprs.length && argExprs.every(argExpr => isIntSlot(argExpr.type))) {
805
+ if (fn === 'abs' && argExprs.length === 1) {
806
+ return math64
807
+ ? {
808
+ kind: 'helper',
809
+ helper: 'abs',
810
+ bits: 64,
811
+ args: [argExprs[0]],
812
+ type: INT64_MATH,
813
+ }
814
+ : {
815
+ kind: 'helper',
816
+ helper: 'abs',
817
+ bits: 32,
818
+ args: [argExprs[0]],
819
+ type: INT,
820
+ };
821
+ }
822
+ if ((fn === 'min' || fn === 'max') && argExprs.length === 2) {
823
+ return {
824
+ kind: 'helper',
825
+ helper: fn,
826
+ bits: 32,
827
+ args: [argExprs[0], argExprs[1]],
828
+ type: INT,
829
+ };
830
+ }
831
+ }
832
+ // Math.trunc stays an int: an int as is, a float via app_f2i (toward zero, NaN as 0, saturating).
833
+ if (fn === 'trunc' && argExprs.length === 1) {
834
+ return isIntSlot(argExprs[0].type)
835
+ ? { kind: 'wholeRound', operand: argExprs[0], type: INT }
836
+ : { kind: 'trunc', operand: argExprs[0], type: INT };
837
+ }
838
+ if (FLOAT_MATH_UNARY.has(fn) && argExprs.length === 1) {
839
+ // An int is already whole, so rounding leaves it as it is; a float round trip would lose digits.
840
+ const roundsToWhole = fn === 'round' || fn === 'floor' || fn === 'ceil';
841
+ if (roundsToWhole && isIntSlot(argExprs[0].type)) {
842
+ return { kind: 'wholeRound', operand: argExprs[0], type: INT };
843
+ }
844
+ const floatCall = {
845
+ kind: 'floatMath',
846
+ fn: fn,
847
+ args: [argExprs[0]],
848
+ type: FLOAT,
849
+ };
850
+ // round/floor/ceil yield a whole number, kept as an int so %d / int assignments are correct.
851
+ return roundsToWhole
852
+ ? { kind: 'toInt', operand: floatCall, type: INT }
853
+ : floatCall;
854
+ }
855
+ if (FLOAT_MATH_BINARY.has(fn) && argExprs.length === 2) {
856
+ return {
857
+ kind: 'floatMath',
858
+ fn: fn,
859
+ args: [argExprs[0], argExprs[1]],
860
+ type: FLOAT,
861
+ };
862
+ }
863
+ throw new Error(`AOT: unsupported Math.${fn}(...) (arity ${argExprs.length})`);
864
+ }
865
+ /**
866
+ * The typing pass over one source expression: gives it its type and decides how it is computed. Pure, so a
867
+ * subexpression can be typed again, as whole-number math beside a 64-bit value is. An AOT error is pinned to
868
+ * the expression it is about, as lowering it would have been.
869
+ *
870
+ * @param source The expression.
871
+ * @param math64 Whole-number math is worked out in 64 bits around it.
872
+ *
873
+ * @returns The typed expression.
874
+ */
875
+ export function typeSource(source, math64) {
876
+ // 64-bit int math reaches only through whole-number math (keepsMath64); other expressions are typed as usual.
877
+ const wide = math64 && keepsMath64(source);
878
+ try {
879
+ switch (source.kind) {
880
+ case 'number':
881
+ return numConst(source.value);
882
+ case 'string':
883
+ return stringConst(source.value);
884
+ case 'boolean':
885
+ return boolConst(source.value);
886
+ case 'state': {
887
+ const { state } = source;
888
+ const assumed = (state.cType === 'int' || state.cType === 'i64') && !state.isBool
889
+ ? assumedWide?.get(state.cField)
890
+ : undefined;
891
+ return {
892
+ kind: 'state',
893
+ state,
894
+ type: assumed ? int64Of(assumed) : stateType(state),
895
+ };
896
+ }
897
+ case 'local':
898
+ // While slot widths are inferred, a local is what it was set from, typed with the slots assumed so far.
899
+ return assumedWide && source.local.source
900
+ ? typeSource(source.local.source, false)
901
+ : localRead(source.local);
902
+ case 'ref': {
903
+ const { ref } = source;
904
+ const assumed = ref.kind === 'value' && (ref.cType === 'int' || ref.cType === 'i64')
905
+ ? assumedWide?.get(ref.cVar)
906
+ : undefined;
907
+ return {
908
+ kind: 'ref',
909
+ ref,
910
+ type: assumed ? int64Of(assumed) : refType(ref),
911
+ };
912
+ }
913
+ case 'fixed':
914
+ return source.expr;
915
+ case 'unary':
916
+ return typeUnary(source, wide);
917
+ case 'binary':
918
+ return typeBinary(source, wide);
919
+ case 'logical':
920
+ return typeLogical(source, wide);
921
+ case 'conditional':
922
+ return typeConditional(source, wide);
923
+ case 'math':
924
+ return typeMath(source, wide);
925
+ }
926
+ }
927
+ catch (error) {
928
+ locateError(error, source.loc);
929
+ throw error;
930
+ }
931
+ }
932
+ /**
933
+ * Infers the slots that have to hold 64 bits: an int slot a value stored into is a 64-bit number, once the
934
+ * slots found so far are taken to hold 64 bits too, until no more are found. Each one holds a time when a time
935
+ * is stored into it, and only 64-bit numbers otherwise. A value whose typing fails leaves its slot as it is;
936
+ * lowering it again reports the error.
937
+ *
938
+ * @param stores Every value lowering stored into an int slot, or into a 64-bit one that holds no time yet.
939
+ * @param wide The slots already 64-bit.
940
+ *
941
+ * @returns Those slots, and every one inferred.
942
+ */
943
+ export function inferWideSlots(stores, wide) {
944
+ const inferred = new Map(wide);
945
+ let grew = true;
946
+ while (grew) {
947
+ grew = false;
948
+ for (const store of stores) {
949
+ if (inferred.get(store.slot) === 'time')
950
+ continue;
951
+ assumedWide = inferred;
952
+ try {
953
+ const { type } = typeSource(store.value, store.math64);
954
+ if (type.kind !== 'int64')
955
+ continue;
956
+ const holds = type.source === 'time' ? 'time' : 'number';
957
+ if (holds === 'time' || !inferred.has(store.slot)) {
958
+ inferred.set(store.slot, holds);
959
+ grew = true;
960
+ }
961
+ }
962
+ catch {
963
+ // Lowering the value again, with the widths inferred, reports its error.
964
+ }
965
+ finally {
966
+ assumedWide = null;
967
+ }
968
+ }
969
+ }
970
+ return inferred;
971
+ }
972
+ /**
973
+ * Whether two sets of slot widths are the same.
974
+ *
975
+ * @param a One set.
976
+ * @param b The other.
977
+ *
978
+ * @returns True when every slot holds the same in both.
979
+ */
980
+ export const sameSlotWidths = (a, b) => a.size === b.size && [...a].every(([slot, holds]) => b.get(slot) === holds);
981
+ /**
982
+ * Whether an operand is written as a number, so a boolean on the other side of `===` never equals it: a
983
+ * numeric literal, a negated one, or a non-boolean state read by name.
984
+ *
985
+ * @param node The operand.
986
+ * @param env The expression environment.
987
+ *
988
+ * @returns True when it is surely a number.
989
+ */
990
+ const isWrittenAsNumber = (node, env) => node.type === 'NumericLiteral' ||
991
+ (node.type === 'UnaryExpression' &&
992
+ node.argument.type === 'NumericLiteral') ||
993
+ (node.type === 'Identifier' &&
994
+ !env.locals.has(node.name) &&
995
+ env.state.get(node.name)?.isBool === false);
996
+ /**
997
+ * A binary expression's source, from its operands' sources.
998
+ *
999
+ * @param node The expression.
1000
+ * @param left Its left operand's source.
1001
+ * @param right Its right operand's source.
1002
+ * @param env The expression environment.
1003
+ *
1004
+ * @returns The source.
1005
+ */
1006
+ const binarySource = (node, left, right, env) => ({
1007
+ kind: 'binary',
1008
+ op: node.operator,
1009
+ left,
1010
+ right,
1011
+ divisor: { constant: staticInt(node.right, env), loc: node.right.loc?.start },
1012
+ leftIsNumber: isWrittenAsNumber(node.left, env),
1013
+ rightIsNumber: isWrittenAsNumber(node.right, env),
1014
+ loc: node.loc?.start,
1015
+ });
1016
+ /**
1017
+ * Lowers one JS expression to its source: names resolved, constants folded, and each operand lowered and typed
1018
+ * in turn, so an error in it is reported before anything after it.
1019
+ *
1020
+ * @param node The expression.
1021
+ * @param env The expression environment.
1022
+ *
1023
+ * @returns The source.
1024
+ */
1025
+ function sourceOf(node, env) {
1026
+ const loc = node.loc?.start;
1027
+ const operand = (operandNode) => lowerSource(operandNode, env).source;
1028
+ switch (node.type) {
1029
+ case 'NumericLiteral':
1030
+ return numberSource(node.value, loc);
1031
+ case 'StringLiteral':
1032
+ return { kind: 'string', value: node.value, loc };
1033
+ case 'BooleanLiteral':
1034
+ return { kind: 'boolean', value: node.value, loc };
1035
+ case 'Identifier': {
1036
+ // A name resolves to a local first, then to state, then to a compile-time constant.
1037
+ if (env.locals.has(node.name)) {
1038
+ return { kind: 'local', local: env.locals.get(node.name), loc };
1039
+ }
1040
+ if (env.state.has(node.name)) {
1041
+ const stateRecord = env.state.get(node.name);
1042
+ if (stateRecord.kind === 'list') {
1043
+ throw new Error(`AOT: a list state ("${node.name}") can only be used via .length or .map`);
1044
+ }
1045
+ return { kind: 'state', state: stateRecord, loc };
1046
+ }
1047
+ if (node.name in env.consts) {
1048
+ const constValue = env.consts[node.name];
1049
+ if (typeof constValue === 'number')
1050
+ return numberSource(constValue, loc);
1051
+ if (typeof constValue === 'string') {
1052
+ return { kind: 'string', value: constValue, loc };
1053
+ }
1054
+ if (typeof constValue === 'boolean') {
1055
+ return { kind: 'boolean', value: constValue, loc };
1056
+ }
1057
+ }
1058
+ throw new Error(`AOT: cannot resolve identifier "${node.name}" in a dynamic expression`);
1059
+ }
1060
+ case 'UnaryExpression': {
1061
+ // A constant is negated here, so `-A` is its value, and -2147483648 is not an int overflow.
1062
+ const staticOperand = node.operator === '-' ? staticInt(node.argument, env) : null;
1063
+ if (staticOperand !== null)
1064
+ return numberSource(-staticOperand, loc);
1065
+ const operandSource = operand(node.argument);
1066
+ if (node.operator === '-' ||
1067
+ node.operator === '+' ||
1068
+ node.operator === '!') {
1069
+ return { kind: 'unary', op: node.operator, operand: operandSource, loc };
1070
+ }
1071
+ throw new Error(`AOT: unsupported unary operator "${node.operator}"`);
1072
+ }
1073
+ case 'BinaryExpression': {
1074
+ // Fold `+ - *` over two whole-number constants as JS would, so a product past int range stays exact.
1075
+ const leftConst = CHECKED_HELPER[node.operator]
1076
+ ? staticInt(node.left, env)
1077
+ : null;
1078
+ const rightConst = leftConst === null ? null : staticInt(node.right, env);
1079
+ if (rightConst !== null) {
1080
+ return numberSource(node.operator === '+'
1081
+ ? leftConst + rightConst
1082
+ : node.operator === '-'
1083
+ ? leftConst - rightConst
1084
+ : leftConst * rightConst, loc);
1085
+ }
1086
+ return binarySource(node, operand(node.left), operand(node.right), env);
1087
+ }
1088
+ case 'LogicalExpression': {
1089
+ // Only `&&` and `||` are supported (not `??`).
1090
+ const operator = node.operator === '&&' || node.operator === '||' ? node.operator : null;
1091
+ if (!operator) {
1092
+ throw new Error(`AOT: unsupported logical operator "${node.operator}"`);
1093
+ }
1094
+ return {
1095
+ kind: 'logical',
1096
+ op: operator,
1097
+ left: operand(node.left),
1098
+ right: operand(node.right),
1099
+ loc,
1100
+ };
1101
+ }
1102
+ case 'ConditionalExpression':
1103
+ return {
1104
+ kind: 'conditional',
1105
+ test: operand(node.test),
1106
+ consequent: operand(node.consequent),
1107
+ alternate: operand(node.alternate),
1108
+ loc,
1109
+ };
1110
+ case 'MemberExpression': {
1111
+ // Static fold: member access that resolves to a compile-time constant (e.g., a .map item's `.key`).
1112
+ try {
1113
+ const constValue = evalStatic(node, foldScope(env, env.consts ?? {}));
1114
+ // A number with no float form falls through too, so its check runs now, not in the check pass.
1115
+ if (typeof constValue === 'number') {
1116
+ return attemptLowering(() => numberSource(constValue, loc));
1117
+ }
1118
+ if (typeof constValue === 'string') {
1119
+ return { kind: 'string', value: constValue, loc };
1120
+ }
1121
+ if (typeof constValue === 'boolean') {
1122
+ return { kind: 'boolean', value: constValue, loc };
1123
+ }
1124
+ }
1125
+ catch {
1126
+ /* not static — fall through to the dynamic member forms below */
1127
+ }
1128
+ // Otherwise the object must be one of the runtime forms below; `prop` is null for a computed member.
1129
+ const object = node.object;
1130
+ const prop = node.computed ? null : node.property.name;
1131
+ const fixed = (expr) => ({ kind: 'fixed', expr, loc });
1132
+ // `<list>.length` → the runtime count.
1133
+ if (object.type === 'Identifier' &&
1134
+ env.state.get(object.name)?.kind === 'list' &&
1135
+ prop === 'length') {
1136
+ return fixed({
1137
+ kind: 'listLength',
1138
+ list: env.state.get(object.name),
1139
+ type: INT,
1140
+ });
1141
+ }
1142
+ // `<item>.field` where item is a struct local (a list row's bound element).
1143
+ if (object.type === 'Identifier' &&
1144
+ env.locals.get(object.name)?.struct &&
1145
+ prop) {
1146
+ const item = env.locals.get(object.name);
1147
+ const field = item.struct.fields.find(structField => structField.key === prop);
1148
+ if (!field) {
1149
+ throw new Error(`AOT: unknown field "${prop}" on a list item`);
1150
+ }
1151
+ return fixed({
1152
+ kind: 'itemField',
1153
+ item,
1154
+ field,
1155
+ type: typeOfSlot(field.kind),
1156
+ });
1157
+ }
1158
+ // `<ref>.current` — a value ref's mutable C slot.
1159
+ if (object.type === 'Identifier' &&
1160
+ env.refs?.has(object.name) &&
1161
+ prop === 'current') {
1162
+ const ref = env.refs.get(object.name);
1163
+ ref.used = true;
1164
+ return { kind: 'ref', ref, loc };
1165
+ }
1166
+ // `<event>.x / .y / .dx / .dy` — touch fields of the handler's EREventData.
1167
+ if (object.type === 'Identifier' &&
1168
+ env.event === object.name &&
1169
+ (prop === 'x' || prop === 'y' || prop === 'dx' || prop === 'dy')) {
1170
+ return fixed({ kind: 'event', field: prop, type: INT });
1171
+ }
1172
+ // `<event>.vx / .vy` — finger velocity (px/ms) at the last move; the engine measures it, a handler cannot.
1173
+ if (object.type === 'Identifier' &&
1174
+ env.event === object.name &&
1175
+ (prop === 'vx' || prop === 'vy')) {
1176
+ return fixed({ kind: 'event', field: prop, type: FLOAT });
1177
+ }
1178
+ // `<gestureState>.…` — the second argument of a PanResponder callback (see emitPanResponder).
1179
+ if (object.type === 'Identifier' && env.gesture === object.name && prop) {
1180
+ return fixed(lowerGestureField(prop, env.pan));
1181
+ }
1182
+ // `<event>.layout.x / .y / .width / .height` — the onLayout rect.
1183
+ if (object.type === 'MemberExpression' &&
1184
+ !object.computed &&
1185
+ object.object.type === 'Identifier' &&
1186
+ env.event === object.object.name &&
1187
+ object.property.name === 'layout') {
1188
+ if (!LAYOUT_FIELDS.has(prop)) {
1189
+ throw new Error(`AOT: unknown onLayout rect field "${prop}" (use x / y / width / height)`);
1190
+ }
1191
+ return fixed({ kind: 'layout', field: prop, type: INT });
1192
+ }
1193
+ // `Math.PI` — the only Math constant.
1194
+ if (object.type === 'Identifier' &&
1195
+ object.name === 'Math' &&
1196
+ prop === 'PI') {
1197
+ return fixed({ kind: 'pi', type: FLOAT });
1198
+ }
1199
+ throw aotError('AOT: unsupported member expression in a dynamic context', 'in a handler or dynamic expression you can read state, `ref.current`, a `.map` item ' +
1200
+ 'field, event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.layout.*), and ' +
1201
+ 'Math.PI — other member access must be a compile-time constant.');
1202
+ }
1203
+ case 'CallExpression': {
1204
+ const callee = node.callee;
1205
+ // Date.now() / performance.now() → the engine clock, as 64-bit whole milliseconds.
1206
+ if (callee.type === 'MemberExpression' &&
1207
+ !callee.computed &&
1208
+ callee.object.type === 'Identifier' &&
1209
+ (callee.object.name === 'Date' ||
1210
+ callee.object.name === 'performance') &&
1211
+ !env.shadowedClock?.has(node)) {
1212
+ if (callee.property.name === 'now') {
1213
+ return {
1214
+ kind: 'fixed',
1215
+ expr: { kind: 'clock', clock: callee.object.name, type: TIME },
1216
+ loc,
1217
+ };
1218
+ }
1219
+ if (callee.object.name === 'Date') {
1220
+ throw dateObjectError();
1221
+ }
1222
+ }
1223
+ if (callee.type === 'Identifier' &&
1224
+ callee.name === 'Date' &&
1225
+ !env.shadowedClock?.has(node)) {
1226
+ throw dateObjectError();
1227
+ }
1228
+ // Math.*: a division under floor / ceil / round / trunc stays apart, for the typing pass to divide exactly.
1229
+ if (callee.type === 'MemberExpression' &&
1230
+ callee.object.name === 'Math') {
1231
+ const fn = callee.property.name;
1232
+ const division = node.arguments[0];
1233
+ const exactDivision = INT_ROUND_DIV.has(fn) &&
1234
+ node.arguments.length === 1 &&
1235
+ division.type === 'BinaryExpression' &&
1236
+ division.operator === '/';
1237
+ return {
1238
+ kind: 'math',
1239
+ fn,
1240
+ args: exactDivision
1241
+ ? [
1242
+ binarySource(division, operand(division.left), operand(division.right), env),
1243
+ ]
1244
+ : node.arguments.map(operand),
1245
+ exactDivision,
1246
+ wholeMath: keepsMath64Node(node),
1247
+ loc,
1248
+ };
1249
+ }
1250
+ throw new Error('AOT: unsupported call expression in a dynamic expression');
1251
+ }
1252
+ case 'NewExpression':
1253
+ // `new Date(…)` gets the Date-specific error; any other constructor gets the generic one below.
1254
+ if (node.callee.type === 'Identifier' &&
1255
+ node.callee.name === 'Date' &&
1256
+ !env.shadowedClock?.has(node)) {
1257
+ throw dateObjectError();
1258
+ }
1259
+ break;
1260
+ }
1261
+ throw new Error(`AOT: unsupported expression "${node.type}" in a dynamic context`);
1262
+ }
1263
+ /**
1264
+ * Lowers one JS expression to its source and types it, with the expression's location attached to any AOT
1265
+ * error either step throws.
1266
+ */
1267
+ export const lowerSource = withLoc((node, env) => {
1268
+ // Below a node that is not whole-number math, its operands are typed as usual (see keepsMath64Node).
1269
+ if (env.math64 && !keepsMath64Node(node)) {
1270
+ env = { ...env, math64: false };
1271
+ }
1272
+ const source = sourceOf(node, env);
1273
+ return { source, expr: typeSource(source, env.math64 ?? false) };
1274
+ });
1275
+ /**
1276
+ * Lowers one JS expression to the IR: its source, typed by the typing pass.
1277
+ *
1278
+ * @param node The expression.
1279
+ * @param env The expression environment.
1280
+ *
1281
+ * @returns The typed expression.
1282
+ */
1283
+ export const lowerExprWide = (node, env) => lowerSource(node, env).expr;
1284
+ /**
1285
+ * emitExpr for the destinations that can hold a 64-bit timestamp: state, refs, locals, text, conditions.
1286
+ *
1287
+ * @param node The expression.
1288
+ * @param env The expression environment.
1289
+ *
1290
+ * @returns The expression as C.
1291
+ */
1292
+ export const emitExprWide = (node, env) => toCExpr(lowerExprWide(node, env));
1293
+ /**
1294
+ * emitExprWide, for a local that holds the value: with the source it was lowered from, which the typing pass
1295
+ * reads when it infers slot widths.
1296
+ *
1297
+ * @param node The expression.
1298
+ * @param env The expression environment.
1299
+ *
1300
+ * @returns The expression as C, and its source.
1301
+ */
1302
+ export function emitSourcedWide(node, env) {
1303
+ const lowered = lowerSource(node, env);
1304
+ return { ...toCExpr(lowered.expr), source: lowered.source };
1305
+ }
1306
+ /**
1307
+ * Lowers an expression for a destination that holds an int, a float, or a string. C would narrow a 64-bit
1308
+ * value (a Date.now() / performance.now() timestamp, or a whole number past the int range) into one of those
1309
+ * without a warning, so it is refused here; the destinations that hold 64 bits call lowerExprWide.
1310
+ *
1311
+ * The result carries its type, so the caller can pick the right printf spec or assignment. A destination
1312
+ * that holds text lowers through lowerText instead.
1313
+ *
1314
+ * @param node The expression.
1315
+ * @param env The expression environment.
1316
+ *
1317
+ * @returns The lowered expression; never 64-bit.
1318
+ */
1319
+ export function lowerExpr(node, env) {
1320
+ const expr = lowerExprWide(node, env);
1321
+ if (expr.type.kind !== 'int64')
1322
+ return expr;
1323
+ const error = aotError('AOT: a 64-bit value (Date.now() / performance.now(), or a whole number past ±2^31) cannot be used here', 'keep it in state, a ref or a local, compare it, or show it in text. Anywhere else, ' +
1324
+ 'reduce it to a small number first — e.g. `ms % 1000`, or `Math.floor(ms / 1000) % ' +
1325
+ '60`.');
1326
+ if (node.loc) {
1327
+ error.aotLoc = node.loc.start;
1328
+ }
1329
+ throw error;
1330
+ }
1331
+ /**
1332
+ * lowerExpr, as C: what the emitters that do not build the IR yet use.
1333
+ *
1334
+ * @param node The expression.
1335
+ * @param env The expression environment.
1336
+ *
1337
+ * @returns The expression as C; never 64-bit.
1338
+ */
1339
+ export function emitExpr(node, env) {
1340
+ return toCExpr(lowerExpr(node, env));
1341
+ }
1342
+ /**
1343
+ * An aotError pinned to the expression that cannot be lowered to text (lowerTextParts is not withLoc-wrapped).
1344
+ *
1345
+ * @param node The expression.
1346
+ * @param message What is not supported.
1347
+ * @param hint How to rewrite it.
1348
+ *
1349
+ * @returns The error, for the caller to throw.
1350
+ */
1351
+ function textShapeError(node, message, hint) {
1352
+ const error = aotError(message, hint);
1353
+ if (node.loc) {
1354
+ error.aotLoc = node.loc.start;
1355
+ }
1356
+ return error;
1357
+ }
1358
+ /**
1359
+ * Text a constant renders as a standalone JSX child. React draws nothing for null, undefined, or a
1360
+ * boolean (see flattenTextChildren in Flow A), which is not how `+` treats the same values — a
1361
+ * concatenation operand goes through String() instead.
1362
+ *
1363
+ * @param value The constant.
1364
+ *
1365
+ * @returns The text React would render for it.
1366
+ */
1367
+ export const jsxChildText = (value) => value === undefined || value === null || typeof value === 'boolean'
1368
+ ? ''
1369
+ : String(value);
1370
+ /**
1371
+ * Splits a string-building `+` chain into text parts, following JS's own left-to-right typing: a `+`
1372
+ * is a concatenation only once one of its sides is a string, so `n + 1 + 'ms'` still adds before it
1373
+ * appends. Each part is literal text, a runtime value, or a boolean printed as a word.
1374
+ *
1375
+ * @param node The expression.
1376
+ * @param env The expression environment.
1377
+ * @param scope The constants a fold may read (already filtered by foldScope).
1378
+ * @param isOperand The expression is an operand of `+`, where null / undefined / booleans print as words.
1379
+ *
1380
+ * @returns The parts, and whether JS would treat the expression as a string.
1381
+ */
1382
+ function lowerTextParts(node, env, scope, isOperand = false) {
1383
+ // `undefined` is "" as a child but "undefined" in a `+`; handled here, not in the fold every prop reader shares.
1384
+ if (node.type === 'Identifier' && node.name === 'undefined') {
1385
+ return {
1386
+ isString: false,
1387
+ parts: [{ kind: 'literal', text: isOperand ? 'undefined' : '' }],
1388
+ };
1389
+ }
1390
+ // A compile-time constant becomes literal text.
1391
+ try {
1392
+ const constValue = evalStatic(node, scope);
1393
+ return {
1394
+ isString: typeof constValue === 'string',
1395
+ parts: [
1396
+ {
1397
+ kind: 'literal',
1398
+ text: isOperand ? String(constValue) : jsxChildText(constValue),
1399
+ },
1400
+ ],
1401
+ };
1402
+ }
1403
+ catch {
1404
+ /* not a compile-time constant — split it below */
1405
+ }
1406
+ // A `+` with a string on either side is a concatenation: its parts are both sides' parts in order.
1407
+ if (node.type === 'BinaryExpression' && node.operator === '+') {
1408
+ const leftParts = lowerTextParts(node.left, env, scope, true);
1409
+ const rightParts = lowerTextParts(node.right, env, scope, true);
1410
+ if (leftParts.isString || rightParts.isString) {
1411
+ return { isString: true, parts: [...leftParts.parts, ...rightParts.parts] };
1412
+ }
1413
+ }
1414
+ // A branch or operand that concatenates needs its own format; refuse before lowerExpr's misleading error.
1415
+ const concatenates = (subExpr) => subExpr.type === 'BinaryExpression' &&
1416
+ subExpr.operator === '+' &&
1417
+ lowerTextParts(subExpr, env, scope, true).isString;
1418
+ if (node.type === 'ConditionalExpression' &&
1419
+ (concatenates(node.test) ||
1420
+ concatenates(node.consequent) ||
1421
+ concatenates(node.alternate))) {
1422
+ throw textShapeError(node, 'AOT: a ternary in text cannot concatenate inside its test or a branch', 'each branch must be a single value — a literal, a state, or a number. Build the ' +
1423
+ "joined string first (a string useState set from a handler), or split it: {on ? 'a' : " +
1424
+ "'b'}{on ? s : ''}.");
1425
+ }
1426
+ if (node.type === 'LogicalExpression' &&
1427
+ (concatenates(node.left) || concatenates(node.right))) {
1428
+ throw textShapeError(node, `AOT: "${node.operator}" in text cannot concatenate inside an operand`, "write it with plain values — {ok ? 'n=' : ''}{ok ? n : ''} — or build the joined " +
1429
+ 'string first in a string useState.');
1430
+ }
1431
+ // Anything else is one runtime value.
1432
+ const value = lowerExprWide(node, env);
1433
+ // C collapses `&&`/`||` to 0/1 and a ternary to one slot, so text matches JS only when operands agree in kind.
1434
+ if (node.type === 'LogicalExpression' && !isBoolean(value.type)) {
1435
+ throw textShapeError(node, `AOT: "${node.operator}" in text evaluates to one of its operands, not to true/false`, `\`a ${node.operator} b\` is a or b unless both sides are already booleans — the ` +
1436
+ `generated C only has 0/1. Write the branch out instead: {cond ? 'yes' : ''}.`);
1437
+ }
1438
+ if (node.type === 'ConditionalExpression' &&
1439
+ isBoolean(lowerExprWide(node.consequent, env).type) !==
1440
+ isBoolean(lowerExprWide(node.alternate, env).type)) {
1441
+ throw textShapeError(node, 'AOT: a ternary in text mixes a boolean branch with a non-boolean one', 'JS renders those differently (`cond ? true : 5` is "true" or "5") but they share one ' +
1442
+ 'C slot here. Make both branches the same kind.');
1443
+ }
1444
+ // A boolean prints nothing as a child, "true"/"false" as an operand; isString stays false so `on + n` adds.
1445
+ if (isBoolean(value.type)) {
1446
+ return isOperand
1447
+ ? { isString: false, parts: [{ kind: 'booleanWord', value }] }
1448
+ : { isString: false, parts: [{ kind: 'literal', text: '' }] };
1449
+ }
1450
+ return {
1451
+ isString: value.type.kind === 'string',
1452
+ parts: [{ kind: 'value', value }],
1453
+ };
1454
+ }
1455
+ /**
1456
+ * Lowers an expression to text for a char-buffer destination (a <Text> body, a string state slot, a
1457
+ * <TextInput value>). A string-building `+` chain becomes its parts in order; anything else is one value.
1458
+ *
1459
+ * @param node The expression.
1460
+ * @param env The expression environment.
1461
+ * @param scope The constants a fold may read; by default the env's.
1462
+ *
1463
+ * @returns The text.
1464
+ */
1465
+ export function lowerText(node, env, scope = env.consts ?? {}) {
1466
+ return { parts: lowerTextParts(node, env, foldScope(env, scope)).parts };
1467
+ }
1468
+ /**
1469
+ * lowerText, printed as one printf format and its arguments (one spec per runtime value, literals folded in).
1470
+ *
1471
+ * @param node The expression.
1472
+ * @param env The expression environment.
1473
+ * @param scope The constants a fold may read; by default the env's.
1474
+ *
1475
+ * @returns The format, with literal `%` already escaped as `%%`, and its arguments.
1476
+ */
1477
+ export function emitFormat(node, env, scope = env.consts ?? {}) {
1478
+ return printText(lowerText(node, env, scope));
1479
+ }