embedded-react 0.19.0 → 0.21.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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -16,30 +16,29 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { attemptLowering, checkNumber } from './check.mjs';
19
+ import { attemptLowering, checkNumber, whenTyped } from './check.mjs';
20
+ import { copyLocal, holdLater, holdsUntyped, readLocalOf, localShape, shapeOf, typedLater, } from './typing.mjs';
20
21
  import { traverse } from '@babel/core';
21
- import { aotError, locateError, withLoc } from './diagnostics.mjs';
22
+ import { isContextRead } from './contexts.mjs';
23
+ import { ENGINE_STRING_MAX, aotError, locateError, withLoc, } from './diagnostics.mjs';
22
24
  import { bootSlotOf, containsBoot, foldBoot, isBoot, wholeBootValue, } from './boot.mjs';
23
- import { evalStatic, foldScope, hasBinding } from './static-eval.mjs';
25
+ import { HiddenField, RuntimeLeaf, evalStatic, setBinding, fixedDigitsProblem, foldScope, hasBinding, includesProblem, padFillProblem, padWidthProblem, rethrowFoldLimit, slicePositionProblem, } from './static-eval.mjs';
24
26
  import { lowerGestureField } from './pan-responder.mjs';
25
- import { toCExpr } from './c/expressions.mjs';
26
- import { printText } from './c/text.mjs';
27
- 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
+ import { derivedListOf, rowItemOf } from './list-order.mjs';
28
+ import { MAX_LIST_CAPACITY } from './options.mjs';
29
+ import { fieldsUnder, inferItemStruct, isPlainObject, itemReadOf, } from './list-items.mjs';
30
+ import { helperValueOf, returnedExpression } from './helper-values.mjs';
31
+ import { isObjectTree, propertyKey } from './records.mjs';
32
+ import { lowerNativeCall, nativeAvailableOf, unkeptRecordError, nativeCalleeOf, readsNativeModule, } from './native-modules.mjs';
33
+ import { lowerTagTest, narrowOn, narrowed, tagTestOf, } from './tagged-records.mjs';
34
+ import { TEXT_END } from './ir/text.mjs';
35
+ import { BOOL, FLOAT, INT, INT64_NUMBER, INT64_MATH, STRING, TIME, isBoolean, isConvertible64, isIntSlot, isTime, int64Join, int64Of, stateType, refType, slotOf, typeOfSlot, typeOfSlotValue, wideSlotOf, } from './ir/types.mjs';
28
36
  /*----------------------------------------------------------------------------------------------------------------------
29
37
  - Constants
30
38
  ---------------------------------------------------------------------------------------------------------------------*/
31
39
  /** The binary operators lowered as arithmetic, and those lowered as comparisons. */
32
- const ARITH = new Set(['+', '-', '*', '/', '%']);
40
+ const ARITHMETIC = new Set(['+', '-', '*', '/', '%']);
33
41
  const COMPARE = new Set(['<', '>', '<=', '>=', '==', '!=', '===', '!==']);
34
- /**
35
- * The C helper each whole-number operator lowers to. It saturates at the limit of its type, where C's own
36
- * signed overflow is undefined behavior; the 64-bit variant appends `64`.
37
- */
38
- export const CHECKED_OP = {
39
- '+': 'app_add',
40
- '-': 'app_sub',
41
- '*': 'app_mul',
42
- };
43
42
  /** The saturating helper each whole-number operator lowers to in the IR. */
44
43
  const CHECKED_HELPER = {
45
44
  '+': 'add',
@@ -54,9 +53,17 @@ const WHOLE_BOOT_TYPES = new Set([
54
53
  'ConditionalExpression',
55
54
  'CallExpression',
56
55
  ]);
57
- /** The range of a C int. */
56
+ /** The range of an int. */
58
57
  const INT_MIN = -(2 ** 31);
59
58
  export const INT_MAX = 2 ** 31 - 1;
59
+ /** The type a native method's result is read as. */
60
+ const NATIVE_TYPES = {
61
+ int: INT,
62
+ float: FLOAT,
63
+ bool: BOOL,
64
+ int64: INT64_NUMBER,
65
+ string: STRING,
66
+ };
60
67
  /** The Math functions that keep a whole number whole. */
61
68
  const WHOLE_MATH = new Set([
62
69
  'floor',
@@ -68,7 +75,7 @@ const WHOLE_MATH = new Set([
68
75
  'max',
69
76
  ]);
70
77
  /** The helper that rounds `a / b` for two whole numbers the way each Math function does. */
71
- const INT_ROUND_DIV = new Map([
78
+ const INT_ROUND_DIVISION = new Map([
72
79
  ['floor', 'floordiv'],
73
80
  ['ceil', 'ceildiv'],
74
81
  ['round', 'rounddiv'],
@@ -88,14 +95,15 @@ const FLOAT_MATH_UNARY = new Set([
88
95
  const FLOAT_MATH_BINARY = new Set(['min', 'max', 'atan2', 'pow']);
89
96
  /** While the typing pass infers slot widths: the slots it takes to hold 64 bits, and what each holds. */
90
97
  let assumedWide = null;
98
+ /** How a state or local whose type the typing pass works out is typed while it infers slot widths. */
99
+ const assumedTypes = new WeakMap();
91
100
  /** The fields of an onLayout rect. */
92
101
  const LAYOUT_FIELDS = new Set(['x', 'y', 'width', 'height']);
102
+ /** The largest 32-bit int. */
103
+ const INT32_MAX = 0x7fffffff;
93
104
  /*----------------------------------------------------------------------------------------------------------------------
94
105
  - Implementation
95
106
  ---------------------------------------------------------------------------------------------------------------------*/
96
- // The modules that still build C from a lowered expression or text import asCond and formatArgs from here.
97
- export { asCond } from './c/expressions.mjs';
98
- export { formatArgs } from './c/text.mjs';
99
107
  /**
100
108
  * A 64-bit timestamp met a float, which would round it.
101
109
  *
@@ -146,13 +154,13 @@ export function findShadowedClockCalls(ast) {
146
154
  * `node` as an integer compile-time constant, or null.
147
155
  *
148
156
  * @param node The expression.
149
- * @param env The expression environment.
157
+ * @param environment The expression environment.
150
158
  *
151
159
  * @returns The integer, or null when the expression is not one.
152
160
  */
153
- export function staticInt(node, env) {
161
+ export function staticInt(node, environment) {
154
162
  try {
155
- const value = evalStatic(node, foldScope(env, env.consts ?? {}), 'strict');
163
+ const value = evalStatic(node, foldScope(environment, environment.constants ?? {}), 'strict');
156
164
  return Number.isInteger(value) ? value : null;
157
165
  }
158
166
  catch {
@@ -181,38 +189,42 @@ function numConst(value) {
181
189
  * check pass, at the expression: a float holds no NaN or Infinity, a folded `0 / 0` say.
182
190
  *
183
191
  * @param value The number.
184
- * @param loc Where it is.
192
+ * @param location Where it is.
185
193
  *
186
194
  * @returns Its source.
187
195
  */
188
- function numberSource(value, loc) {
196
+ function numberSource(value, location) {
189
197
  if (numConst(value).type.kind === 'float') {
190
198
  checkNumber(value);
191
199
  }
192
- return { kind: 'number', value, loc };
200
+ return { kind: 'number', value, location };
193
201
  }
194
202
  /**
195
203
  * A read of a value worked out at boot. One boot cannot work out is taken at the build's panel instead, which
196
204
  * the panel at boot must then give too.
197
205
  *
198
206
  * @param value The value.
199
- * @param loc Where it is read.
207
+ * @param location Where it is read.
200
208
  *
201
209
  * @returns Its source.
202
210
  */
203
- function bootSource(value, loc) {
211
+ function bootSource(value, location) {
204
212
  const slot = bootSlotOf(value);
205
213
  if (slot) {
206
- return { kind: 'fixed', expr: { kind: 'boot', slot, type: slot.type }, loc };
214
+ return {
215
+ kind: 'fixed',
216
+ expression: { kind: 'boot', slot, type: slot.type },
217
+ location,
218
+ };
207
219
  }
208
220
  const buildValue = foldBoot(value);
209
221
  if (typeof buildValue === 'number')
210
- return numberSource(buildValue, loc);
222
+ return numberSource(buildValue, location);
211
223
  if (typeof buildValue === 'string') {
212
- return { kind: 'string', value: buildValue, loc };
224
+ return { kind: 'string', value: buildValue, location };
213
225
  }
214
226
  if (typeof buildValue === 'boolean') {
215
- return { kind: 'boolean', value: buildValue, loc };
227
+ return { kind: 'boolean', value: buildValue, location };
216
228
  }
217
229
  throw new Error('AOT: a value derived from the panel size cannot be used in a dynamic expression');
218
230
  }
@@ -248,13 +260,13 @@ function readsBootName(node, scope) {
248
260
  * in double precision. Null for one that also reads state, or that boot cannot work out.
249
261
  *
250
262
  * @param node The expression.
251
- * @param env The expression environment.
252
- * @param loc Where it is.
263
+ * @param environment The expression environment.
264
+ * @param location Where it is.
253
265
  *
254
266
  * @returns Its source, or null.
255
267
  */
256
- function wholeBootSource(node, env, loc) {
257
- const scope = foldScope(env, env.consts ?? {});
268
+ function wholeBootSource(node, environment, location) {
269
+ const scope = foldScope(environment, environment.constants ?? {});
258
270
  if (!readsBootName(node, scope))
259
271
  return null;
260
272
  let value;
@@ -269,7 +281,11 @@ function wholeBootSource(node, env, loc) {
269
281
  const whole = wholeBootValue(node, scope, value);
270
282
  const slot = whole && bootSlotOf(whole);
271
283
  return slot
272
- ? { kind: 'fixed', expr: { kind: 'boot', slot, type: slot.type }, loc }
284
+ ? {
285
+ kind: 'fixed',
286
+ expression: { kind: 'boot', slot, type: slot.type },
287
+ location,
288
+ }
273
289
  : null;
274
290
  }
275
291
  /**
@@ -306,7 +322,7 @@ const boolConst = (value) => ({
306
322
  const localRead = (local) => ({
307
323
  kind: 'local',
308
324
  local,
309
- type: typeOfCExpr(local),
325
+ type: typeOfSlotValue(local),
310
326
  });
311
327
  /**
312
328
  * Whole-number math JS would not cut to 32 bits: `+ - *`, negation, `%`, and the Math functions that keep a
@@ -333,18 +349,18 @@ const keepsMath64Node = (node) => (node.type === 'BinaryExpression' &&
333
349
  * @returns Whether it is whole-number math JS would not cut to 32 bits.
334
350
  */
335
351
  const keepsMath64 = (source) => (source.kind === 'binary' &&
336
- (Boolean(CHECKED_HELPER[source.op]) || source.op === '%')) ||
337
- (source.kind === 'unary' && source.op === '-') ||
352
+ (Boolean(CHECKED_HELPER[source.operator]) || source.operator === '%')) ||
353
+ (source.kind === 'unary' && source.operator === '-') ||
338
354
  (source.kind === 'math' && source.wholeMath);
339
355
  /**
340
356
  * A 64-bit value computed at runtime from a timestamp, as opposed to a 64-bit constant or whole-number math
341
357
  * widened to 64 bits beside one.
342
358
  *
343
- * @param expr The lowered expression.
359
+ * @param expression The lowered expression.
344
360
  *
345
361
  * @returns Whether it is a timestamp.
346
362
  */
347
- export const isTime64 = (expr) => isTime(expr.type);
363
+ export const isTime64 = (expression) => isTime(expression.type);
348
364
  /**
349
365
  * Besides a float, a 64-bit number that is not a time converts, as in JS; only a timestamp refuses.
350
366
  *
@@ -360,16 +376,16 @@ const litPeers = (...operands) => operands.some(operand => operand.type.kind ===
360
376
  /**
361
377
  * The error for a divisor that is not a constant where a time's has to be one.
362
378
  *
363
- * @param loc Where the divisor is.
379
+ * @param location Where the divisor is.
364
380
  *
365
381
  * @returns The error, for the caller to throw.
366
382
  */
367
- function nonConstantDivisorError(loc) {
383
+ function nonConstantDivisorError(location) {
368
384
  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 / ' +
369
385
  '60000)`. For a divisor from state, reduce the timestamp first: `(ms % 86400000) / ' +
370
386
  'period`.');
371
- if (loc) {
372
- error.aotLoc = loc;
387
+ if (location) {
388
+ error.aotLoc = location;
373
389
  }
374
390
  return error;
375
391
  }
@@ -379,12 +395,12 @@ function nonConstantDivisorError(loc) {
379
395
  * converts it: a remainder of 0, or a quotient saturated by the dividend's sign.
380
396
  *
381
397
  * @param node The divisor.
382
- * @param env The expression environment.
398
+ * @param environment The expression environment.
383
399
  *
384
400
  * @returns The divisor's value.
385
401
  */
386
- export function constDivisor(node, env) {
387
- const divisor = staticInt(node, env);
402
+ export function constDivisor(node, environment) {
403
+ const divisor = staticInt(node, environment);
388
404
  if (divisor !== null)
389
405
  return divisor;
390
406
  throw nonConstantDivisorError(node.loc?.start);
@@ -399,7 +415,7 @@ export function constDivisor(node, env) {
399
415
  function sourceDivisor(divisor) {
400
416
  if (divisor.constant !== null)
401
417
  return divisor.constant;
402
- throw nonConstantDivisorError(divisor.loc);
418
+ throw nonConstantDivisorError(divisor.location);
403
419
  }
404
420
  /**
405
421
  * `+ - * %` with a 64-bit value on either side, kept whole. `+ - *` saturate at the int64 limits. With a
@@ -418,14 +434,14 @@ function typeArith64(source, left, right) {
418
434
  if (left.type.kind === 'float' || right.type.kind === 'float') {
419
435
  throw mix64Error();
420
436
  }
421
- if (source.op === '/') {
437
+ if (source.operator === '/') {
422
438
  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 / ' +
423
439
  'b) for whole units — e.g. Math.floor(ms / 1000) for seconds.');
424
440
  }
425
441
  // With no timestamp on either side, this is whole-number math widened to 64 bits.
426
442
  const isWide = !isTime64(left) && !isTime64(right);
427
443
  // `%`: zero/±1 divisors give 0, a timestamp needs a constant divisor, and the result narrows to int if it fits.
428
- if (source.op === '%') {
444
+ if (source.operator === '%') {
429
445
  const staticDivisor = source.divisor.constant;
430
446
  // JS gives NaN for a zero divisor, which is 0 here, as the int `%` has it.
431
447
  if (staticDivisor === 0)
@@ -435,20 +451,20 @@ function typeArith64(source, left, right) {
435
451
  kind: 'helper',
436
452
  helper: 'mod',
437
453
  bits: 64,
438
- args: [left, right],
454
+ callArguments: [left, right],
439
455
  type: INT64_MATH,
440
456
  };
441
457
  }
442
458
  const divisor = sourceDivisor(source.divisor);
443
- // ±1 leaves no remainder, and INT64_MIN % -1 overflows in C.
459
+ // ±1 leaves no remainder, and INT64_MIN % -1 overflows.
444
460
  if (divisor === 1 || divisor === -1)
445
461
  return numConst(0);
446
- if (Math.abs(divisor) <= 0x7fffffff || isIntSlot(left.type)) {
462
+ if (Math.abs(divisor) <= INT32_MAX || isIntSlot(left.type)) {
447
463
  return { kind: 'narrowRemainder', left, right, type: INT };
448
464
  }
449
465
  return {
450
466
  kind: 'arithmetic',
451
- op: '%',
467
+ operator: '%',
452
468
  left,
453
469
  right,
454
470
  type: isWide ? INT64_MATH : TIME,
@@ -457,9 +473,9 @@ function typeArith64(source, left, right) {
457
473
  // `+ - *`: the saturating 64-bit helper.
458
474
  return {
459
475
  kind: 'helper',
460
- helper: CHECKED_HELPER[source.op],
476
+ helper: CHECKED_HELPER[source.operator],
461
477
  bits: 64,
462
- args: [left, right],
478
+ callArguments: [left, right],
463
479
  type: isWide ? INT64_MATH : TIME,
464
480
  };
465
481
  }
@@ -468,13 +484,13 @@ function typeArith64(source, left, right) {
468
484
  * division by a constant (see constDivisor); a zero one saturates by the dividend's sign, as JS's ±Infinity
469
485
  * converts. Null when neither side is a timestamp, which leaves it to the whole-number or float path.
470
486
  *
471
- * @param fn The Math function's name.
487
+ * @param mathFunction The Math function's name.
472
488
  * @param division Its one argument, the division.
473
489
  * @param math64 Whole-number math is worked out in 64 bits here.
474
490
  *
475
491
  * @returns The typed call, or null when it is not this case.
476
492
  */
477
- function typeTimeRoundDiv(fn, division, math64) {
493
+ function typeTimeRoundDiv(mathFunction, division, math64) {
478
494
  const dividend = typeSource(division.left, math64);
479
495
  const divisor = typeSource(division.right, math64);
480
496
  if (!isTime64(dividend) && !isTime64(divisor))
@@ -484,39 +500,39 @@ function typeTimeRoundDiv(fn, division, math64) {
484
500
  }
485
501
  if (dividend.type.kind === 'string' || divisor.type.kind === 'string')
486
502
  return null;
487
- // Dividing by -1 is a negation, which saturates; C's `/` would overflow on INT64_MIN / -1.
503
+ // Dividing by -1 is a negation, which saturates; a plain `/` would overflow on INT64_MIN / -1.
488
504
  if (sourceDivisor(division.divisor) === -1) {
489
505
  return {
490
506
  kind: 'helper',
491
507
  helper: 'neg',
492
508
  bits: 64,
493
- args: [dividend],
509
+ callArguments: [dividend],
494
510
  type: TIME,
495
511
  };
496
512
  }
497
513
  return {
498
514
  kind: 'helper',
499
- helper: INT_ROUND_DIV.get(fn),
515
+ helper: INT_ROUND_DIVISION.get(mathFunction),
500
516
  bits: 64,
501
- args: [dividend, divisor],
517
+ callArguments: [dividend, divisor],
502
518
  type: TIME,
503
519
  };
504
520
  }
505
521
  /**
506
522
  * Math.floor / ceil / round / trunc over `a / b` with two whole numbers, as exact integer division: the float
507
523
  * path rounds an operand past 2^24, so Math.floor(16777217 / 1) would come out 16777216. A zero divisor keeps
508
- * JS's answer as app_f2i converts it (±Infinity saturates by the dividend's sign, 0 / 0 is 0), and
524
+ * JS's answer as an int (±Infinity saturates by the dividend's sign, 0 / 0 is 0), and
509
525
  * INT_MIN / -1 saturates too. Beside a 64-bit value, or with a 64-bit operand that is not a timestamp (a
510
526
  * constant past the int range, or math already widened), it divides in 64 bits, since JS would not cut the
511
527
  * operands to 32. Null for anything else, which leaves it to the float path.
512
528
  *
513
- * @param fn The Math function's name.
529
+ * @param mathFunction The Math function's name.
514
530
  * @param division Its one argument, the division.
515
531
  * @param math64 Whole-number math is worked out in 64 bits here.
516
532
  *
517
533
  * @returns The typed call, or null when it is not this case.
518
534
  */
519
- function typeIntRoundDiv(fn, division, math64) {
535
+ function typeIntRoundDiv(mathFunction, division, math64) {
520
536
  // Divide in 64 bits beside a 64-bit value, when both operands are whole numbers and neither is a timestamp.
521
537
  const dividend = typeSource(division.left, math64);
522
538
  const divisor = typeSource(division.right, math64);
@@ -529,9 +545,9 @@ function typeIntRoundDiv(fn, division, math64) {
529
545
  return null;
530
546
  return {
531
547
  kind: 'helper',
532
- helper: INT_ROUND_DIV.get(fn),
548
+ helper: INT_ROUND_DIVISION.get(mathFunction),
533
549
  bits: 64,
534
- args: [dividend, divisor],
550
+ callArguments: [dividend, divisor],
535
551
  type: INT64_MATH,
536
552
  };
537
553
  }
@@ -540,56 +556,61 @@ function typeIntRoundDiv(fn, division, math64) {
540
556
  return null;
541
557
  return {
542
558
  kind: 'helper',
543
- helper: INT_ROUND_DIV.get(fn),
559
+ helper: INT_ROUND_DIVISION.get(mathFunction),
544
560
  bits: 32,
545
- args: [dividend, divisor],
561
+ callArguments: [dividend, divisor],
546
562
  type: INT,
547
563
  };
548
564
  }
549
565
  /**
550
566
  * Math.* over a 64-bit timestamp: only what stays exact in whole numbers.
551
567
  *
552
- * @param fn The Math function's name.
553
- * @param argExprs Its typed arguments, at least one of them 64-bit.
568
+ * @param mathFunction The Math function's name.
569
+ * @param argumentExpressions Its typed arguments, at least one of them 64-bit.
554
570
  *
555
571
  * @returns The typed call.
556
572
  */
557
- function typeMath64(fn, argExprs) {
558
- if (argExprs.some(argExpr => argExpr.type.kind === 'float')) {
573
+ function typeMath64(mathFunction, argumentExpressions) {
574
+ if (argumentExpressions.some(argumentExpression => argumentExpression.type.kind === 'float')) {
559
575
  throw mix64Error();
560
576
  }
561
- if (argExprs.every(argExpr => isIntSlot(argExpr.type) || argExpr.type.kind === 'int64')) {
577
+ if (argumentExpressions.every(argumentExpression => isIntSlot(argumentExpression.type) ||
578
+ argumentExpression.type.kind === 'int64')) {
562
579
  // Whole-number math with no timestamp in it stays whole-number math.
563
- const isWide = !argExprs.some(isTime64);
580
+ const isWide = !argumentExpressions.some(isTime64);
564
581
  // A timestamp is already whole, so rounding leaves it as it is.
565
- if ((fn === 'floor' || fn === 'round' || fn === 'ceil' || fn === 'trunc') &&
566
- argExprs.length === 1) {
582
+ if ((mathFunction === 'floor' ||
583
+ mathFunction === 'round' ||
584
+ mathFunction === 'ceil' ||
585
+ mathFunction === 'trunc') &&
586
+ argumentExpressions.length === 1) {
567
587
  return {
568
588
  kind: 'wholeRound',
569
- operand: argExprs[0],
589
+ operand: argumentExpressions[0],
570
590
  type: isWide ? INT64_MATH : TIME,
571
591
  };
572
592
  }
573
- if (fn === 'abs' && argExprs.length === 1) {
593
+ if (mathFunction === 'abs' && argumentExpressions.length === 1) {
574
594
  return {
575
595
  kind: 'helper',
576
596
  helper: 'abs',
577
597
  bits: 64,
578
- args: [argExprs[0]],
598
+ callArguments: [argumentExpressions[0]],
579
599
  type: isWide ? INT64_MATH : TIME,
580
600
  };
581
601
  }
582
- if ((fn === 'min' || fn === 'max') && argExprs.length === 2) {
602
+ if ((mathFunction === 'min' || mathFunction === 'max') &&
603
+ argumentExpressions.length === 2) {
583
604
  return {
584
605
  kind: 'helper',
585
- helper: fn,
606
+ helper: mathFunction,
586
607
  bits: 64,
587
- args: [argExprs[0], argExprs[1]],
608
+ callArguments: [argumentExpressions[0], argumentExpressions[1]],
588
609
  type: isWide ? INT64_MATH : TIME,
589
610
  };
590
611
  }
591
612
  }
592
- 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 ' +
613
+ throw aotError(`AOT: Math.${mathFunction}(...) on a 64-bit time value is not supported`, 'Math.floor / round / ceil / trunc / abs / min / max keep a timestamp exact; for ' +
593
614
  'anything else, reduce it to a small number first, e.g. `ms % 1000`.');
594
615
  }
595
616
  /**
@@ -602,12 +623,12 @@ function typeMath64(fn, argExprs) {
602
623
  */
603
624
  function typeUnary(source, math64) {
604
625
  const operand = typeSource(source.operand, math64);
605
- if ((source.op === '-' || source.op === '+') &&
626
+ if ((source.operator === '-' || source.operator === '+') &&
606
627
  operand.type.kind === 'string') {
607
- 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.');
628
+ throw aotError(`AOT: unary "${source.operator}" on a string is not supported`, "JS would coerce the string to a number; the AOT doesn't. Keep the operand numeric.");
608
629
  }
609
630
  // Negating the minimum overflows, so a whole number saturates the way `+ - *` do.
610
- if (source.op === '-' &&
631
+ if (source.operator === '-' &&
611
632
  (isIntSlot(operand.type) || operand.type.kind === 'int64')) {
612
633
  const is64Bit = operand.type.kind === 'int64' || math64;
613
634
  return is64Bit
@@ -615,23 +636,27 @@ function typeUnary(source, math64) {
615
636
  kind: 'helper',
616
637
  helper: 'neg',
617
638
  bits: 64,
618
- args: [operand],
639
+ callArguments: [operand],
619
640
  type: operand.type.kind === 'int64' ? operand.type : INT64_MATH,
620
641
  }
621
642
  : {
622
643
  kind: 'helper',
623
644
  helper: 'neg',
624
645
  bits: 32,
625
- args: [operand],
646
+ callArguments: [operand],
626
647
  type: INT,
627
648
  };
628
649
  }
629
650
  // Only `!` yields a boolean; unary +/- coerce to a number, so `+flag` drops its boolean-ness.
630
651
  return {
631
652
  kind: 'unary',
632
- op: source.op,
653
+ operator: source.operator,
633
654
  operand,
634
- type: source.op === '!' ? BOOL : isBoolean(operand.type) ? INT : operand.type,
655
+ type: source.operator === '!'
656
+ ? BOOL
657
+ : isBoolean(operand.type)
658
+ ? INT
659
+ : operand.type,
635
660
  };
636
661
  }
637
662
  /**
@@ -657,48 +682,47 @@ function typeBinary(source, math64) {
657
682
  }
658
683
  [left, right] = litPeers(left, right);
659
684
  // Arithmetic: refuse strings, hand 64-bit math to typeArith64, and saturate whole-number `+ - *`.
660
- if (ARITH.has(source.op)) {
685
+ if (ARITHMETIC.has(source.operator)) {
661
686
  if (left.type.kind === 'string' || right.type.kind === 'string') {
662
- // String `+` has no single C value; only a char-buffer destination can lower it, via emitFormat().
663
- if (source.op === '+') {
664
- 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 ' +
665
- 'lands in a text buffer: a <Text> body, a string useState setter, or a <TextInput ' +
666
- 'value>.');
687
+ // String `+` has no single value; only a destination that holds text can lower it, via lowerText().
688
+ if (source.operator === '+') {
689
+ throw aotError('AOT: string concatenation is not supported in this position', 'a `+` chain over strings only works where the value lands in text: a <Text> body, a string ' +
690
+ 'useState setter, or a <TextInput value>.');
667
691
  }
668
- // JS would coerce the string to a number; C would do pointer arithmetic or refuse to compile.
669
- throw aotError(`AOT: "${source.op}" on a string is not supported`, 'keep both operands numeric — a string cannot be coerced to a number here.');
692
+ // JS would coerce the string to a number; the AOT doesn't.
693
+ throw aotError(`AOT: "${source.operator}" on a string is not supported`, 'keep both operands numeric — a string cannot be coerced to a number here.');
670
694
  }
671
- // `/` takes a 64-bit constant as an ordinary C number; only a runtime 64-bit value is refused it.
695
+ // `/` takes a 64-bit constant as an ordinary number; only a runtime 64-bit value is refused it.
672
696
  if (isTime64(left) ||
673
697
  isTime64(right) ||
674
698
  ((left.type.kind === 'int64' || right.type.kind === 'int64') &&
675
- (CHECKED_HELPER[source.op] || source.op === '%'))) {
699
+ (CHECKED_HELPER[source.operator] || source.operator === '%'))) {
676
700
  return typeArith64(source, left, right);
677
701
  }
678
- if (source.op === '/') {
702
+ if (source.operator === '/') {
679
703
  return { kind: 'floatDivide', left, right, type: FLOAT };
680
704
  }
681
705
  const isFloat = left.type.kind === 'float' || right.type.kind === 'float';
682
- const checkedHelper = !isFloat && CHECKED_HELPER[source.op];
706
+ const checkedHelper = !isFloat && CHECKED_HELPER[source.operator];
683
707
  if (checkedHelper) {
684
708
  return math64
685
709
  ? {
686
710
  kind: 'helper',
687
711
  helper: checkedHelper,
688
712
  bits: 64,
689
- args: [left, right],
713
+ callArguments: [left, right],
690
714
  type: INT64_MATH,
691
715
  }
692
716
  : {
693
717
  kind: 'helper',
694
718
  helper: checkedHelper,
695
719
  bits: 32,
696
- args: [left, right],
720
+ callArguments: [left, right],
697
721
  type: INT,
698
722
  };
699
723
  }
700
- // A 0 divisor (NaN in JS) or -1 (INT_MIN % -1 overflows C) gives 0; other constants need no check.
701
- if (!isFloat && source.op === '%') {
724
+ // A 0 divisor (NaN in JS) or -1 (INT_MIN % -1 overflows) gives 0; other constants need no check.
725
+ if (!isFloat && source.operator === '%') {
702
726
  const staticDivisor = source.divisor.constant;
703
727
  if (staticDivisor === 0 || staticDivisor === -1) {
704
728
  return numConst(0);
@@ -708,48 +732,57 @@ function typeBinary(source, math64) {
708
732
  kind: 'helper',
709
733
  helper: 'mod',
710
734
  bits: 32,
711
- args: [left, right],
735
+ callArguments: [left, right],
712
736
  type: INT,
713
737
  };
714
738
  }
715
739
  }
716
- // C has no float `%`; fmodf matches JS's `%` exactly, zero and infinite divisors included.
717
- if (isFloat && source.op === '%') {
740
+ // fmod matches JS's `%` exactly, zero and infinite divisors included.
741
+ if (isFloat && source.operator === '%') {
718
742
  return {
719
743
  kind: 'floatMath',
720
- fn: 'mod',
721
- args: [left, right],
744
+ mathFunction: 'mod',
745
+ callArguments: [left, right],
722
746
  type: FLOAT,
723
747
  };
724
748
  }
725
749
  return {
726
750
  kind: 'arithmetic',
727
- op: source.op,
751
+ operator: source.operator,
728
752
  left,
729
753
  right,
730
754
  type: isFloat ? FLOAT : INT,
731
755
  };
732
756
  }
733
- // Comparisons: strings through strcmp, everything else as a plain C comparison yielding a boolean.
734
- if (COMPARE.has(source.op)) {
735
- const cOperator = source.op === '===' ? '==' : source.op === '!==' ? '!=' : source.op;
757
+ // Comparisons: strings by their text, everything else as a plain comparison yielding a boolean.
758
+ if (COMPARE.has(source.operator)) {
759
+ const comparison = source.operator === '==='
760
+ ? '=='
761
+ : source.operator === '!=='
762
+ ? '!='
763
+ : source.operator;
736
764
  if (left.type.kind === 'string' || right.type.kind === 'string') {
737
765
  if (slotOf(left.type) !== slotOf(right.type)) {
738
766
  // A strict comparison never coerces, so a string against a number is decided statically.
739
- if (source.op === '===' || source.op === '!==') {
740
- return boolConst(source.op === '!==');
767
+ if (source.operator === '===' || source.operator === '!==') {
768
+ return boolConst(source.operator === '!==');
741
769
  }
742
- 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. ` +
770
+ throw aotError('AOT: a string cannot be compared with a number', `\`${source.operator}\` coerces the string to a number in JS, which the AOT doesn't reproduce. ` +
743
771
  `Compare like with like, or use === / !== (which never coerce).`);
744
772
  }
745
- // Equality is exact, but strcmp's UTF-8 order can differ from JS's UTF-16 order, so refuse ordering.
746
- if (cOperator !== '==' && cOperator !== '!=') {
747
- 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 ' +
748
- 'differ. Use === / !==, or compare numbers.');
773
+ // Strings order by UTF-16 code unit, as JS orders them.
774
+ if (comparison !== '==' && comparison !== '!=') {
775
+ return {
776
+ kind: 'compare',
777
+ operator: comparison,
778
+ left: { kind: 'stringOrder', left, right, type: INT },
779
+ right: { kind: 'number', value: 0, type: INT },
780
+ type: BOOL,
781
+ };
749
782
  }
750
783
  return {
751
784
  kind: 'stringEquals',
752
- op: cOperator,
785
+ operator: comparison,
753
786
  left,
754
787
  right,
755
788
  type: BOOL,
@@ -760,25 +793,25 @@ function typeBinary(source, math64) {
760
793
  (left.type.kind === 'float' || right.type.kind === 'float')) {
761
794
  throw mix64Error();
762
795
  }
763
- // `true === 1` is false in JS but true in C's int slot; fold it when the other side is surely a number.
796
+ // `true === 1` is false in JS but true in an int slot; fold it when the other side is surely a number.
764
797
  const isSurelyNumber = (isWrittenAsNumber, operand) => !isBoolean(operand.type) &&
765
798
  (operand.type.kind === 'float' ||
766
799
  operand.type.kind === 'int64' ||
767
800
  isWrittenAsNumber);
768
- if ((source.op === '===' || source.op === '!==') &&
801
+ if ((source.operator === '===' || source.operator === '!==') &&
769
802
  ((isBoolean(left.type) && isSurelyNumber(source.rightIsNumber, right)) ||
770
803
  (isBoolean(right.type) && isSurelyNumber(source.leftIsNumber, left)))) {
771
- return boolConst(source.op === '!==');
804
+ return boolConst(source.operator === '!==');
772
805
  }
773
806
  return {
774
807
  kind: 'compare',
775
- op: cOperator,
808
+ operator: comparison,
776
809
  left,
777
810
  right,
778
811
  type: BOOL,
779
812
  };
780
813
  }
781
- throw new Error(`AOT: unsupported binary operator "${source.op}"`);
814
+ throw new Error(`AOT: unsupported binary operator "${source.operator}"`);
782
815
  }
783
816
  /**
784
817
  * Types `&&` / `||`. JS returns an operand, so with a 64-bit side the value is kept instead of collapsing it
@@ -796,30 +829,30 @@ function typeLogical(source, math64) {
796
829
  throw mix64Error();
797
830
  }
798
831
  if (left.type.kind === 'string' || right.type.kind === 'string') {
799
- 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}.');
832
+ throw aotError(`AOT: "${source.operator}" cannot mix a 64-bit time value with a string`, 'keep both sides numbers, or write the branch out: {ms ? ms : 0}.');
800
833
  }
801
834
  if (isBoolean(left.type) || isBoolean(right.type)) {
802
- throw bool64Error(`"${source.op}"`);
835
+ throw bool64Error(`"${source.operator}"`);
803
836
  }
804
837
  return {
805
838
  kind: 'pick',
806
- op: source.op,
839
+ operator: source.operator,
807
840
  left,
808
841
  right,
809
842
  type: int64Join(left.type, right.type),
810
843
  };
811
844
  }
812
- // Otherwise the C result is the truth of the expression, a boolean only when both operands are.
845
+ // Otherwise the result is the truth of the expression, a boolean only when both operands are.
813
846
  return {
814
847
  kind: 'logical',
815
- op: source.op,
848
+ operator: source.operator,
816
849
  left,
817
850
  right,
818
851
  type: isBoolean(left.type) && isBoolean(right.type) ? BOOL : INT,
819
852
  };
820
853
  }
821
854
  /**
822
- * Types `test ? consequent : alternate`. Both branches share one C slot: float or 64-bit if either is, and a
855
+ * Types `test ? consequent : alternate`. Both branches share one slot: float or 64-bit if either is, and a
823
856
  * 64-bit branch beside a float or a boolean one is refused.
824
857
  *
825
858
  * @param source The expression.
@@ -830,7 +863,7 @@ function typeLogical(source, math64) {
830
863
  function typeConditional(source, math64) {
831
864
  const test = typeSource(source.test, math64);
832
865
  const [consequent, alternate] = litPeers(typeSource(source.consequent, math64), typeSource(source.alternate, math64));
833
- // A string branch beside a numeric one is ill-typed C with no single printf spec, so refuse it here.
866
+ // A string branch beside a numeric one has no single type, so refuse it here.
834
867
  if ((consequent.type.kind === 'string') !==
835
868
  (alternate.type.kind === 'string')) {
836
869
  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'}.");
@@ -870,71 +903,81 @@ function typeConditional(source, math64) {
870
903
  * @returns The typed call.
871
904
  */
872
905
  function typeMath(source, math64) {
873
- const { fn } = source;
906
+ const { mathFunction } = source;
907
+ // Math.min and Math.max take any number of values, the IR's two: the rest go pairwise, left to right.
908
+ if ((mathFunction === 'min' || mathFunction === 'max') &&
909
+ source.callArguments.length > 2) {
910
+ const [first, second, ...rest] = source.callArguments;
911
+ return typeMath(rest.reduce((pairs, argument) => ({ ...source, callArguments: [pairs, argument] }), { ...source, callArguments: [first, second] }), math64);
912
+ }
874
913
  if (source.exactDivision) {
875
- const division = source.args[0];
876
- const timeDiv = typeTimeRoundDiv(fn, division, math64);
877
- if (timeDiv)
878
- return timeDiv;
879
- const intDiv = typeIntRoundDiv(fn, division, math64);
880
- if (intDiv)
881
- return intDiv;
882
- }
883
- let argExprs = litPeers(...source.args.map(arg => typeSource(arg, math64)));
884
- if (argExprs.some(argExpr => argExpr.type.kind === 'int64')) {
914
+ const division = source.callArguments[0];
915
+ const timeDivision = typeTimeRoundDiv(mathFunction, division, math64);
916
+ if (timeDivision)
917
+ return timeDivision;
918
+ const intDivision = typeIntRoundDiv(mathFunction, division, math64);
919
+ if (intDivision)
920
+ return intDivision;
921
+ }
922
+ let argumentExpressions = litPeers(...source.callArguments.map(argument => typeSource(argument, math64)));
923
+ if (argumentExpressions.some(argumentExpression => argumentExpression.type.kind === 'int64')) {
885
924
  // Whole-number Math keeps a 64-bit value exact, and a time takes nothing else; the rest works on floats.
886
- if (WHOLE_MATH.has(fn) || argExprs.some(isTime64)) {
887
- return typeMath64(fn, argExprs);
925
+ if (WHOLE_MATH.has(mathFunction) || argumentExpressions.some(isTime64)) {
926
+ return typeMath64(mathFunction, argumentExpressions);
888
927
  }
889
- argExprs = argExprs.map((argExpr) => argExpr.type.kind === 'int64'
890
- ? { kind: 'toFloat', operand: argExpr, type: FLOAT }
891
- : argExpr);
928
+ argumentExpressions = argumentExpressions.map((argumentExpression) => argumentExpression.type.kind === 'int64'
929
+ ? { kind: 'toFloat', operand: argumentExpression, type: FLOAT }
930
+ : argumentExpression);
892
931
  }
893
932
  // Keep int abs/min/max whole (a float rounds past 2^24); with math64, abs widens to keep |INT_MIN|.
894
- if (argExprs.length && argExprs.every(argExpr => isIntSlot(argExpr.type))) {
895
- if (fn === 'abs' && argExprs.length === 1) {
933
+ if (argumentExpressions.length &&
934
+ argumentExpressions.every(argumentExpression => isIntSlot(argumentExpression.type))) {
935
+ if (mathFunction === 'abs' && argumentExpressions.length === 1) {
896
936
  return math64
897
937
  ? {
898
938
  kind: 'helper',
899
939
  helper: 'abs',
900
940
  bits: 64,
901
- args: [argExprs[0]],
941
+ callArguments: [argumentExpressions[0]],
902
942
  type: INT64_MATH,
903
943
  }
904
944
  : {
905
945
  kind: 'helper',
906
946
  helper: 'abs',
907
947
  bits: 32,
908
- args: [argExprs[0]],
948
+ callArguments: [argumentExpressions[0]],
909
949
  type: INT,
910
950
  };
911
951
  }
912
- if ((fn === 'min' || fn === 'max') && argExprs.length === 2) {
952
+ if ((mathFunction === 'min' || mathFunction === 'max') &&
953
+ argumentExpressions.length === 2) {
913
954
  return {
914
955
  kind: 'helper',
915
- helper: fn,
956
+ helper: mathFunction,
916
957
  bits: 32,
917
- args: [argExprs[0], argExprs[1]],
958
+ callArguments: [argumentExpressions[0], argumentExpressions[1]],
918
959
  type: INT,
919
960
  };
920
961
  }
921
962
  }
922
- // Math.trunc stays an int: an int as is, a float via app_f2i (toward zero, NaN as 0, saturating).
923
- if (fn === 'trunc' && argExprs.length === 1) {
924
- return isIntSlot(argExprs[0].type)
925
- ? { kind: 'wholeRound', operand: argExprs[0], type: INT }
926
- : { kind: 'trunc', operand: argExprs[0], type: INT };
963
+ // Math.trunc stays an int: an int as is, a float truncated (toward zero, NaN as 0, saturating).
964
+ if (mathFunction === 'trunc' && argumentExpressions.length === 1) {
965
+ return isIntSlot(argumentExpressions[0].type)
966
+ ? { kind: 'wholeRound', operand: argumentExpressions[0], type: INT }
967
+ : { kind: 'trunc', operand: argumentExpressions[0], type: INT };
927
968
  }
928
- if (FLOAT_MATH_UNARY.has(fn) && argExprs.length === 1) {
969
+ if (FLOAT_MATH_UNARY.has(mathFunction) && argumentExpressions.length === 1) {
929
970
  // An int is already whole, so rounding leaves it as it is; a float round trip would lose digits.
930
- const roundsToWhole = fn === 'round' || fn === 'floor' || fn === 'ceil';
931
- if (roundsToWhole && isIntSlot(argExprs[0].type)) {
932
- return { kind: 'wholeRound', operand: argExprs[0], type: INT };
971
+ const roundsToWhole = mathFunction === 'round' ||
972
+ mathFunction === 'floor' ||
973
+ mathFunction === 'ceil';
974
+ if (roundsToWhole && isIntSlot(argumentExpressions[0].type)) {
975
+ return { kind: 'wholeRound', operand: argumentExpressions[0], type: INT };
933
976
  }
934
977
  const floatCall = {
935
978
  kind: 'floatMath',
936
- fn: fn,
937
- args: [argExprs[0]],
979
+ mathFunction: mathFunction,
980
+ callArguments: [argumentExpressions[0]],
938
981
  type: FLOAT,
939
982
  };
940
983
  // round/floor/ceil yield a whole number, kept as an int so %d / int assignments are correct.
@@ -942,16 +985,115 @@ function typeMath(source, math64) {
942
985
  ? { kind: 'toInt', operand: floatCall, type: INT }
943
986
  : floatCall;
944
987
  }
945
- if (FLOAT_MATH_BINARY.has(fn) && argExprs.length === 2) {
988
+ if (FLOAT_MATH_BINARY.has(mathFunction) && argumentExpressions.length === 2) {
946
989
  return {
947
990
  kind: 'floatMath',
948
- fn: fn,
949
- args: [argExprs[0], argExprs[1]],
991
+ mathFunction: mathFunction,
992
+ callArguments: [argumentExpressions[0], argumentExpressions[1]],
950
993
  type: FLOAT,
951
994
  };
952
995
  }
953
- throw new Error(`AOT: unsupported Math.${fn}(...) (arity ${argExprs.length})`);
996
+ throw new Error(`AOT: unsupported Math.${mathFunction}(...) (arity ${argumentExpressions.length})`);
997
+ }
998
+ /**
999
+ * A read of a local while slot widths are inferred, when the typing pass has yet to say what it holds: a local
1000
+ * is what it was set from, and a `let` what it was declared with or widened to, typed with the slots assumed so
1001
+ * far.
1002
+ *
1003
+ * @param local The local.
1004
+ *
1005
+ * @returns The typed read.
1006
+ */
1007
+ function assumedLocal(local) {
1008
+ const worked = assumedTypes.get(local);
1009
+ if (worked)
1010
+ return { kind: 'local', local, type: worked() };
1011
+ if (local.source)
1012
+ return typeSource(local.source, false);
1013
+ if (!local.assignable || !local.declared)
1014
+ return localRead(local);
1015
+ const declared = typeSource(local.declared, false);
1016
+ const width = declared.type.kind === 'int' ? assumedWide.get(local.assignable) : null;
1017
+ return {
1018
+ kind: 'local',
1019
+ local,
1020
+ type: !width ? declared.type : width === 'float' ? FLOAT : int64Of(width),
1021
+ };
1022
+ }
1023
+ /**
1024
+ * Says how a state or local the typing pass works out the type of is typed while it infers slot widths.
1025
+ *
1026
+ * @param slot The state or local.
1027
+ * @param type Its type, with the slots assumed so far.
1028
+ */
1029
+ export function assumeType(slot, type) {
1030
+ assumedTypes.set(slot, type);
954
1031
  }
1032
+ /**
1033
+ * The type a state or local is taken to have while slot widths are inferred (see assumeType).
1034
+ *
1035
+ * @param slot The state or local.
1036
+ *
1037
+ * @returns Its type, with the slots assumed so far.
1038
+ */
1039
+ export const assumedTypeOf = (slot) => assumedTypes.get(slot)();
1040
+ /**
1041
+ * The shape of a scalar state's value.
1042
+ *
1043
+ * @param state The state.
1044
+ *
1045
+ * @returns The shape.
1046
+ */
1047
+ export const stateShape = (state) => state.isBoolean ? 'bool' : localShape(state);
1048
+ /**
1049
+ * Whether a state's type is settled where it is declared: only a whole-number slot widens.
1050
+ *
1051
+ * @param state The state.
1052
+ *
1053
+ * @returns True for a string, a boolean or a float.
1054
+ */
1055
+ const isSettledState = (state) => state.isBoolean ||
1056
+ (!holdsUntyped(state) &&
1057
+ (state.slotKind === 'string' || state.slotKind === 'float'));
1058
+ /**
1059
+ * A read of a scalar state's value, typed once the slot's width is known.
1060
+ *
1061
+ * @param state The state.
1062
+ * @param latest It reads the value a setter left, not the render's.
1063
+ *
1064
+ * @returns The read.
1065
+ */
1066
+ export function stateRead(state, latest = false) {
1067
+ const source = {
1068
+ kind: 'state',
1069
+ state,
1070
+ ...(latest ? { latest: true } : {}),
1071
+ location: undefined,
1072
+ };
1073
+ return isSettledState(state)
1074
+ ? typeSource(source, false)
1075
+ : typedLater(stateShape(state), () => typeSource(source, false), source);
1076
+ }
1077
+ /**
1078
+ * Whether a state or ref slot holds 64 bits, counting the slots the typing pass assumes to while it infers
1079
+ * widths.
1080
+ *
1081
+ * @param slot The state or ref.
1082
+ *
1083
+ * @returns True for a 64-bit slot.
1084
+ */
1085
+ export const is64BitSlot = (slot) => slot.slotKind === 'i64' ||
1086
+ (slot.slotKind === 'int' &&
1087
+ wideSlotOf(assumedWide, slot.slotName) !== undefined);
1088
+ /**
1089
+ * Whether a `let` holds 64 bits (see is64BitSlot).
1090
+ *
1091
+ * @param local The local.
1092
+ *
1093
+ * @returns True for a 64-bit local.
1094
+ */
1095
+ export const is64BitLocal = (local) => (assumedWide ? assumedLocal(local).type : typeOfSlotValue(local)).kind ===
1096
+ 'int64';
955
1097
  /**
956
1098
  * The typing pass over one source expression: gives it its type and decides how it is computed. Pure, so a
957
1099
  * subexpression can be typed again, as whole-number math beside a 64-bit value is. An AOT error is pinned to
@@ -975,24 +1117,35 @@ export function typeSource(source, math64) {
975
1117
  return boolConst(source.value);
976
1118
  case 'state': {
977
1119
  const { state } = source;
978
- const assumed = (state.cType === 'int' || state.cType === 'i64') && !state.isBool
979
- ? assumedWide?.get(state.cField)
1120
+ const worked = assumedWide ? assumedTypes.get(state) : undefined;
1121
+ if (worked) {
1122
+ return {
1123
+ kind: 'state',
1124
+ state,
1125
+ type: worked(),
1126
+ ...(source.latest ? { latest: true } : {}),
1127
+ };
1128
+ }
1129
+ const assumed = (state.slotKind === 'int' || state.slotKind === 'i64') &&
1130
+ !state.isBoolean
1131
+ ? wideSlotOf(assumedWide, state.slotName)
980
1132
  : undefined;
981
1133
  return {
982
1134
  kind: 'state',
983
1135
  state,
984
1136
  type: assumed ? int64Of(assumed) : stateType(state),
1137
+ ...(source.latest ? { latest: true } : {}),
985
1138
  };
986
1139
  }
987
1140
  case 'local':
988
- // While slot widths are inferred, a local is what it was set from, typed with the slots assumed so far.
989
- return assumedWide && source.local.source
990
- ? typeSource(source.local.source, false)
1141
+ return assumedWide
1142
+ ? assumedLocal(source.local)
991
1143
  : localRead(source.local);
992
1144
  case 'ref': {
993
1145
  const { ref } = source;
994
- const assumed = ref.kind === 'value' && (ref.cType === 'int' || ref.cType === 'i64')
995
- ? assumedWide?.get(ref.cVar)
1146
+ const assumed = ref.kind === 'value' &&
1147
+ (ref.slotKind === 'int' || ref.slotKind === 'i64')
1148
+ ? wideSlotOf(assumedWide, ref.slotName)
996
1149
  : undefined;
997
1150
  return {
998
1151
  kind: 'ref',
@@ -1001,7 +1154,7 @@ export function typeSource(source, math64) {
1001
1154
  };
1002
1155
  }
1003
1156
  case 'fixed':
1004
- return source.expr;
1157
+ return source.expression;
1005
1158
  case 'unary':
1006
1159
  return typeUnary(source, wide);
1007
1160
  case 'binary':
@@ -1015,15 +1168,15 @@ export function typeSource(source, math64) {
1015
1168
  }
1016
1169
  }
1017
1170
  catch (error) {
1018
- locateError(error, source.loc);
1171
+ locateError(error, source.location);
1019
1172
  throw error;
1020
1173
  }
1021
1174
  }
1022
1175
  /**
1023
1176
  * Infers the slots that have to hold 64 bits: an int slot a value stored into is a 64-bit number, once the
1024
1177
  * slots found so far are taken to hold 64 bits too, until no more are found. Each one holds a time when a time
1025
- * is stored into it, and only 64-bit numbers otherwise. A value whose typing fails leaves its slot as it is;
1026
- * lowering it again reports the error.
1178
+ * is stored into it, and only 64-bit numbers otherwise. A `let` local given a fraction holds a float instead. A
1179
+ * value whose typing fails leaves its slot as it is; lowering it again reports the error.
1027
1180
  *
1028
1181
  * @param stores Every value lowering stored into an int slot, or into a 64-bit one that holds no time yet.
1029
1182
  * @param wide The slots already 64-bit.
@@ -1036,11 +1189,24 @@ export function inferWideSlots(stores, wide) {
1036
1189
  while (grew) {
1037
1190
  grew = false;
1038
1191
  for (const store of stores) {
1039
- if (inferred.get(store.slot) === 'time')
1192
+ const width = inferred.get(store.slot);
1193
+ if (width === 'time' || width === 'float')
1040
1194
  continue;
1041
1195
  assumedWide = inferred;
1042
1196
  try {
1043
- const { type } = typeSource(store.value, store.math64);
1197
+ // Only a `let` that holds whole numbers widens.
1198
+ if (store.local) {
1199
+ const held = assumedLocal(store.local).type;
1200
+ if (held.kind !== 'int' && held !== INT64_NUMBER)
1201
+ continue;
1202
+ }
1203
+ const { type } = typeSource(store.value, store.math64?.() ?? false);
1204
+ // A `let` given a fraction holds floats.
1205
+ if (store.local && type.kind === 'float') {
1206
+ inferred.set(store.slot, 'float');
1207
+ grew = true;
1208
+ continue;
1209
+ }
1044
1210
  if (type.kind !== 'int64')
1045
1211
  continue;
1046
1212
  const holds = type.source === 'time' ? 'time' : 'number';
@@ -1049,8 +1215,11 @@ export function inferWideSlots(stores, wide) {
1049
1215
  grew = true;
1050
1216
  }
1051
1217
  }
1052
- catch {
1053
- // Lowering the value again, with the widths inferred, reports its error.
1218
+ catch (error) {
1219
+ // The typing pass reports its error, with the widths inferred.
1220
+ if (String(error?.message).startsWith('AOT internal')) {
1221
+ throw error;
1222
+ }
1054
1223
  }
1055
1224
  finally {
1056
1225
  assumedWide = null;
@@ -1059,49 +1228,44 @@ export function inferWideSlots(stores, wide) {
1059
1228
  }
1060
1229
  return inferred;
1061
1230
  }
1062
- /**
1063
- * Whether two sets of slot widths are the same.
1064
- *
1065
- * @param a One set.
1066
- * @param b The other.
1067
- *
1068
- * @returns True when every slot holds the same in both.
1069
- */
1070
- export const sameSlotWidths = (a, b) => a.size === b.size && [...a].every(([slot, holds]) => b.get(slot) === holds);
1071
1231
  /**
1072
1232
  * Whether an operand is written as a number, so a boolean on the other side of `===` never equals it: a
1073
1233
  * numeric literal, a negated one, or a non-boolean state read by name.
1074
1234
  *
1075
1235
  * @param node The operand.
1076
- * @param env The expression environment.
1236
+ * @param environment The expression environment.
1077
1237
  *
1078
1238
  * @returns True when it is surely a number.
1079
1239
  */
1080
- const isWrittenAsNumber = (node, env) => node.type === 'NumericLiteral' ||
1240
+ const isWrittenAsNumber = (node, environment) => node.type === 'NumericLiteral' ||
1081
1241
  (node.type === 'UnaryExpression' &&
1082
1242
  node.argument.type === 'NumericLiteral') ||
1083
1243
  (node.type === 'Identifier' &&
1084
- !env.locals.has(node.name) &&
1085
- env.state.get(node.name)?.isBool === false);
1244
+ !environment.locals.has(node.name) &&
1245
+ environment.state.get(node.name)?.isBoolean ===
1246
+ false);
1086
1247
  /**
1087
1248
  * A binary expression's source, from its operands' sources.
1088
1249
  *
1089
1250
  * @param node The expression.
1090
1251
  * @param left Its left operand's source.
1091
1252
  * @param right Its right operand's source.
1092
- * @param env The expression environment.
1253
+ * @param environment The expression environment.
1093
1254
  *
1094
1255
  * @returns The source.
1095
1256
  */
1096
- const binarySource = (node, left, right, env) => ({
1257
+ export const binarySource = (node, left, right, environment) => ({
1097
1258
  kind: 'binary',
1098
- op: node.operator,
1259
+ operator: node.operator,
1099
1260
  left,
1100
1261
  right,
1101
- divisor: { constant: staticInt(node.right, env), loc: node.right.loc?.start },
1102
- leftIsNumber: isWrittenAsNumber(node.left, env),
1103
- rightIsNumber: isWrittenAsNumber(node.right, env),
1104
- loc: node.loc?.start,
1262
+ divisor: {
1263
+ constant: staticInt(node.right, environment),
1264
+ location: node.right.loc?.start,
1265
+ },
1266
+ leftIsNumber: isWrittenAsNumber(node.left, environment),
1267
+ rightIsNumber: isWrittenAsNumber(node.right, environment),
1268
+ location: node.loc?.start,
1105
1269
  });
1106
1270
  /**
1107
1271
  * Whether `node` is the handler's event, or its `nativeEvent` as React Native code reads it.
@@ -1122,123 +1286,637 @@ function isEventRoot(node, event) {
1122
1286
  node.object.name === event &&
1123
1287
  node.property.name === 'nativeEvent');
1124
1288
  }
1289
+ /**
1290
+ * The type a list item's field reads as.
1291
+ *
1292
+ * @param field The field.
1293
+ *
1294
+ * @returns Its type.
1295
+ */
1296
+ export const fieldType = (field) => field.kind === 'bool' ? BOOL : typeOfSlot(field.kind);
1297
+ /**
1298
+ * A member's key when it is a name: `a.b`, or `a['b']`.
1299
+ *
1300
+ * @param node The member.
1301
+ *
1302
+ * @returns The key, or null for a computed one.
1303
+ */
1304
+ function memberKey(node) {
1305
+ if (!node.computed)
1306
+ return node.property.name;
1307
+ return node.property.type === 'StringLiteral' ? node.property.value : null;
1308
+ }
1309
+ /**
1310
+ * Whether a value holds a value worked out at run time, at any depth.
1311
+ *
1312
+ * @param value The value.
1313
+ *
1314
+ * @returns Whether it does.
1315
+ */
1316
+ const holdsRuntime = (value) => value instanceof RuntimeLeaf ||
1317
+ ((Array.isArray(value) || isPlainObject(value)) &&
1318
+ Object.values(value).some(holdsRuntime));
1319
+ /**
1320
+ * A constant array read by a runtime index, kept as a list whose rows are set at boot and never change.
1321
+ *
1322
+ * @param array The array.
1323
+ * @param node What names it, for its name and errors.
1324
+ * @param environment The expression environment.
1325
+ *
1326
+ * @returns The list.
1327
+ */
1328
+ export function constantListOf(array, node, environment) {
1329
+ const lists = environment.constantLists;
1330
+ if (!lists) {
1331
+ throw new Error('AOT internal: no table for constant lists');
1332
+ }
1333
+ const known = lists.get(array);
1334
+ if (known)
1335
+ return known;
1336
+ if (holdsRuntime(array)) {
1337
+ throw aotError('AOT: an array built from runtime values cannot be read by a runtime index', 'index a constant array or a list state, or read a fixed element: rows[0].value.');
1338
+ }
1339
+ const name = node.type === 'Identifier' ? node.name : 'array';
1340
+ if (array.length > MAX_LIST_CAPACITY) {
1341
+ throw aotError(`AOT: the array "${name}" has ${array.length} elements, but an array read by a runtime index holds ${MAX_LIST_CAPACITY}`, 'split it into smaller arrays, or index a list state.');
1342
+ }
1343
+ const list = {
1344
+ kind: 'list',
1345
+ name,
1346
+ slotName: `k${lists.size}_${name}`,
1347
+ setter: undefined,
1348
+ struct: inferItemStruct(array, `the array "${name}"`),
1349
+ items: array,
1350
+ capacity: array.length,
1351
+ constant: true,
1352
+ initialAt: node.loc?.start,
1353
+ };
1354
+ lists.set(array, list);
1355
+ return list;
1356
+ }
1357
+ /**
1358
+ * The list a computed member reads a row of by a runtime index: a list state, or a constant array. A constant
1359
+ * array's element at a constant index folds instead.
1360
+ *
1361
+ * @param node The member.
1362
+ * @param environment The expression environment.
1363
+ *
1364
+ * @returns The list, or null when it is neither.
1365
+ */
1366
+ function indexedListOf(node, environment) {
1367
+ return listValueOf(node.object, environment, node.property);
1368
+ }
1369
+ /**
1370
+ * The list an expression names: a list state, a list worked out in render, or a constant array.
1371
+ *
1372
+ * @param node The expression.
1373
+ * @param environment The expression environment.
1374
+ * @param index The index it is read by, when a constant one folds the read instead.
1375
+ *
1376
+ * @returns The list, or null when it is none.
1377
+ */
1378
+ export function listValueOf(node, environment, index) {
1379
+ // A local hides a state of the same name.
1380
+ if (node.type === 'Identifier' && environment.locals.has(node.name)) {
1381
+ return null;
1382
+ }
1383
+ if (node.type === 'Identifier' && environment.state.has(node.name)) {
1384
+ const record = environment.state.get(node.name);
1385
+ return record.kind === 'list' ? record : null;
1386
+ }
1387
+ const derived = derivedListOf(node, environment);
1388
+ if (derived)
1389
+ return derived;
1390
+ const scope = foldScope(environment, environment.constants ?? {});
1391
+ const folds = (part) => {
1392
+ try {
1393
+ return { value: evalStatic(part, scope, 'boot') };
1394
+ }
1395
+ catch (error) {
1396
+ rethrowFoldLimit(error);
1397
+ return null;
1398
+ }
1399
+ };
1400
+ if (index && folds(index))
1401
+ return null;
1402
+ const array = folds(node)?.value;
1403
+ return Array.isArray(array) ? constantListOf(array, node, environment) : null;
1404
+ }
1405
+ /**
1406
+ * What a member chain reads in a list item: a row's item (`item.pos.x`), a row by index (`items[i].title`), or a
1407
+ * plain value by index (`values[i]`). `?.` after an index reads undefined past the list's end.
1408
+ *
1409
+ * @param node The expression.
1410
+ * @param environment The expression environment.
1411
+ *
1412
+ * @returns The item and the path under it, or null when it reads no list item.
1413
+ */
1414
+ function itemPathOf(node, environment) {
1415
+ if (node.type === 'TSNonNullExpression') {
1416
+ return itemPathOf(node.expression, environment);
1417
+ }
1418
+ if (node.type === 'Identifier') {
1419
+ const local = environment.locals.get(node.name);
1420
+ return local?.struct && local.list ? { item: local, path: [] } : null;
1421
+ }
1422
+ if (node.type !== 'MemberExpression' &&
1423
+ node.type !== 'OptionalMemberExpression') {
1424
+ return null;
1425
+ }
1426
+ const key = memberKey(node);
1427
+ if (key !== null) {
1428
+ const base = itemPathOf(node.object, environment);
1429
+ if (!base)
1430
+ return null;
1431
+ const guards = node.optional && !base.path.length && base.item.index !== undefined;
1432
+ return {
1433
+ item: guards ? { ...base.item, guarded: true } : base.item,
1434
+ path: [...base.path, key],
1435
+ };
1436
+ }
1437
+ const list = indexedListOf(node, environment);
1438
+ if (!list)
1439
+ return null;
1440
+ const index = lowerExpr(node.property, environment);
1441
+ whenTyped(() => {
1442
+ if (index.type.kind !== 'int') {
1443
+ throw aotError(`AOT: an index into "${list.name}" must be a whole number`, 'an index is an int: Math.floor(x) or a whole-number state.');
1444
+ }
1445
+ });
1446
+ // A plain value past the end is undefined; a field of an item there throws in JS, and faults here.
1447
+ const item = rowItemOf(list, { name: `${list.name}[]`, index });
1448
+ return {
1449
+ item: { ...item, guarded: !!item.struct.plain },
1450
+ path: [],
1451
+ };
1452
+ }
1453
+ /**
1454
+ * The source of a read into a list item: a field, or whether an object of fields (or the item) is there, as
1455
+ * an object is truthy.
1456
+ *
1457
+ * @param itemPath The read.
1458
+ * @param location Where it is.
1459
+ *
1460
+ * @returns The source.
1461
+ */
1462
+ function itemSource({ item, path }, location) {
1463
+ const struct = item.struct;
1464
+ const key = path.join('.');
1465
+ const field = struct.fields.find(entry => entry.key === key);
1466
+ if (field && (path.length || struct.plain)) {
1467
+ return {
1468
+ kind: 'fixed',
1469
+ expression: { kind: 'itemField', item, field, type: fieldType(field) },
1470
+ location,
1471
+ };
1472
+ }
1473
+ const fields = path.length ? fieldsUnder(struct, path) : [];
1474
+ if (path.length && !fields.length) {
1475
+ throw new Error(`AOT: unknown field "${key}" on a list item`);
1476
+ }
1477
+ return {
1478
+ kind: 'fixed',
1479
+ expression: { kind: 'itemPresent', item, fields, type: BOOL },
1480
+ location,
1481
+ };
1482
+ }
1483
+ /**
1484
+ * The row of a list a whole item names, `items[i]`, for passing to a component.
1485
+ *
1486
+ * @param node The expression.
1487
+ * @param environment The expression environment.
1488
+ *
1489
+ * @returns The item, or null when it names none.
1490
+ */
1491
+ export function listItemOf(node, environment) {
1492
+ if (node.type !== 'MemberExpression' || !node.computed)
1493
+ return null;
1494
+ const itemPath = itemPathOf(node, environment);
1495
+ return itemPath && !itemPath.item.struct.plain ? itemPath.item : null;
1496
+ }
1497
+ /**
1498
+ * Whether a value is there, where it can be missing: a list item's field, an object of fields or an item, or a
1499
+ * local that stands for a field read.
1500
+ *
1501
+ * @param node The expression.
1502
+ * @param environment The expression environment.
1503
+ *
1504
+ * @returns A boolean expression, or null when the value is always there.
1505
+ */
1506
+ function presenceOf(node, environment) {
1507
+ const itemPath = itemPathOf(node, environment);
1508
+ if (itemPath) {
1509
+ const read = itemSource(itemPath, undefined);
1510
+ const { expression } = read;
1511
+ return expression.kind === 'itemField'
1512
+ ? {
1513
+ kind: 'itemPresent',
1514
+ item: expression.item,
1515
+ fields: [expression.field],
1516
+ type: BOOL,
1517
+ }
1518
+ : expression;
1519
+ }
1520
+ if (node.type === 'Identifier' && environment.locals.has(node.name)) {
1521
+ const local = environment.locals.get(node.name);
1522
+ const read = local.expression ? itemReadOf(local.expression) : null;
1523
+ if (read) {
1524
+ return {
1525
+ kind: 'itemPresent',
1526
+ item: read.item,
1527
+ fields: [read.field],
1528
+ type: BOOL,
1529
+ };
1530
+ }
1531
+ }
1532
+ return null;
1533
+ }
1534
+ /**
1535
+ * Whether an expression is null or undefined, as a constant.
1536
+ *
1537
+ * @param node The expression.
1538
+ * @param environment The expression environment.
1539
+ *
1540
+ * @returns Whether it is.
1541
+ */
1542
+ function isNullish(node, environment) {
1543
+ if (node.type === 'Identifier' && node.name === 'undefined')
1544
+ return true;
1545
+ try {
1546
+ return (evalStatic(node, foldScope(environment, environment.constants ?? {})) ==
1547
+ null);
1548
+ }
1549
+ catch (error) {
1550
+ rethrowFoldLimit(error);
1551
+ return false;
1552
+ }
1553
+ }
1554
+ /**
1555
+ * `x === undefined`, `x !== undefined`, `x == null` and `x != null` (either way round) on a value that can be
1556
+ * missing: whether it is there.
1557
+ *
1558
+ * @param node The comparison.
1559
+ * @param environment The expression environment.
1560
+ *
1561
+ * @returns A boolean expression, or null when it is no such test.
1562
+ */
1563
+ function presenceTestOf(node, environment) {
1564
+ const { operator } = node;
1565
+ if (!['==', '!=', '===', '!=='].includes(operator))
1566
+ return null;
1567
+ const isUndefined = (side) => side.type === 'Identifier' && side.name === 'undefined';
1568
+ const matches = (side) => isUndefined(side) ||
1569
+ ((operator === '==' || operator === '!=') && side.type === 'NullLiteral');
1570
+ const value = matches(node.right)
1571
+ ? node.left
1572
+ : matches(node.left)
1573
+ ? node.right
1574
+ : null;
1575
+ if (!value || value.type === 'PrivateName')
1576
+ return null;
1577
+ const present = presenceOf(value, environment);
1578
+ if (!present)
1579
+ return null;
1580
+ return operator === '!=' || operator === '!=='
1581
+ ? present
1582
+ : { kind: 'unary', operator: '!', operand: present, type: BOOL };
1583
+ }
1584
+ /**
1585
+ * The local a member reads when it names a value worked out at run time in an array or object built in render.
1586
+ *
1587
+ * @param node The member.
1588
+ * @param environment The expression environment.
1589
+ *
1590
+ * @returns The local, or null.
1591
+ */
1592
+ function runtimeLeafOf(node, environment) {
1593
+ const key = memberKey(node);
1594
+ const scope = foldScope(environment, environment.constants ?? {});
1595
+ let container;
1596
+ let index = key;
1597
+ try {
1598
+ container = evalStatic(node.object, scope, 'boot');
1599
+ if (key === null) {
1600
+ index = evalStatic(node.property, scope);
1601
+ }
1602
+ }
1603
+ catch (error) {
1604
+ rethrowFoldLimit(error);
1605
+ return null;
1606
+ }
1607
+ const value = typeof container === 'object' && container !== null
1608
+ ? container[index]
1609
+ : undefined;
1610
+ if (value instanceof HiddenField)
1611
+ throw value.error();
1612
+ return value instanceof RuntimeLeaf ? value.local : null;
1613
+ }
1614
+ /**
1615
+ * Folds an array or object built in render: what folds stays a constant, and each value worked out at run time
1616
+ * becomes a RuntimeLeaf, so a `.map` over it unrolls and its constant fields still fold.
1617
+ *
1618
+ * @param node The expression.
1619
+ * @param environment The expression environment.
1620
+ * @param scope The constants it folds against.
1621
+ *
1622
+ * @returns The value.
1623
+ */
1624
+ export function foldRuntime(node, environment, scope = environment.constants ?? {}) {
1625
+ try {
1626
+ return evalStatic(node, scope, 'boot');
1627
+ }
1628
+ catch (error) {
1629
+ rethrowFoldLimit(error);
1630
+ }
1631
+ if (node.type === 'ArrayExpression') {
1632
+ return node.elements.map(element => {
1633
+ if (!element || element.type === 'SpreadElement') {
1634
+ throw aotError('AOT: an array built in render cannot have holes or spreads', 'write each element out.');
1635
+ }
1636
+ return foldRuntime(element, environment, scope);
1637
+ });
1638
+ }
1639
+ if (node.type === 'ObjectExpression') {
1640
+ const folded = {};
1641
+ for (const property of node.properties) {
1642
+ if (property.type === 'SpreadElement') {
1643
+ const spread = foldRuntime(property.argument, environment, scope);
1644
+ if (!isObjectTree(spread)) {
1645
+ throw aotError('AOT: only an object can be spread into an object', 'spread an object state or an object built from fields: {...p, x: 1}.');
1646
+ }
1647
+ Object.assign(folded, spread);
1648
+ continue;
1649
+ }
1650
+ if (property.type !== 'ObjectProperty' || property.computed) {
1651
+ throw aotError('AOT: an object built in render must be plain fields', 'write each field out: {label: "A", value: n}. Methods and computed keys are not lowered.');
1652
+ }
1653
+ const key = property.key.name ??
1654
+ String(property.key.value);
1655
+ folded[key] = foldRuntime(property.value, environment, scope);
1656
+ }
1657
+ return folded;
1658
+ }
1659
+ return new RuntimeLeaf(lowerLocal(node, environment));
1660
+ }
1661
+ /**
1662
+ * Binds the names an object pattern destructures from an object built in render.
1663
+ *
1664
+ * @param pattern The pattern.
1665
+ * @param value The object.
1666
+ * @param environment The expression environment; the bindings go into its constants.
1667
+ */
1668
+ function bindPattern(pattern, value, environment) {
1669
+ const taken = new Set();
1670
+ for (const property of pattern.properties) {
1671
+ if (property.type === 'RestElement') {
1672
+ if (property.argument.type !== 'Identifier') {
1673
+ throw aotError('AOT: a rest element must be a plain name');
1674
+ }
1675
+ setBinding(environment.constants, property.argument.name, Object.fromEntries(Object.entries(value).filter(([key]) => !taken.has(key))));
1676
+ continue;
1677
+ }
1678
+ const key = propertyKey(property);
1679
+ if (!Object.hasOwn(value, key)) {
1680
+ throw aotError(`AOT: the object has no field "${key}" to destructure`, 'destructure only the fields the object holds, by name.');
1681
+ }
1682
+ taken.add(key);
1683
+ const field = value[key];
1684
+ if (property.value.type === 'Identifier') {
1685
+ setBinding(environment.constants, property.value.name, field);
1686
+ }
1687
+ else if (property.value.type === 'ObjectPattern' && isObjectTree(field)) {
1688
+ bindPattern(property.value, field, environment);
1689
+ }
1690
+ else {
1691
+ throw aotError('AOT: a destructured field must be a plain name or a nested object pattern', 'defaults never apply, since every field holds a value; drop the `= …`.');
1692
+ }
1693
+ }
1694
+ }
1695
+ /**
1696
+ * Whether every name an object pattern takes is bound already.
1697
+ *
1698
+ * @param pattern The pattern.
1699
+ * @param scope The constants in reach.
1700
+ *
1701
+ * @returns True when each is.
1702
+ */
1703
+ function isPatternBound(pattern, scope) {
1704
+ return pattern.properties.every(property => {
1705
+ if (property.type === 'RestElement')
1706
+ return false;
1707
+ const { value } = property;
1708
+ if (value.type === 'Identifier')
1709
+ return hasBinding(scope, value.name);
1710
+ return value.type === 'ObjectPattern' && isPatternBound(value, scope);
1711
+ });
1712
+ }
1713
+ /**
1714
+ * Binds each `const` of a component body that builds an array or object in render from runtime values, as
1715
+ * foldRuntime folds it. A const that folds is bound already, and a hook's binding is not a literal.
1716
+ *
1717
+ * @param body The component's body.
1718
+ * @param environment Its expression environment; the bindings go into its constants.
1719
+ */
1720
+ export function bindBuiltValues(body, environment) {
1721
+ const scope = environment.constants;
1722
+ for (const statement of body) {
1723
+ if (statement.type !== 'VariableDeclaration' ||
1724
+ statement.kind !== 'const') {
1725
+ continue;
1726
+ }
1727
+ for (const declarator of statement.declarations) {
1728
+ const { id, init } = declarator;
1729
+ if (isContextRead(init))
1730
+ continue; // bound from its provider (see bindContextUses)
1731
+ if (id.type === 'ObjectPattern' && init) {
1732
+ if (isPatternBound(id, scope))
1733
+ continue; // folded already
1734
+ const value = foldRuntime(init, environment, scope);
1735
+ if (!isObjectTree(value)) {
1736
+ throw aotError('AOT: only an object can be destructured', 'destructure an object state, or an object built from fields.');
1737
+ }
1738
+ bindPattern(id, value, environment);
1739
+ continue;
1740
+ }
1741
+ if (id.type !== 'Identifier' ||
1742
+ (init?.type !== 'ArrayExpression' &&
1743
+ init?.type !== 'ObjectExpression') ||
1744
+ hasBinding(scope, id.name) ||
1745
+ environment.locals.has(id.name)) {
1746
+ continue;
1747
+ }
1748
+ setBinding(scope, id.name, foldRuntime(init, environment, scope));
1749
+ }
1750
+ }
1751
+ }
1125
1752
  /**
1126
1753
  * Lowers one JS expression to its source: names resolved, constants folded, and each operand lowered and typed
1127
1754
  * in turn, so an error in it is reported before anything after it.
1128
1755
  *
1129
1756
  * @param node The expression.
1130
- * @param env The expression environment.
1757
+ * @param environment The expression environment.
1131
1758
  *
1132
1759
  * @returns The source.
1133
1760
  */
1134
- function sourceOf(node, env) {
1135
- const loc = node.loc?.start;
1761
+ function sourceOf(node, environment) {
1762
+ const location = node.loc?.start;
1136
1763
  // An expression that depends only on the panel is read from a slot worked out at boot, in doubles as JS.
1137
1764
  const whole = WHOLE_BOOT_TYPES.has(node.type)
1138
- ? wholeBootSource(node, env, loc)
1765
+ ? wholeBootSource(node, environment, location)
1139
1766
  : null;
1140
1767
  if (whole)
1141
1768
  return whole;
1142
- const operand = (operandNode) => lowerSource(operandNode, env).source;
1769
+ const operand = (operandNode) => lowerSource(operandNode, environment).source;
1143
1770
  switch (node.type) {
1144
1771
  case 'NumericLiteral':
1145
- return numberSource(node.value, loc);
1772
+ return numberSource(node.value, location);
1146
1773
  case 'StringLiteral':
1147
- return { kind: 'string', value: node.value, loc };
1774
+ return { kind: 'string', value: node.value, location };
1148
1775
  case 'BooleanLiteral':
1149
- return { kind: 'boolean', value: node.value, loc };
1776
+ return { kind: 'boolean', value: node.value, location };
1150
1777
  case 'Identifier': {
1151
1778
  // A name resolves to a local first, then to state, then to a compile-time constant.
1152
- if (env.locals.has(node.name)) {
1153
- return { kind: 'local', local: env.locals.get(node.name), loc };
1779
+ if (environment.locals.has(node.name)) {
1780
+ const local = environment.locals.get(node.name);
1781
+ // An item of a list of plain values is its one field.
1782
+ if (local.struct?.plain && local.list) {
1783
+ return itemSource({ item: local, path: [] }, location);
1784
+ }
1785
+ return { kind: 'local', local, location };
1154
1786
  }
1155
- if (env.state.has(node.name)) {
1156
- const stateRecord = env.state.get(node.name);
1787
+ if (environment.state.has(node.name)) {
1788
+ const stateRecord = environment.state.get(node.name);
1157
1789
  if (stateRecord.kind === 'list') {
1158
- throw new Error(`AOT: a list state ("${node.name}") can only be used via .length or .map`);
1790
+ throw new Error(`AOT: a list state ("${node.name}") can only be used via .length, .map or [index]`);
1159
1791
  }
1160
- return { kind: 'state', state: stateRecord, loc };
1792
+ return { kind: 'state', state: stateRecord, location };
1161
1793
  }
1162
- if (hasBinding(env.consts, node.name)) {
1163
- const constValue = env.consts[node.name];
1164
- if (isBoot(constValue))
1165
- return bootSource(constValue, loc);
1166
- if (typeof constValue === 'number')
1167
- return numberSource(constValue, loc);
1168
- if (typeof constValue === 'string') {
1169
- return { kind: 'string', value: constValue, loc };
1794
+ if (hasBinding(environment.constants, node.name)) {
1795
+ const constantValue = environment.constants[node.name];
1796
+ if (constantValue instanceof RuntimeLeaf) {
1797
+ return { kind: 'local', local: constantValue.local, location };
1170
1798
  }
1171
- if (typeof constValue === 'boolean') {
1172
- return { kind: 'boolean', value: constValue, loc };
1799
+ if (constantValue instanceof HiddenField)
1800
+ throw constantValue.error();
1801
+ if (isBoot(constantValue))
1802
+ return bootSource(constantValue, location);
1803
+ if (typeof constantValue === 'number')
1804
+ return numberSource(constantValue, location);
1805
+ if (typeof constantValue === 'string') {
1806
+ return { kind: 'string', value: constantValue, location };
1807
+ }
1808
+ if (typeof constantValue === 'boolean') {
1809
+ return { kind: 'boolean', value: constantValue, location };
1810
+ }
1811
+ if (isObjectTree(constantValue)) {
1812
+ throw aotError(`AOT: "${node.name}" is an object, which can't be used as a value here`, `read one of its fields: ${node.name}.${Object.keys(constantValue)[0] ?? 'field'}.`);
1173
1813
  }
1174
1814
  }
1815
+ if (readsNativeModule(node.name, environment)) {
1816
+ throw aotError(`AOT: the native module ${node.name} can only have its methods called`, `call a method of it, as in ${node.name}.read(0); it isn't a value to keep or pass on.`);
1817
+ }
1175
1818
  throw new Error(`AOT: cannot resolve identifier "${node.name}" in a dynamic expression`);
1176
1819
  }
1177
1820
  case 'UnaryExpression': {
1178
1821
  // A constant is negated here, so `-A` is its value, and -2147483648 is not an int overflow.
1179
- const staticOperand = node.operator === '-' ? staticInt(node.argument, env) : null;
1822
+ const staticOperand = node.operator === '-' ? staticInt(node.argument, environment) : null;
1180
1823
  if (staticOperand !== null)
1181
- return numberSource(-staticOperand, loc);
1824
+ return numberSource(-staticOperand, location);
1182
1825
  const operandSource = operand(node.argument);
1183
1826
  if (node.operator === '-' ||
1184
1827
  node.operator === '+' ||
1185
1828
  node.operator === '!') {
1186
- return { kind: 'unary', op: node.operator, operand: operandSource, loc };
1829
+ return {
1830
+ kind: 'unary',
1831
+ operator: node.operator,
1832
+ operand: operandSource,
1833
+ location,
1834
+ };
1187
1835
  }
1188
1836
  throw new Error(`AOT: unsupported unary operator "${node.operator}"`);
1189
1837
  }
1190
1838
  case 'BinaryExpression': {
1839
+ // `s.kind === 'busy'`: a test of a tagged object's hidden tag.
1840
+ const tagTest = tagTestOf(node, environment);
1841
+ if (tagTest) {
1842
+ return { kind: 'fixed', expression: lowerTagTest(tagTest), location };
1843
+ }
1844
+ // `field === undefined`, `field != null` …: whether a list item's field is there.
1845
+ const presenceTest = presenceTestOf(node, environment);
1846
+ if (presenceTest) {
1847
+ return { kind: 'fixed', expression: presenceTest, location };
1848
+ }
1191
1849
  // Fold `+ - *` over two whole-number constants as JS would, so a product past int range stays exact.
1192
- const leftConst = CHECKED_HELPER[node.operator]
1193
- ? staticInt(node.left, env)
1850
+ const leftConstant = CHECKED_HELPER[node.operator]
1851
+ ? staticInt(node.left, environment)
1194
1852
  : null;
1195
- const rightConst = leftConst === null ? null : staticInt(node.right, env);
1196
- if (rightConst !== null) {
1853
+ const rightConstant = leftConstant === null ? null : staticInt(node.right, environment);
1854
+ if (rightConstant !== null) {
1197
1855
  return numberSource(node.operator === '+'
1198
- ? leftConst + rightConst
1856
+ ? leftConstant + rightConstant
1199
1857
  : node.operator === '-'
1200
- ? leftConst - rightConst
1201
- : leftConst * rightConst, loc);
1858
+ ? leftConstant - rightConstant
1859
+ : leftConstant * rightConstant, location);
1202
1860
  }
1203
- return binarySource(node, operand(node.left), operand(node.right), env);
1861
+ return binarySource(node, operand(node.left), operand(node.right), environment);
1204
1862
  }
1205
1863
  case 'LogicalExpression': {
1206
- // Only `&&` and `||` are supported (not `??`).
1864
+ // `a ?? b`: b where a is a list item's field that isn't there; a value that is always there is a.
1865
+ if (node.operator === '??') {
1866
+ const present = presenceOf(node.left, environment);
1867
+ if (present) {
1868
+ return {
1869
+ kind: 'conditional',
1870
+ test: { kind: 'fixed', expression: present, location },
1871
+ consequent: operand(node.left),
1872
+ alternate: operand(node.right),
1873
+ location,
1874
+ };
1875
+ }
1876
+ return isNullish(node.left, environment)
1877
+ ? operand(node.right)
1878
+ : operand(node.left);
1879
+ }
1880
+ // Otherwise only `&&` and `||`.
1207
1881
  const operator = node.operator === '&&' || node.operator === '||' ? node.operator : null;
1208
1882
  if (!operator) {
1209
1883
  throw new Error(`AOT: unsupported logical operator "${node.operator}"`);
1210
1884
  }
1885
+ // The right side reads a tagged object as the left side's outcome leaves it.
1886
+ const narrowing = narrowOn(node.left, environment);
1211
1887
  return {
1212
1888
  kind: 'logical',
1213
- op: operator,
1889
+ operator: operator,
1214
1890
  left: operand(node.left),
1215
- right: operand(node.right),
1216
- loc,
1891
+ right: lowerSource(node.right, narrowed(environment, operator === '&&' ? narrowing.whenTrue : narrowing.whenFalse)).source,
1892
+ location,
1217
1893
  };
1218
1894
  }
1219
- case 'ConditionalExpression':
1895
+ case 'ConditionalExpression': {
1896
+ const narrowing = narrowOn(node.test, environment);
1220
1897
  return {
1221
1898
  kind: 'conditional',
1222
1899
  test: operand(node.test),
1223
- consequent: operand(node.consequent),
1224
- alternate: operand(node.alternate),
1225
- loc,
1900
+ consequent: lowerSource(node.consequent, narrowed(environment, narrowing.whenTrue)).source,
1901
+ alternate: lowerSource(node.alternate, narrowed(environment, narrowing.whenFalse)).source,
1902
+ location,
1226
1903
  };
1904
+ }
1227
1905
  case 'MemberExpression': {
1228
1906
  // Static fold: member access that resolves to a compile-time constant (e.g., a .map item's `.key`).
1229
1907
  try {
1230
- const constValue = evalStatic(node, foldScope(env, env.consts ?? {}), 'boot');
1231
- if (isBoot(constValue))
1232
- return bootSource(constValue, loc);
1908
+ const constantValue = evalStatic(node, foldScope(environment, environment.constants ?? {}), 'boot');
1909
+ if (isBoot(constantValue))
1910
+ return bootSource(constantValue, location);
1233
1911
  // A number with no float form falls through too, so its check runs now, not in the check pass.
1234
- if (typeof constValue === 'number') {
1235
- return attemptLowering(() => numberSource(constValue, loc));
1912
+ if (typeof constantValue === 'number') {
1913
+ return attemptLowering(() => numberSource(constantValue, location));
1236
1914
  }
1237
- if (typeof constValue === 'string') {
1238
- return { kind: 'string', value: constValue, loc };
1915
+ if (typeof constantValue === 'string') {
1916
+ return { kind: 'string', value: constantValue, location };
1239
1917
  }
1240
- if (typeof constValue === 'boolean') {
1241
- return { kind: 'boolean', value: constValue, loc };
1918
+ if (typeof constantValue === 'boolean') {
1919
+ return { kind: 'boolean', value: constantValue, location };
1242
1920
  }
1243
1921
  }
1244
1922
  catch {
@@ -1247,64 +1925,66 @@ function sourceOf(node, env) {
1247
1925
  // Otherwise the object must be one of the runtime forms below; `prop` is null for a computed member.
1248
1926
  const object = node.object;
1249
1927
  const prop = node.computed ? null : node.property.name;
1250
- const fixed = (expr) => ({ kind: 'fixed', expr, loc });
1251
- // `<list>.length` → the runtime count.
1252
- if (object.type === 'Identifier' &&
1253
- env.state.get(object.name)?.kind === 'list' &&
1254
- prop === 'length') {
1255
- return fixed({
1256
- kind: 'listLength',
1257
- list: env.state.get(object.name),
1258
- type: INT,
1259
- });
1260
- }
1261
- // `<item>.field` where item is a struct local (a list row's bound element).
1262
- if (object.type === 'Identifier' &&
1263
- env.locals.get(object.name)?.struct &&
1264
- prop) {
1265
- const item = env.locals.get(object.name);
1266
- const field = item.struct.fields.find(structField => structField.key === prop);
1267
- if (!field) {
1268
- throw new Error(`AOT: unknown field "${prop}" on a list item`);
1928
+ const fixed = (expression) => ({
1929
+ kind: 'fixed',
1930
+ expression,
1931
+ location,
1932
+ });
1933
+ const available = nativeAvailableOf(node, environment);
1934
+ if (available)
1935
+ return fixed(available);
1936
+ // `<list>.length` → the runtime count, of a filtered or sorted list too.
1937
+ if (prop === 'length') {
1938
+ const list = object.type === 'Identifier'
1939
+ ? environment.state.get(object.name)
1940
+ : derivedListOf(object, environment);
1941
+ if (list?.kind === 'list') {
1942
+ return fixed({ kind: 'listLength', list, type: INT });
1269
1943
  }
1270
- return fixed({
1271
- kind: 'itemField',
1272
- item,
1273
- field,
1274
- type: typeOfSlot(field.kind),
1275
- });
1276
1944
  }
1277
- // `<ref>.current` — a value ref's mutable C slot.
1945
+ // A value worked out at run time in an array or object built in render.
1946
+ const leaf = runtimeLeafOf(node, environment);
1947
+ if (leaf) {
1948
+ return { kind: 'local', local: leaf, location };
1949
+ }
1950
+ // `item.field`, `item.pos.x`, `items[i].field` and `values[i]`: a field of a list item.
1951
+ const itemPath = itemPathOf(node, environment);
1952
+ if (itemPath) {
1953
+ return itemSource(itemPath, location);
1954
+ }
1955
+ // `<ref>.current` — a value ref's mutable slot.
1278
1956
  if (object.type === 'Identifier' &&
1279
- env.refs?.has(object.name) &&
1957
+ environment.refs?.has(object.name) &&
1280
1958
  prop === 'current') {
1281
- const ref = env.refs.get(object.name);
1959
+ const ref = environment.refs.get(object.name);
1282
1960
  ref.used = true;
1283
- return { kind: 'ref', ref, loc };
1961
+ return { kind: 'ref', ref, location };
1284
1962
  }
1285
1963
  // `<event>.x / .y / .dx / .dy` — touch fields of the handler's EREventData.
1286
1964
  if (object.type === 'Identifier' &&
1287
- env.event === object.name &&
1965
+ environment.event === object.name &&
1288
1966
  (prop === 'x' || prop === 'y' || prop === 'dx' || prop === 'dy')) {
1289
1967
  return fixed({ kind: 'event', field: prop, type: INT });
1290
1968
  }
1291
1969
  // `<event>.vx / .vy` — finger velocity (px/ms) at the last move; the engine measures it, a handler cannot.
1292
1970
  if (object.type === 'Identifier' &&
1293
- env.event === object.name &&
1971
+ environment.event === object.name &&
1294
1972
  (prop === 'vx' || prop === 'vy')) {
1295
1973
  return fixed({ kind: 'event', field: prop, type: FLOAT });
1296
1974
  }
1297
1975
  // `<gestureState>.…` — the second argument of a PanResponder callback (see emitPanResponder).
1298
- if (object.type === 'Identifier' && env.gesture === object.name && prop) {
1299
- return fixed(lowerGestureField(prop, env.pan));
1976
+ if (object.type === 'Identifier' &&
1977
+ environment.gesture === object.name &&
1978
+ prop) {
1979
+ return fixed(lowerGestureField(prop, environment.pan));
1300
1980
  }
1301
1981
  // `<event>.layout.x / .y / .width / .height` — the onLayout rect, also read as
1302
1982
  // `<event>.nativeEvent.layout.…` as in React Native.
1303
1983
  if (object.type === 'MemberExpression' &&
1304
1984
  !object.computed &&
1305
1985
  object.property.name === 'layout' &&
1306
- isEventRoot(object.object, env.event)) {
1307
- if (!env.layout) {
1986
+ isEventRoot(object.object, environment.event)) {
1987
+ if (!environment.layout) {
1308
1988
  throw aotError('AOT: only an onLayout event carries a layout rect', 'read e.layout (or e.nativeEvent.layout) inside an onLayout handler.');
1309
1989
  }
1310
1990
  if (!LAYOUT_FIELDS.has(prop)) {
@@ -1318,24 +1998,61 @@ function sourceOf(node, env) {
1318
1998
  prop === 'PI') {
1319
1999
  return fixed({ kind: 'pi', type: FLOAT });
1320
2000
  }
1321
- 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 ' +
1322
- 'field, event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.layout.*), and ' +
2001
+ // A field of a record a native method returns, read where it can't be kept.
2002
+ let root = node;
2003
+ while (root.type === 'MemberExpression')
2004
+ root = root.object;
2005
+ const unkept = unkeptRecordError(root, environment);
2006
+ if (unkept)
2007
+ throw unkept;
2008
+ throw aotError('AOT: unsupported member expression in a dynamic context', "in a handler or dynamic expression you can read state, `ref.current`, a list item's " +
2009
+ 'field (`item.title`, `items[i].title`), event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.layout.*), and ' +
1323
2010
  'Math.PI — other member access must be a compile-time constant.');
1324
2011
  }
2012
+ case 'OptionalMemberExpression': {
2013
+ // `items[i]?.field`, or `item.pos?.x`: a list item's field, undefined where it isn't there.
2014
+ const itemPath = itemPathOf(node, environment);
2015
+ if (itemPath) {
2016
+ return itemSource(itemPath, location);
2017
+ }
2018
+ throw aotError('AOT: `?.` is only lowered on a list item', 'read a field of a list item with it, as in `items[i]?.title` — anything else must be there.');
2019
+ }
1325
2020
  case 'CallExpression': {
1326
2021
  const callee = node.callee;
2022
+ // `Sensors.read(channel)`: a native method's result.
2023
+ const nativeCallee = nativeCalleeOf(node, environment);
2024
+ if (nativeCallee) {
2025
+ const unkept = unkeptRecordError(node, environment);
2026
+ if (unkept)
2027
+ throw unkept;
2028
+ const call = lowerNativeCall(node, nativeCallee, environment);
2029
+ if (call.import.result === 'void') {
2030
+ const binding = callee.object.name;
2031
+ throw aotError(`AOT: ${binding}.${nativeCallee.method}() returns nothing, so it has no value`, 'call it as a statement of its own.');
2032
+ }
2033
+ return {
2034
+ kind: 'fixed',
2035
+ expression: {
2036
+ kind: 'native',
2037
+ call,
2038
+ // A record was refused above.
2039
+ type: NATIVE_TYPES[call.import.result],
2040
+ },
2041
+ location,
2042
+ };
2043
+ }
1327
2044
  // Date.now() / performance.now() → the engine clock, as 64-bit whole milliseconds.
1328
2045
  if (callee.type === 'MemberExpression' &&
1329
2046
  !callee.computed &&
1330
2047
  callee.object.type === 'Identifier' &&
1331
2048
  (callee.object.name === 'Date' ||
1332
2049
  callee.object.name === 'performance') &&
1333
- !env.shadowedClock?.has(node)) {
2050
+ !environment.shadowedClock?.has(node)) {
1334
2051
  if (callee.property.name === 'now') {
1335
2052
  return {
1336
2053
  kind: 'fixed',
1337
- expr: { kind: 'clock', clock: callee.object.name, type: TIME },
1338
- loc,
2054
+ expression: { kind: 'clock', clock: callee.object.name, type: TIME },
2055
+ location,
1339
2056
  };
1340
2057
  }
1341
2058
  if (callee.object.name === 'Date') {
@@ -1344,38 +2061,64 @@ function sourceOf(node, env) {
1344
2061
  }
1345
2062
  if (callee.type === 'Identifier' &&
1346
2063
  callee.name === 'Date' &&
1347
- !env.shadowedClock?.has(node)) {
2064
+ !environment.shadowedClock?.has(node)) {
1348
2065
  throw dateObjectError();
1349
2066
  }
2067
+ // `text.includes(search)` on strings, a boolean.
2068
+ if (callee.type === 'MemberExpression' &&
2069
+ !callee.computed &&
2070
+ callee.property.type === 'Identifier' &&
2071
+ callee.property.name === 'includes') {
2072
+ return {
2073
+ kind: 'fixed',
2074
+ expression: lowerIncludes(node, environment),
2075
+ location,
2076
+ };
2077
+ }
2078
+ // `a.localeCompare(b)` on strings: -1, 0 or 1.
2079
+ if (callee.type === 'MemberExpression' &&
2080
+ !callee.computed &&
2081
+ callee.property.type === 'Identifier' &&
2082
+ callee.property.name === 'localeCompare') {
2083
+ return {
2084
+ kind: 'fixed',
2085
+ expression: lowerLocaleCompare(node, environment),
2086
+ location,
2087
+ };
2088
+ }
1350
2089
  // Math.*: a division under floor / ceil / round / trunc stays apart, for the typing pass to divide exactly.
1351
2090
  if (callee.type === 'MemberExpression' &&
1352
2091
  callee.object.name === 'Math') {
1353
- const fn = callee.property.name;
2092
+ const mathFunction = callee.property.name;
1354
2093
  const division = node.arguments[0];
1355
- const exactDivision = INT_ROUND_DIV.has(fn) &&
2094
+ const exactDivision = INT_ROUND_DIVISION.has(mathFunction) &&
1356
2095
  node.arguments.length === 1 &&
1357
2096
  division.type === 'BinaryExpression' &&
1358
2097
  division.operator === '/';
1359
2098
  return {
1360
2099
  kind: 'math',
1361
- fn,
1362
- args: exactDivision
2100
+ mathFunction,
2101
+ callArguments: exactDivision
1363
2102
  ? [
1364
- binarySource(division, operand(division.left), operand(division.right), env),
2103
+ binarySource(division, operand(division.left), operand(division.right), environment),
1365
2104
  ]
1366
2105
  : node.arguments.map(operand),
1367
2106
  exactDivision,
1368
2107
  wholeMath: keepsMath64Node(node),
1369
- loc,
2108
+ location,
1370
2109
  };
1371
2110
  }
2111
+ // A helper used as a value: its body as one expression.
2112
+ const helperValue = helperValueOf(node, environment);
2113
+ if (helperValue)
2114
+ return helperValue;
1372
2115
  throw new Error('AOT: unsupported call expression in a dynamic expression');
1373
2116
  }
1374
2117
  case 'NewExpression':
1375
2118
  // `new Date(…)` gets the Date-specific error; any other constructor gets the generic one below.
1376
2119
  if (node.callee.type === 'Identifier' &&
1377
2120
  node.callee.name === 'Date' &&
1378
- !env.shadowedClock?.has(node)) {
2121
+ !environment.shadowedClock?.has(node)) {
1379
2122
  throw dateObjectError();
1380
2123
  }
1381
2124
  break;
@@ -1386,80 +2129,172 @@ function sourceOf(node, env) {
1386
2129
  * Lowers one JS expression to its source and types it, with the expression's location attached to any AOT
1387
2130
  * error either step throws.
1388
2131
  */
1389
- export const lowerSource = withLoc((node, env) => {
2132
+ export const lowerSource = withLoc((node, environment) => {
1390
2133
  // Below a node that is not whole-number math, its operands are typed as usual (see keepsMath64Node).
1391
- if (env.math64 && !keepsMath64Node(node)) {
1392
- env = { ...env, math64: false };
2134
+ if (environment.math64 && !keepsMath64Node(node)) {
2135
+ environment = { ...environment, math64: undefined };
1393
2136
  }
1394
- const source = sourceOf(node, env);
1395
- return { source, expr: typeSource(source, env.math64 ?? false) };
2137
+ const source = sourceOf(node, environment);
2138
+ // A constant's type, and one its source or its slot fixes, depends on no slot's width.
2139
+ if (source.kind === 'number' ||
2140
+ source.kind === 'string' ||
2141
+ source.kind === 'boolean' ||
2142
+ source.kind === 'fixed' ||
2143
+ (source.kind === 'state' && isSettledState(source.state)) ||
2144
+ (source.kind === 'ref' &&
2145
+ source.ref.slotKind !== 'int' &&
2146
+ source.ref.slotKind !== 'i64')) {
2147
+ return { source, expression: typeSource(source, false) };
2148
+ }
2149
+ const { math64 } = environment;
2150
+ return {
2151
+ source,
2152
+ expression: typedLater(sourceShape(source), () => typeSource(source, math64?.() ?? false), source),
2153
+ };
1396
2154
  });
1397
2155
  /**
1398
2156
  * Lowers one JS expression to the IR: its source, typed by the typing pass.
1399
2157
  *
1400
2158
  * @param node The expression.
1401
- * @param env The expression environment.
2159
+ * @param environment The expression environment.
1402
2160
  *
1403
2161
  * @returns The typed expression.
1404
2162
  */
1405
- export const lowerExprWide = (node, env) => lowerSource(node, env).expr;
2163
+ export const lowerExprWide = (node, environment) => lowerSource(node, environment).expression;
1406
2164
  /**
1407
- * emitExpr for the destinations that can hold a 64-bit timestamp: state, refs, locals, text, conditions.
2165
+ * The shape of a source expression's value, which holds whatever the typing pass makes of its numbers.
1408
2166
  *
1409
- * @param node The expression.
1410
- * @param env The expression environment.
2167
+ * @param source The expression.
2168
+ *
2169
+ * @returns The shape.
2170
+ */
2171
+ export function sourceShape(source) {
2172
+ switch (source.kind) {
2173
+ case 'number':
2174
+ return 'number';
2175
+ case 'string':
2176
+ return 'string';
2177
+ case 'boolean':
2178
+ return 'bool';
2179
+ case 'state':
2180
+ return stateShape(source.state);
2181
+ case 'local':
2182
+ return localShape(source.local);
2183
+ case 'ref':
2184
+ return source.ref.kind === 'node' ? 'node' : 'number';
2185
+ case 'fixed':
2186
+ return shapeOf(source.expression);
2187
+ case 'unary': {
2188
+ if (source.operator === '!')
2189
+ return 'bool';
2190
+ const operand = sourceShape(source.operand);
2191
+ return operand === 'bool' ? 'number' : operand;
2192
+ }
2193
+ case 'binary':
2194
+ return COMPARE.has(source.operator) ? 'bool' : 'number';
2195
+ case 'logical':
2196
+ return sourceShape(source.left) === 'bool' &&
2197
+ sourceShape(source.right) === 'bool'
2198
+ ? 'bool'
2199
+ : 'number';
2200
+ case 'conditional': {
2201
+ const consequent = sourceShape(source.consequent);
2202
+ return consequent === sourceShape(source.alternate)
2203
+ ? consequent
2204
+ : 'number';
2205
+ }
2206
+ case 'math':
2207
+ return 'number';
2208
+ }
2209
+ }
2210
+ /**
2211
+ * The local an expression is a bare read of, if it is one.
2212
+ *
2213
+ * @param lowered The expression, and its source.
2214
+ *
2215
+ * @returns The local, or null.
2216
+ */
2217
+ export function bareLocalOf(lowered) {
2218
+ return lowered.source.kind === 'local'
2219
+ ? lowered.source.local
2220
+ : readLocalOf(lowered.expression);
2221
+ }
2222
+ /**
2223
+ * What a slot holding an expression's value records about it. A bare local is the Local itself, so a list row keeps
2224
+ * its struct (extractProps copies it into a prop).
1411
2225
  *
1412
- * @returns The expression as C.
2226
+ * @param expression The expression.
2227
+ *
2228
+ * @returns The slot value.
1413
2229
  */
1414
- export const emitExprWide = (node, env) => toCExpr(lowerExprWide(node, env));
2230
+ export function slotValueOf(expression) {
2231
+ if (expression.kind === 'local') {
2232
+ return expression.local;
2233
+ }
2234
+ const value = { slotKind: slotOf(expression.type) };
2235
+ if (expression.type.kind === 'bool') {
2236
+ value.isBoolean = true;
2237
+ }
2238
+ else if (expression.type.kind === 'int64' &&
2239
+ expression.type.source !== 'time') {
2240
+ value[expression.type.source === 'number' ? 'isLiteral' : 'wide'] = true;
2241
+ }
2242
+ return value;
2243
+ }
1415
2244
  /**
1416
- * emitExprWide, for a local that holds the value: with the source it was lowered from, which the typing pass
2245
+ * lowerExprWide, for a local that holds the value: with the source it was lowered from, which the typing pass
1417
2246
  * reads when it infers slot widths.
1418
2247
  *
1419
2248
  * @param node The expression.
1420
- * @param env The expression environment.
2249
+ * @param environment The expression environment.
1421
2250
  *
1422
- * @returns The expression as C, and its source.
2251
+ * @returns The slot value, its source, and the typed expression.
1423
2252
  */
1424
- export function emitSourcedWide(node, env) {
1425
- const lowered = lowerSource(node, env);
1426
- return { ...toCExpr(lowered.expr), source: lowered.source };
2253
+ export function lowerSourcedWide(node, environment) {
2254
+ const lowered = lowerSource(node, environment);
2255
+ const local = bareLocalOf(lowered);
2256
+ return local
2257
+ ? copyLocal(local, lowered)
2258
+ : holdLater({ ...lowered }, shapeOf(lowered.expression), () => slotValueOf(lowered.expression));
1427
2259
  }
1428
2260
  /**
1429
- * Lowers an expression for a destination that holds an int, a float, or a string. C would narrow a 64-bit
1430
- * value (a Date.now() / performance.now() timestamp, or a whole number past the int range) into one of those
1431
- * without a warning, so it is refused here; the destinations that hold 64 bits call lowerExprWide.
1432
- *
1433
- * The result carries its type, so the caller can pick the right printf spec or assignment. A destination
1434
- * that holds text lowers through lowerText instead.
2261
+ * Lowers an expression a name is bound to: the local that every read of the name is.
1435
2262
  *
1436
2263
  * @param node The expression.
1437
- * @param env The expression environment.
2264
+ * @param environment The expression environment.
1438
2265
  *
1439
- * @returns The lowered expression; never 64-bit.
2266
+ * @returns The local.
1440
2267
  */
1441
- export function lowerExpr(node, env) {
1442
- const expr = lowerExprWide(node, env);
1443
- if (expr.type.kind !== 'int64')
1444
- return expr;
1445
- 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, ' +
1446
- 'reduce it to a small number first — e.g. `ms % 1000`, or `Math.floor(ms / 1000) % ' +
1447
- '60`.');
1448
- if (node.loc) {
1449
- error.aotLoc = node.loc.start;
1450
- }
1451
- throw error;
2268
+ export function lowerLocal(node, environment) {
2269
+ const { source, expression } = lowerSourcedWide(node, environment);
2270
+ return holdLater({ source, expression }, shapeOf(expression), () => slotValueOf(expression));
1452
2271
  }
1453
2272
  /**
1454
- * lowerExpr, as C: what the emitters that do not build the IR yet use.
2273
+ * Lowers an expression for a destination that holds an int, a float, or a string. A 64-bit value (a Date.now() /
2274
+ * performance.now() timestamp, or a whole number past the int range) would be cut narrowing into one of those, so it
2275
+ * is refused here; the destinations that hold 64 bits call lowerExprWide.
2276
+ *
2277
+ * The result carries its type. A destination that holds text lowers through lowerText instead.
1455
2278
  *
1456
2279
  * @param node The expression.
1457
- * @param env The expression environment.
2280
+ * @param environment The expression environment.
1458
2281
  *
1459
- * @returns The expression as C; never 64-bit.
2282
+ * @returns The lowered expression; never 64-bit.
1460
2283
  */
1461
- export function emitExpr(node, env) {
1462
- return toCExpr(lowerExpr(node, env));
2284
+ export function lowerExpr(node, environment) {
2285
+ const expression = lowerExprWide(node, environment);
2286
+ whenTyped(() => {
2287
+ if (expression.type.kind !== 'int64')
2288
+ return;
2289
+ 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, ' +
2290
+ 'reduce it to a small number first — e.g. `ms % 1000`, or `Math.floor(ms / 1000) % ' +
2291
+ '60`.');
2292
+ if (node.loc) {
2293
+ error.aotLoc = node.loc.start;
2294
+ }
2295
+ throw error;
2296
+ });
2297
+ return expression;
1463
2298
  }
1464
2299
  /**
1465
2300
  * An aotError pinned to the expression that cannot be lowered to text (lowerTextParts is not withLoc-wrapped).
@@ -1477,6 +2312,351 @@ function textShapeError(node, message, hint) {
1477
2312
  }
1478
2313
  return error;
1479
2314
  }
2315
+ /**
2316
+ * Whether an expression is a compile-time constant.
2317
+ *
2318
+ * @param node The expression.
2319
+ * @param scope The constants a fold may read.
2320
+ *
2321
+ * @returns True when it folds.
2322
+ */
2323
+ function foldsStatically(node, scope) {
2324
+ try {
2325
+ evalStatic(node, scope, 'strict');
2326
+ return true;
2327
+ }
2328
+ catch {
2329
+ return false;
2330
+ }
2331
+ }
2332
+ /**
2333
+ * Whether an expression builds a string at run time: a template literal, a string helper, or a string `+`. Only a
2334
+ * destination that holds text can take one, through lowerText.
2335
+ *
2336
+ * @param node The expression.
2337
+ * @param environment The expression environment.
2338
+ *
2339
+ * @returns True when it builds a string.
2340
+ */
2341
+ export function buildsText(node, environment) {
2342
+ const scope = foldScope(environment, environment.constants ?? {});
2343
+ if (foldsStatically(node, scope))
2344
+ return false;
2345
+ if (node.type === 'TemplateLiteral' ||
2346
+ textCallOf(node, environment, scope) !== null) {
2347
+ return true;
2348
+ }
2349
+ // A helper that returns built text builds it.
2350
+ const returned = returnedExpression(node, environment);
2351
+ if (returned)
2352
+ return buildsText(returned.node, returned.environment);
2353
+ return (node.type === 'BinaryExpression' &&
2354
+ node.operator === '+' &&
2355
+ lowerTextParts(node, environment, scope, true).isString);
2356
+ }
2357
+ /** The string helpers that build text. */
2358
+ const TEXT_METHODS = new Set(['toFixed', 'padStart', 'slice', 'toUpperCase']);
2359
+ /**
2360
+ * The text helper a call is: `String(x)`, or `x.toFixed(n)`, `x.padStart(n, fill)`, `x.slice(start, end)` or
2361
+ * `x.toUpperCase()`. A list's slice is not one.
2362
+ *
2363
+ * @param node The expression.
2364
+ * @param environment The expression environment.
2365
+ * @param scope The constants a fold may read, which may shadow `String`.
2366
+ *
2367
+ * @returns The helper's name, or null for anything else.
2368
+ */
2369
+ function textCallOf(node, environment, scope) {
2370
+ if (node.type !== 'CallExpression')
2371
+ return null;
2372
+ const { callee } = node;
2373
+ if (callee.type === 'Identifier' &&
2374
+ callee.name === 'String' &&
2375
+ !hasBinding(scope, 'String')) {
2376
+ return 'String';
2377
+ }
2378
+ if (callee.type !== 'MemberExpression' ||
2379
+ callee.computed ||
2380
+ callee.property.type !== 'Identifier' ||
2381
+ !TEXT_METHODS.has(callee.property.name)) {
2382
+ return null;
2383
+ }
2384
+ const isList = callee.object.type === 'Identifier' &&
2385
+ environment.state.get(callee.object.name)?.kind === 'list';
2386
+ return isList ? null : callee.property.name;
2387
+ }
2388
+ /**
2389
+ * A compile-time whole number a text helper takes.
2390
+ *
2391
+ * @param node The argument, or undefined when it is left out.
2392
+ * @param fallback The value JS uses when it is left out.
2393
+ * @param what What the argument is, for errors.
2394
+ * @param environment The expression environment.
2395
+ *
2396
+ * @returns The number.
2397
+ */
2398
+ function helperInt(node, fallback, what, environment) {
2399
+ if (!node)
2400
+ return fallback;
2401
+ const value = staticInt(node, environment);
2402
+ if (value === null) {
2403
+ throw textShapeError(node, `AOT: ${what} must be a compile-time whole number`, 'the package bakes it into the instruction, so write a literal or a module constant.');
2404
+ }
2405
+ return value;
2406
+ }
2407
+ /**
2408
+ * Lowers `x.toFixed(digits)` on a runtime number.
2409
+ *
2410
+ * @param call The call.
2411
+ * @param environment The expression environment.
2412
+ *
2413
+ * @returns The text: the number, printed with that many decimals.
2414
+ */
2415
+ function lowerToFixed(call, environment) {
2416
+ const receiver = call.callee.object;
2417
+ const value = lowerExprWide(receiver, environment);
2418
+ if (shapeOf(value) !== 'number') {
2419
+ throw textShapeError(call, 'AOT: toFixed is only supported on a number', 'JS has toFixed on numbers only; call it on the number itself.');
2420
+ }
2421
+ const digits = helperInt(call.arguments[0], 0, "toFixed's digits", environment);
2422
+ const problem = fixedDigitsProblem(digits);
2423
+ if (problem) {
2424
+ throw textShapeError(call, ...problem);
2425
+ }
2426
+ return { isString: true, parts: [{ kind: 'value', value, digits }] };
2427
+ }
2428
+ /**
2429
+ * Lowers `x.padStart(width, fill)` on a runtime string.
2430
+ *
2431
+ * @param call The call.
2432
+ * @param environment The expression environment.
2433
+ * @param scope The constants a fold may read.
2434
+ *
2435
+ * @returns The text: the string, padded.
2436
+ */
2437
+ function lowerPadStart(call, environment, scope) {
2438
+ const receiver = lowerTextParts(call.callee.object, environment, scope, true);
2439
+ if (!receiver.isString) {
2440
+ throw textShapeError(call, 'AOT: padStart is only supported on a string', 'JS has padStart on strings only; convert first: String(n).padStart(2, "0").');
2441
+ }
2442
+ // The same limits as a constant fold, checked before the receiver so a constant one gets the same error.
2443
+ const width = helperInt(call.arguments[0], 0, "padStart's length", environment);
2444
+ const widthProblem = padWidthProblem(width);
2445
+ if (widthProblem) {
2446
+ throw textShapeError(call, ...widthProblem);
2447
+ }
2448
+ const fillNode = call.arguments[1];
2449
+ let fill = ' ';
2450
+ if (fillNode) {
2451
+ try {
2452
+ fill = evalStatic(fillNode, scope, 'strict');
2453
+ }
2454
+ catch {
2455
+ fill = null;
2456
+ }
2457
+ }
2458
+ const fillProblem = padFillProblem(fill);
2459
+ if (fillProblem) {
2460
+ throw textShapeError(fillNode ?? call, ...fillProblem);
2461
+ }
2462
+ const piece = onePiece(receiver, call, 'AOT: padStart can only pad one value', 'pad each value on its own and join them after: `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`.');
2463
+ if (fill === '' || width <= 0) {
2464
+ return { isString: true, parts: [piece] };
2465
+ }
2466
+ return {
2467
+ isString: true,
2468
+ parts: [
2469
+ {
2470
+ ...piece,
2471
+ edits: [
2472
+ ...(piece.edits ?? []),
2473
+ { kind: 'pad', width, fill: fill },
2474
+ ],
2475
+ },
2476
+ ],
2477
+ };
2478
+ }
2479
+ /**
2480
+ * One of slice's positions: a constant cut to a whole number as JS cuts it, or a runtime whole number.
2481
+ *
2482
+ * @param node The argument, or undefined when it is left out.
2483
+ * @param fallback The position JS uses when it is left out.
2484
+ * @param environment The expression environment.
2485
+ * @param scope The constants a fold may read.
2486
+ *
2487
+ * @returns The position.
2488
+ */
2489
+ function slicePosition(node, fallback, environment, scope) {
2490
+ if (!node)
2491
+ return numConst(fallback);
2492
+ if (node.type === 'SpreadElement') {
2493
+ throw textShapeError(node, 'AOT: slice cannot take a spread', 'pass the start and end themselves: text.slice(0, 3).');
2494
+ }
2495
+ let constant = null;
2496
+ try {
2497
+ constant = { value: evalStatic(node, scope, 'strict') };
2498
+ }
2499
+ catch (error) {
2500
+ rethrowFoldLimit(error);
2501
+ }
2502
+ if (constant) {
2503
+ const problem = slicePositionProblem([constant.value]);
2504
+ if (problem) {
2505
+ throw textShapeError(node, ...problem);
2506
+ }
2507
+ const position = Math.trunc(constant.value) || 0;
2508
+ return numConst(Math.max(-TEXT_END, Math.min(TEXT_END, position)));
2509
+ }
2510
+ const position = lowerExpr(node, environment);
2511
+ whenTyped(() => {
2512
+ if (position.type.kind !== 'int') {
2513
+ throw textShapeError(node, "AOT: slice's start and end must be whole numbers", 'a package cuts at whole positions; round it first: text.slice(0, Math.floor(n)).');
2514
+ }
2515
+ });
2516
+ return position;
2517
+ }
2518
+ /**
2519
+ * The one piece a helper that edits a printed piece (padStart, slice) can work on.
2520
+ *
2521
+ * @param receiver The text the helper is called on.
2522
+ * @param call The call, for errors.
2523
+ * @param message The error when there is more than one value, or none.
2524
+ * @param hint How to rewrite it.
2525
+ *
2526
+ * @returns The piece.
2527
+ */
2528
+ function onePiece(receiver, call, message, hint) {
2529
+ const pieces = receiver.parts.filter(part => !(part.kind === 'literal' && part.text === ''));
2530
+ const [piece] = pieces;
2531
+ if (pieces.length !== 1 || piece.kind === 'literal') {
2532
+ throw textShapeError(call, message, hint);
2533
+ }
2534
+ return piece;
2535
+ }
2536
+ /**
2537
+ * Lowers `x.slice(start, end)` on a runtime string.
2538
+ *
2539
+ * @param call The call.
2540
+ * @param environment The expression environment.
2541
+ * @param scope The constants a fold may read.
2542
+ *
2543
+ * @returns The text: the part of the string between the two positions.
2544
+ */
2545
+ function lowerSlice(call, environment, scope) {
2546
+ const receiver = lowerTextParts(call.callee.object, environment, scope, true);
2547
+ if (!receiver.isString) {
2548
+ throw textShapeError(call, 'AOT: slice is only supported on a string', 'on a number, convert first: String(n).slice(-2). A list slices only as list.slice(0, end).map(…).');
2549
+ }
2550
+ const [startNode, endNode] = call.arguments;
2551
+ const start = slicePosition(startNode, 0, environment, scope);
2552
+ const end = slicePosition(endNode, TEXT_END, environment, scope);
2553
+ const piece = onePiece(receiver, call, 'AOT: slice can only cut one value', 'slice each value on its own and join them after: `${a.slice(0, 3)}-${b.slice(0, 3)}`.');
2554
+ whenTyped(() => {
2555
+ if (piece.kind === 'value' &&
2556
+ piece.digits &&
2557
+ piece.value.type.kind !== 'float') {
2558
+ throw textShapeError(call, "AOT: slice cannot cut a whole number's toFixed", 'its decimals are printed apart from it; slice String(n) and add the decimals after it.');
2559
+ }
2560
+ });
2561
+ return {
2562
+ isString: true,
2563
+ parts: [
2564
+ { ...piece, edits: [...(piece.edits ?? []), { kind: 'slice', start, end }] },
2565
+ ],
2566
+ };
2567
+ }
2568
+ /**
2569
+ * Lowers `x.toUpperCase()` on a runtime string. Its literal text is upper-cased here, and each value as it is
2570
+ * printed; a whole number has no letters to change (see typedParts).
2571
+ *
2572
+ * @param call The call.
2573
+ * @param environment The expression environment.
2574
+ * @param scope The constants a fold may read.
2575
+ *
2576
+ * @returns The text, upper-cased.
2577
+ */
2578
+ function lowerToUpperCase(call, environment, scope) {
2579
+ const receiver = lowerTextParts(call.callee.object, environment, scope, true);
2580
+ if (!receiver.isString) {
2581
+ throw textShapeError(call, 'AOT: toUpperCase is only supported on a string', 'JS has toUpperCase on strings only; convert first: String(on).toUpperCase().');
2582
+ }
2583
+ return {
2584
+ isString: true,
2585
+ parts: receiver.parts.map(part => {
2586
+ if (part.kind === 'literal') {
2587
+ return { ...part, text: part.text.toUpperCase() };
2588
+ }
2589
+ return { ...part, edits: [...(part.edits ?? []), { kind: 'upper' }] };
2590
+ }),
2591
+ };
2592
+ }
2593
+ /**
2594
+ * Lowers `text.includes(search)` on runtime strings.
2595
+ *
2596
+ * @param call The call.
2597
+ * @param environment The expression environment.
2598
+ *
2599
+ * @returns The boolean.
2600
+ */
2601
+ function lowerIncludes(call, environment) {
2602
+ const receiver = call.callee.object;
2603
+ const [needleNode, ...rest] = call.arguments;
2604
+ if (needleNode?.type === 'SpreadElement') {
2605
+ throw aotError('AOT: includes cannot take a spread', 'pass the string to search for: name.includes(x).');
2606
+ }
2607
+ const problem = includesProblem(needleNode ? '' : undefined, rest.length > 0);
2608
+ if (problem) {
2609
+ throw aotError(...problem);
2610
+ }
2611
+ // A string built in place lives in the format buffer, not in a string register.
2612
+ const stringOf = (node, problemOf) => {
2613
+ if (buildsText(node, environment)) {
2614
+ throw aotError('AOT: includes needs a string kept somewhere, not one built in place', 'build it into a local first: `const label = `${a} ${b}`;` then label.includes(x).');
2615
+ }
2616
+ const value = lowerExprWide(node, environment);
2617
+ if (shapeOf(value) !== 'string') {
2618
+ throw aotError(...problemOf());
2619
+ }
2620
+ return value;
2621
+ };
2622
+ const haystack = stringOf(receiver, () => [
2623
+ 'AOT: includes is only supported on a string',
2624
+ 'JS has includes on strings and arrays; a package has it on a string only. Compare with === for one value.',
2625
+ ]);
2626
+ const needle = stringOf(needleNode, () => includesProblem(0, false));
2627
+ return { kind: 'stringIncludes', haystack, needle, type: BOOL };
2628
+ }
2629
+ /**
2630
+ * Lowers `text.localeCompare(other)` on runtime strings, which orders them as `<` does, with no locale rules.
2631
+ *
2632
+ * @param call The call.
2633
+ * @param environment The expression environment.
2634
+ *
2635
+ * @returns -1, 0 or 1.
2636
+ */
2637
+ function lowerLocaleCompare(call, environment) {
2638
+ const receiver = call.callee.object;
2639
+ const [otherNode, ...rest] = call.arguments;
2640
+ if (!otherNode || otherNode.type === 'SpreadElement' || rest.length) {
2641
+ throw aotError('AOT: localeCompare takes one string', 'pass just the string to compare with: a.name.localeCompare(b.name). Locales and options are not supported.');
2642
+ }
2643
+ const stringOf = (node) => {
2644
+ if (buildsText(node, environment)) {
2645
+ throw aotError('AOT: localeCompare needs a string kept somewhere, not one built in place', 'build it into a local first: `const label = `${a} ${b}`;` then label.localeCompare(x).');
2646
+ }
2647
+ const value = lowerExprWide(node, environment);
2648
+ if (shapeOf(value) !== 'string') {
2649
+ throw aotError('AOT: localeCompare is only supported on strings', 'compare numbers by subtracting them: (a, b) => a.n - b.n.');
2650
+ }
2651
+ return value;
2652
+ };
2653
+ return {
2654
+ kind: 'stringOrder',
2655
+ left: stringOf(receiver),
2656
+ right: stringOf(otherNode),
2657
+ type: INT,
2658
+ };
2659
+ }
1480
2660
  /**
1481
2661
  * Text a constant renders as a standalone JSX child. React draws nothing for null, undefined, or a
1482
2662
  * boolean (see flattenTextChildren in Flow A), which is not how `+` treats the same values — a
@@ -1486,22 +2666,28 @@ function textShapeError(node, message, hint) {
1486
2666
  *
1487
2667
  * @returns The text React would render for it.
1488
2668
  */
1489
- export const jsxChildText = (value) => value === undefined || value === null || typeof value === 'boolean'
1490
- ? ''
1491
- : String(value);
2669
+ export function jsxChildText(value) {
2670
+ if (value === undefined || value === null || typeof value === 'boolean') {
2671
+ return '';
2672
+ }
2673
+ if (typeof value === 'object' && !Array.isArray(value)) {
2674
+ throw aotError('AOT: an object cannot be a <Text> child', 'React refuses objects as children; render one of its fields: {p.label}.');
2675
+ }
2676
+ return String(value);
2677
+ }
1492
2678
  /**
1493
2679
  * Splits a string-building `+` chain into text parts, following JS's own left-to-right typing: a `+`
1494
2680
  * is a concatenation only once one of its sides is a string, so `n + 1 + 'ms'` still adds before it
1495
2681
  * appends. Each part is literal text, a runtime value, or a boolean printed as a word.
1496
2682
  *
1497
2683
  * @param node The expression.
1498
- * @param env The expression environment.
2684
+ * @param environment The expression environment.
1499
2685
  * @param scope The constants a fold may read (already filtered by foldScope).
1500
2686
  * @param isOperand The expression is an operand of `+`, where null / undefined / booleans print as words.
1501
2687
  *
1502
2688
  * @returns The parts, and whether JS would treat the expression as a string.
1503
2689
  */
1504
- function lowerTextParts(node, env, scope, isOperand = false) {
2690
+ function lowerTextParts(node, environment, scope, isOperand = false) {
1505
2691
  // `undefined` is "" as a child but "undefined" in a `+`; handled here, not in the fold every prop reader shares.
1506
2692
  if (node.type === 'Identifier' && node.name === 'undefined') {
1507
2693
  return {
@@ -1511,13 +2697,13 @@ function lowerTextParts(node, env, scope, isOperand = false) {
1511
2697
  }
1512
2698
  // A compile-time constant becomes literal text; a value worked out at boot is a runtime value.
1513
2699
  try {
1514
- const constValue = evalStatic(node, scope, 'strict');
2700
+ const constantValue = evalStatic(node, scope, 'strict');
1515
2701
  return {
1516
- isString: typeof constValue === 'string',
2702
+ isString: typeof constantValue === 'string',
1517
2703
  parts: [
1518
2704
  {
1519
2705
  kind: 'literal',
1520
- text: isOperand ? String(constValue) : jsxChildText(constValue),
2706
+ text: isOperand ? String(constantValue) : jsxChildText(constantValue),
1521
2707
  },
1522
2708
  ],
1523
2709
  };
@@ -1527,16 +2713,62 @@ function lowerTextParts(node, env, scope, isOperand = false) {
1527
2713
  }
1528
2714
  // A `+` with a string on either side is a concatenation: its parts are both sides' parts in order.
1529
2715
  if (node.type === 'BinaryExpression' && node.operator === '+') {
1530
- const leftParts = lowerTextParts(node.left, env, scope, true);
1531
- const rightParts = lowerTextParts(node.right, env, scope, true);
2716
+ const leftParts = lowerTextParts(node.left, environment, scope, true);
2717
+ const rightParts = lowerTextParts(node.right, environment, scope, true);
1532
2718
  if (leftParts.isString || rightParts.isString) {
1533
2719
  return { isString: true, parts: [...leftParts.parts, ...rightParts.parts] };
1534
2720
  }
1535
2721
  }
1536
- // A branch or operand that concatenates needs its own format; refuse before lowerExpr's misleading error.
1537
- const concatenates = (subExpr) => subExpr.type === 'BinaryExpression' &&
1538
- subExpr.operator === '+' &&
1539
- lowerTextParts(subExpr, env, scope, true).isString;
2722
+ // A template literal is its strings and values in order, each value printed as String() prints it.
2723
+ if (node.type === 'TemplateLiteral') {
2724
+ const parts = [];
2725
+ node.quasis.forEach((quasi, index) => {
2726
+ parts.push({ kind: 'literal', text: quasi.value.cooked ?? '' });
2727
+ if (index < node.expressions.length) {
2728
+ parts.push(...lowerTextParts(node.expressions[index], environment, scope, true)
2729
+ .parts);
2730
+ }
2731
+ });
2732
+ return { isString: true, parts };
2733
+ }
2734
+ // A helper that returns text on its only path is that text, built where it is called.
2735
+ const returned = returnedExpression(node, environment);
2736
+ if (returned) {
2737
+ return lowerTextParts(returned.node, returned.environment, foldScope(returned.environment, returned.environment.constants), isOperand);
2738
+ }
2739
+ // String(x) prints x as an operand of a string `+` would.
2740
+ const textCall = textCallOf(node, environment, scope);
2741
+ if (textCall === 'String') {
2742
+ const [argument] = node.arguments;
2743
+ if (argument?.type === 'SpreadElement') {
2744
+ throw textShapeError(node, 'AOT: String(...) cannot take a spread', 'pass the value itself: String(n).');
2745
+ }
2746
+ return {
2747
+ isString: true,
2748
+ parts: argument
2749
+ ? lowerTextParts(argument, environment, scope, true).parts
2750
+ : [],
2751
+ };
2752
+ }
2753
+ if (textCall === 'toFixed') {
2754
+ return lowerToFixed(node, environment);
2755
+ }
2756
+ if (textCall === 'padStart') {
2757
+ return lowerPadStart(node, environment, scope);
2758
+ }
2759
+ if (textCall === 'slice') {
2760
+ return lowerSlice(node, environment, scope);
2761
+ }
2762
+ if (textCall === 'toUpperCase') {
2763
+ return lowerToUpperCase(node, environment, scope);
2764
+ }
2765
+ // A branch or operand that builds text needs its own format; refuse before lowerExpr's misleading error.
2766
+ const concatenates = (subExpression) => (subExpression.type === 'BinaryExpression' &&
2767
+ subExpression.operator === '+' &&
2768
+ lowerTextParts(subExpression, environment, scope, true).isString) ||
2769
+ ((subExpression.type === 'TemplateLiteral' ||
2770
+ textCallOf(subExpression, environment, scope) !== null) &&
2771
+ !foldsStatically(subExpression, scope));
1540
2772
  if (node.type === 'ConditionalExpression' &&
1541
2773
  (concatenates(node.test) ||
1542
2774
  concatenates(node.consequent) ||
@@ -1551,51 +2783,112 @@ function lowerTextParts(node, env, scope, isOperand = false) {
1551
2783
  'string first in a string useState.');
1552
2784
  }
1553
2785
  // Anything else is one runtime value.
1554
- const value = lowerExprWide(node, env);
1555
- // C collapses `&&`/`||` to 0/1 and a ternary to one slot, so text matches JS only when operands agree in kind.
1556
- if (node.type === 'LogicalExpression' && !isBoolean(value.type)) {
2786
+ const value = lowerExprWide(node, environment);
2787
+ // `&&`/`||` collapse to 0/1 and a ternary to one slot, so text matches JS only when operands agree in kind.
2788
+ if (node.type === 'LogicalExpression' &&
2789
+ node.operator !== '??' &&
2790
+ shapeOf(value) !== 'bool') {
1557
2791
  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 ` +
1558
- `generated C only has 0/1. Write the branch out instead: {cond ? 'yes' : ''}.`);
2792
+ `package only has 0/1. Write the branch out instead: {cond ? 'yes' : ''}.`);
1559
2793
  }
2794
+ const narrowing = node.type === 'ConditionalExpression'
2795
+ ? narrowOn(node.test, environment)
2796
+ : null;
1560
2797
  if (node.type === 'ConditionalExpression' &&
1561
- isBoolean(lowerExprWide(node.consequent, env).type) !==
1562
- isBoolean(lowerExprWide(node.alternate, env).type)) {
2798
+ (shapeOf(lowerExprWide(node.consequent, narrowed(environment, narrowing.whenTrue))) ===
2799
+ 'bool') !==
2800
+ (shapeOf(lowerExprWide(node.alternate, narrowed(environment, narrowing.whenFalse))) ===
2801
+ 'bool')) {
1563
2802
  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 ' +
1564
- 'C slot here. Make both branches the same kind.');
2803
+ 'slot here. Make both branches the same kind.');
1565
2804
  }
2805
+ // A list item's field that isn't there prints as undefined does.
2806
+ const missing = itemReadOf(value)
2807
+ ? { missing: isOperand ? 'undefined' : '' }
2808
+ : {};
1566
2809
  // A boolean prints nothing as a child, "true"/"false" as an operand; isString stays false so `on + n` adds.
1567
- if (isBoolean(value.type)) {
2810
+ if (shapeOf(value) === 'bool') {
1568
2811
  return isOperand
1569
- ? { isString: false, parts: [{ kind: 'booleanWord', value }] }
2812
+ ? { isString: false, parts: [{ kind: 'booleanWord', value, ...missing }] }
1570
2813
  : { isString: false, parts: [{ kind: 'literal', text: '' }] };
1571
2814
  }
1572
2815
  return {
1573
- isString: value.type.kind === 'string',
1574
- parts: [{ kind: 'value', value }],
2816
+ isString: shapeOf(value) === 'string',
2817
+ parts: [{ kind: 'value', value, ...missing }],
1575
2818
  };
1576
2819
  }
1577
2820
  /**
1578
- * Lowers an expression to text for a char-buffer destination (a <Text> body, a string state slot, a
1579
- * <TextInput value>). A string-building `+` chain becomes its parts in order; anything else is one value.
2821
+ * Settles a text's parts once its values are typed: a whole number has no letters for toUpperCase to change, so
2822
+ * it is printed as it is.
1580
2823
  *
1581
- * @param node The expression.
1582
- * @param env The expression environment.
1583
- * @param scope The constants a fold may read; by default the env's.
2824
+ * @param parts The parts.
1584
2825
  *
1585
- * @returns The text.
2826
+ * @returns The parts.
1586
2827
  */
1587
- export function lowerText(node, env, scope = env.consts ?? {}) {
1588
- return { parts: lowerTextParts(node, env, foldScope(env, scope)).parts };
2828
+ function typedParts(parts) {
2829
+ const cased = parts.filter(part => part.kind === 'value' && part.edits?.some(edit => edit.kind === 'upper'));
2830
+ if (cased.length) {
2831
+ whenTyped(() => {
2832
+ for (const part of cased) {
2833
+ const { kind } = part.value.type;
2834
+ if (kind !== 'int' && kind !== 'int64')
2835
+ continue;
2836
+ const edits = part.edits.filter(edit => edit.kind !== 'upper');
2837
+ if (edits.length) {
2838
+ part.edits = edits;
2839
+ }
2840
+ else {
2841
+ delete part.edits;
2842
+ }
2843
+ }
2844
+ });
2845
+ }
2846
+ return parts;
1589
2847
  }
1590
2848
  /**
1591
- * lowerText, printed as one printf format and its arguments (one spec per runtime value, literals folded in).
2849
+ * Lowers `console.log`'s arguments to the line it prints: each as a string `+` prints it, a space between them.
2850
+ *
2851
+ * @param callArguments The call's arguments.
2852
+ * @param environment The expression environment.
2853
+ *
2854
+ * @returns The line.
2855
+ */
2856
+ export function lowerLogText(callArguments, environment) {
2857
+ const scope = foldScope(environment, environment.constants ?? {});
2858
+ const parts = [];
2859
+ callArguments.forEach((argument, index) => {
2860
+ if (argument.type === 'SpreadElement') {
2861
+ throw textShapeError(argument, 'AOT: console.* cannot take a spread', 'pass each value itself: console.log(a, b).');
2862
+ }
2863
+ // An object or a list that folds would print as `+` prints it, "[object Object]".
2864
+ let folded;
2865
+ try {
2866
+ folded = evalStatic(argument, scope, 'strict');
2867
+ }
2868
+ catch {
2869
+ /* not a compile-time constant */
2870
+ }
2871
+ if (folded !== null && typeof folded === 'object') {
2872
+ throw textShapeError(argument, 'AOT: console.* cannot print an object or a list', 'print its fields or items: console.log(point.x, point.y).');
2873
+ }
2874
+ if (index > 0)
2875
+ parts.push({ kind: 'literal', text: ' ' });
2876
+ parts.push(...lowerTextParts(argument, environment, scope, true).parts);
2877
+ });
2878
+ return { parts: typedParts(parts) };
2879
+ }
2880
+ /**
2881
+ * Lowers an expression to text for a char-buffer destination (a <Text> body, a string state slot, a
2882
+ * <TextInput value>). A string-building `+` chain becomes its parts in order; anything else is one value.
1592
2883
  *
1593
2884
  * @param node The expression.
1594
- * @param env The expression environment.
2885
+ * @param environment The expression environment.
1595
2886
  * @param scope The constants a fold may read; by default the env's.
1596
2887
  *
1597
- * @returns The format, with literal `%` already escaped as `%%`, and its arguments.
2888
+ * @returns The text.
1598
2889
  */
1599
- export function emitFormat(node, env, scope = env.consts ?? {}) {
1600
- return printText(lowerText(node, env, scope));
2890
+ export function lowerText(node, environment, scope = environment.constants ?? {}) {
2891
+ return {
2892
+ parts: typedParts(lowerTextParts(node, environment, foldScope(environment, scope)).parts),
2893
+ };
1601
2894
  }