embedded-react 0.20.0 → 0.22.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 (140) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +3 -2
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +17 -47
  5. package/aot/compiler/alerts.mjs +604 -0
  6. package/aot/compiler/animations.mjs +299 -57
  7. package/aot/compiler/boot.mjs +27 -2
  8. package/aot/compiler/check.mjs +62 -10
  9. package/aot/compiler/collect.mjs +517 -137
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +276 -117
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/elements/button.mjs +182 -0
  14. package/aot/compiler/elements/image-background.mjs +76 -0
  15. package/aot/compiler/elements/image.mjs +2 -1
  16. package/aot/compiler/elements/props.mjs +47 -8
  17. package/aot/compiler/elements/rewrite.mjs +118 -0
  18. package/aot/compiler/elements/section-list.mjs +370 -0
  19. package/aot/compiler/expressions.mjs +1378 -97
  20. package/aot/compiler/handlers.mjs +1807 -354
  21. package/aot/compiler/helper-values.mjs +312 -0
  22. package/aot/compiler/ir/nodes.mjs +40 -1
  23. package/aot/compiler/ir/reads.mjs +206 -5
  24. package/aot/compiler/ir/text.mjs +5 -1
  25. package/aot/compiler/ir/types.mjs +12 -0
  26. package/aot/compiler/kept-states.mjs +177 -0
  27. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  28. package/aot/compiler/keyboard.mjs +1 -1
  29. package/aot/compiler/list-items.mjs +226 -0
  30. package/aot/compiler/list-order.mjs +586 -0
  31. package/aot/compiler/list-split.mjs +259 -0
  32. package/aot/compiler/loops.mjs +582 -0
  33. package/aot/compiler/lower.mjs +203 -53
  34. package/aot/compiler/native-files.mjs +439 -0
  35. package/aot/compiler/native-header.mjs +335 -0
  36. package/aot/compiler/native-modules.mjs +1173 -0
  37. package/aot/compiler/nodes.mjs +45 -31
  38. package/aot/compiler/options.mjs +3 -2
  39. package/aot/compiler/out.mjs +18 -1
  40. package/aot/compiler/package/animations.mjs +133 -23
  41. package/aot/compiler/package/assemble.mjs +2 -4
  42. package/aot/compiler/package/bytecode.mjs +37 -8
  43. package/aot/compiler/package/checks.mjs +4 -0
  44. package/aot/compiler/package/codegen.mjs +906 -33
  45. package/aot/compiler/package/enums.mjs +10 -0
  46. package/aot/compiler/package/format.mjs +16 -3
  47. package/aot/compiler/package/lower.mjs +707 -176
  48. package/aot/compiler/package/string-caps.mjs +515 -0
  49. package/aot/compiler/package/tables.mjs +24 -0
  50. package/aot/compiler/package/writer.mjs +22 -0
  51. package/aot/compiler/parse.mjs +3 -1
  52. package/aot/compiler/record-shapes.mjs +246 -0
  53. package/aot/compiler/records.mjs +654 -0
  54. package/aot/compiler/reducers.mjs +272 -0
  55. package/aot/compiler/scroll-to.mjs +112 -0
  56. package/aot/compiler/static-eval.mjs +315 -7
  57. package/aot/compiler/style-text.mjs +20 -5
  58. package/aot/compiler/svg.mjs +13 -7
  59. package/aot/compiler/switch-cases.mjs +198 -0
  60. package/aot/compiler/tagged-records.mjs +450 -0
  61. package/aot/compiler/typing.mjs +307 -0
  62. package/aot/compiler/updaters.mjs +321 -0
  63. package/aot/compiler/window-dimensions.mjs +94 -0
  64. package/aot/compiler/worked-values.mjs +319 -0
  65. package/aot/demo-file.mjs +30 -0
  66. package/aot/style-map.mjs +94 -3
  67. package/assets/bake-font.mjs +187 -244
  68. package/assets/bake-image.mjs +47 -71
  69. package/assets/bake-svg.mjs +465 -533
  70. package/assets/build-builtin-font.mjs +14 -27
  71. package/assets/emit-c.mjs +124 -204
  72. package/assets/emit-container.mjs +129 -197
  73. package/assets/emit-pack.mjs +92 -136
  74. package/assets/font-config.mjs +19 -27
  75. package/assets/font-sizes.mjs +432 -507
  76. package/assets/glyph-coverage.mjs +170 -214
  77. package/assets/index.mjs +52 -97
  78. package/assets/rasterize.mjs +173 -194
  79. package/assets/svg-loader.mjs +42 -48
  80. package/build.mjs +85 -94
  81. package/cli.mjs +490 -586
  82. package/compile-bin.mjs +24 -36
  83. package/flash.mjs +297 -401
  84. package/hotreload/dev-device.mjs +229 -270
  85. package/hotreload/pack-app.mjs +118 -159
  86. package/hotreload/pack-split.mjs +146 -213
  87. package/hotreload/package-transfer.mjs +128 -131
  88. package/hotreload/protocol.mjs +118 -118
  89. package/hotreload/uploader.mjs +132 -159
  90. package/hotreload/watch-tree.mjs +56 -65
  91. package/pack-container.mjs +94 -116
  92. package/package.json +19 -16
  93. package/persist-transform.mjs +89 -105
  94. package/qjsc-wasm.mjs +47 -72
  95. package/sim/embedded-react.wasm +0 -0
  96. package/sim/index.html +1 -1
  97. package/sim-server.mjs +260 -354
  98. package/src/embedded-react/Alert.mjs +112 -0
  99. package/src/embedded-react/Animated.mjs +412 -0
  100. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  101. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  102. package/src/embedded-react/Dimensions.mjs +32 -0
  103. package/src/embedded-react/Easing.mjs +34 -0
  104. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  105. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  106. package/src/embedded-react/Keyboard.mjs +82 -0
  107. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  108. package/src/embedded-react/PanResponder.mjs +256 -0
  109. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  110. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  111. package/src/embedded-react/SectionList.mjs +103 -0
  112. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  113. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  114. package/src/embedded-react/background-image.mjs +321 -0
  115. package/src/embedded-react/{components.js → components.mjs} +1 -3
  116. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  117. package/src/embedded-react/index.d.ts +238 -5
  118. package/src/embedded-react/index.js +26 -17
  119. package/src/embedded-react/layout-anim-config.mjs +85 -0
  120. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  121. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  122. package/src/embedded-react/nativeModule.mjs +371 -0
  123. package/src/embedded-react/split-style.mjs +57 -0
  124. package/src/embedded-react/svg-ops.mjs +1075 -0
  125. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  126. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  127. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  128. package/src/host-config.mjs +512 -0
  129. package/src/{native-ui.js → native-ui.mjs} +1 -8
  130. package/src/props.mjs +341 -0
  131. package/src/{renderer.js → renderer.mjs} +30 -44
  132. package/src/embedded-react/Animated.js +0 -440
  133. package/src/embedded-react/Easing.js +0 -39
  134. package/src/embedded-react/PanResponder.js +0 -330
  135. package/src/embedded-react/SectionList.js +0 -148
  136. package/src/embedded-react/layout-anim-config.js +0 -101
  137. package/src/embedded-react/split-style.js +0 -58
  138. package/src/embedded-react/svg-ops.js +0 -1295
  139. package/src/host-config.js +0 -548
  140. package/src/props.js +0 -306
@@ -16,13 +16,24 @@
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 { BOOL, FLOAT, INT, INT64_NUMBER, INT64_MATH, STRING, TIME, isBoolean, isConvertible64, isIntSlot, isTime, int64Join, int64Of, stateType, refType, slotOf, typeOfSlot, typeOfSlotValue, } 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 { unkeptScrollError } from './scroll-to.mjs';
35
+ import { TEXT_END } from './ir/text.mjs';
36
+ 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';
26
37
  /*----------------------------------------------------------------------------------------------------------------------
27
38
  - Constants
28
39
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -46,6 +57,14 @@ const WHOLE_BOOT_TYPES = new Set([
46
57
  /** The range of an int. */
47
58
  const INT_MIN = -(2 ** 31);
48
59
  export const INT_MAX = 2 ** 31 - 1;
60
+ /** The type a native method's result is read as. */
61
+ const NATIVE_TYPES = {
62
+ int: INT,
63
+ float: FLOAT,
64
+ bool: BOOL,
65
+ int64: INT64_NUMBER,
66
+ string: STRING,
67
+ };
49
68
  /** The Math functions that keep a whole number whole. */
50
69
  const WHOLE_MATH = new Set([
51
70
  'floor',
@@ -77,6 +96,8 @@ const FLOAT_MATH_UNARY = new Set([
77
96
  const FLOAT_MATH_BINARY = new Set(['min', 'max', 'atan2', 'pow']);
78
97
  /** While the typing pass infers slot widths: the slots it takes to hold 64 bits, and what each holds. */
79
98
  let assumedWide = null;
99
+ /** How a state or local whose type the typing pass works out is typed while it infers slot widths. */
100
+ const assumedTypes = new WeakMap();
80
101
  /** The fields of an onLayout rect. */
81
102
  const LAYOUT_FIELDS = new Set(['x', 'y', 'width', 'height']);
82
103
  /** The largest 32-bit int. */
@@ -750,10 +771,15 @@ function typeBinary(source, math64) {
750
771
  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. ` +
751
772
  `Compare like with like, or use === / !== (which never coerce).`);
752
773
  }
753
- // Equality is exact, but strcmp's UTF-8 order can differ from JS's UTF-16 order, so refuse ordering.
774
+ // Strings order by UTF-16 code unit, as JS orders them.
754
775
  if (comparison !== '==' && comparison !== '!=') {
755
- throw aotError(`AOT: ordering strings with "${source.operator}" is not supported`, 'JS orders strings by UTF-16 code unit but the device holds UTF-8, so the order can ' +
756
- 'differ. Use === / !==, or compare numbers.');
776
+ return {
777
+ kind: 'compare',
778
+ operator: comparison,
779
+ left: { kind: 'stringOrder', left, right, type: INT },
780
+ right: { kind: 'number', value: 0, type: INT },
781
+ type: BOOL,
782
+ };
757
783
  }
758
784
  return {
759
785
  kind: 'stringEquals',
@@ -970,6 +996,105 @@ function typeMath(source, math64) {
970
996
  }
971
997
  throw new Error(`AOT: unsupported Math.${mathFunction}(...) (arity ${argumentExpressions.length})`);
972
998
  }
999
+ /**
1000
+ * A read of a local while slot widths are inferred, when the typing pass has yet to say what it holds: a local
1001
+ * is what it was set from, and a `let` what it was declared with or widened to, typed with the slots assumed so
1002
+ * far.
1003
+ *
1004
+ * @param local The local.
1005
+ *
1006
+ * @returns The typed read.
1007
+ */
1008
+ function assumedLocal(local) {
1009
+ const worked = assumedTypes.get(local);
1010
+ if (worked)
1011
+ return { kind: 'local', local, type: worked() };
1012
+ if (local.source)
1013
+ return typeSource(local.source, false);
1014
+ if (!local.assignable || !local.declared)
1015
+ return localRead(local);
1016
+ const declared = typeSource(local.declared, false);
1017
+ const width = declared.type.kind === 'int' ? assumedWide.get(local.assignable) : null;
1018
+ return {
1019
+ kind: 'local',
1020
+ local,
1021
+ type: !width ? declared.type : width === 'float' ? FLOAT : int64Of(width),
1022
+ };
1023
+ }
1024
+ /**
1025
+ * Says how a state or local the typing pass works out the type of is typed while it infers slot widths.
1026
+ *
1027
+ * @param slot The state or local.
1028
+ * @param type Its type, with the slots assumed so far.
1029
+ */
1030
+ export function assumeType(slot, type) {
1031
+ assumedTypes.set(slot, type);
1032
+ }
1033
+ /**
1034
+ * The type a state or local is taken to have while slot widths are inferred (see assumeType).
1035
+ *
1036
+ * @param slot The state or local.
1037
+ *
1038
+ * @returns Its type, with the slots assumed so far.
1039
+ */
1040
+ export const assumedTypeOf = (slot) => assumedTypes.get(slot)();
1041
+ /**
1042
+ * The shape of a scalar state's value.
1043
+ *
1044
+ * @param state The state.
1045
+ *
1046
+ * @returns The shape.
1047
+ */
1048
+ export const stateShape = (state) => state.isBoolean ? 'bool' : localShape(state);
1049
+ /**
1050
+ * Whether a state's type is settled where it is declared: only a whole-number slot widens.
1051
+ *
1052
+ * @param state The state.
1053
+ *
1054
+ * @returns True for a string, a boolean or a float.
1055
+ */
1056
+ const isSettledState = (state) => state.isBoolean ||
1057
+ (!holdsUntyped(state) &&
1058
+ (state.slotKind === 'string' || state.slotKind === 'float'));
1059
+ /**
1060
+ * A read of a scalar state's value, typed once the slot's width is known.
1061
+ *
1062
+ * @param state The state.
1063
+ * @param latest It reads the value a setter left, not the render's.
1064
+ *
1065
+ * @returns The read.
1066
+ */
1067
+ export function stateRead(state, latest = false) {
1068
+ const source = {
1069
+ kind: 'state',
1070
+ state,
1071
+ ...(latest ? { latest: true } : {}),
1072
+ location: undefined,
1073
+ };
1074
+ return isSettledState(state)
1075
+ ? typeSource(source, false)
1076
+ : typedLater(stateShape(state), () => typeSource(source, false), source);
1077
+ }
1078
+ /**
1079
+ * Whether a state or ref slot holds 64 bits, counting the slots the typing pass assumes to while it infers
1080
+ * widths.
1081
+ *
1082
+ * @param slot The state or ref.
1083
+ *
1084
+ * @returns True for a 64-bit slot.
1085
+ */
1086
+ export const is64BitSlot = (slot) => slot.slotKind === 'i64' ||
1087
+ (slot.slotKind === 'int' &&
1088
+ wideSlotOf(assumedWide, slot.slotName) !== undefined);
1089
+ /**
1090
+ * Whether a `let` holds 64 bits (see is64BitSlot).
1091
+ *
1092
+ * @param local The local.
1093
+ *
1094
+ * @returns True for a 64-bit local.
1095
+ */
1096
+ export const is64BitLocal = (local) => (assumedWide ? assumedLocal(local).type : typeOfSlotValue(local)).kind ===
1097
+ 'int64';
973
1098
  /**
974
1099
  * The typing pass over one source expression: gives it its type and decides how it is computed. Pure, so a
975
1100
  * subexpression can be typed again, as whole-number math beside a 64-bit value is. An AOT error is pinned to
@@ -993,26 +1118,35 @@ export function typeSource(source, math64) {
993
1118
  return boolConst(source.value);
994
1119
  case 'state': {
995
1120
  const { state } = source;
1121
+ const worked = assumedWide ? assumedTypes.get(state) : undefined;
1122
+ if (worked) {
1123
+ return {
1124
+ kind: 'state',
1125
+ state,
1126
+ type: worked(),
1127
+ ...(source.latest ? { latest: true } : {}),
1128
+ };
1129
+ }
996
1130
  const assumed = (state.slotKind === 'int' || state.slotKind === 'i64') &&
997
1131
  !state.isBoolean
998
- ? assumedWide?.get(state.slotName)
1132
+ ? wideSlotOf(assumedWide, state.slotName)
999
1133
  : undefined;
1000
1134
  return {
1001
1135
  kind: 'state',
1002
1136
  state,
1003
1137
  type: assumed ? int64Of(assumed) : stateType(state),
1138
+ ...(source.latest ? { latest: true } : {}),
1004
1139
  };
1005
1140
  }
1006
1141
  case 'local':
1007
- // While slot widths are inferred, a local is what it was set from, typed with the slots assumed so far.
1008
- return assumedWide && source.local.source
1009
- ? typeSource(source.local.source, false)
1142
+ return assumedWide
1143
+ ? assumedLocal(source.local)
1010
1144
  : localRead(source.local);
1011
1145
  case 'ref': {
1012
1146
  const { ref } = source;
1013
1147
  const assumed = ref.kind === 'value' &&
1014
1148
  (ref.slotKind === 'int' || ref.slotKind === 'i64')
1015
- ? assumedWide?.get(ref.slotName)
1149
+ ? wideSlotOf(assumedWide, ref.slotName)
1016
1150
  : undefined;
1017
1151
  return {
1018
1152
  kind: 'ref',
@@ -1042,8 +1176,8 @@ export function typeSource(source, math64) {
1042
1176
  /**
1043
1177
  * Infers the slots that have to hold 64 bits: an int slot a value stored into is a 64-bit number, once the
1044
1178
  * slots found so far are taken to hold 64 bits too, until no more are found. Each one holds a time when a time
1045
- * is stored into it, and only 64-bit numbers otherwise. A value whose typing fails leaves its slot as it is;
1046
- * lowering it again reports the error.
1179
+ * is stored into it, and only 64-bit numbers otherwise. A `let` local given a fraction holds a float instead. A
1180
+ * value whose typing fails leaves its slot as it is; lowering it again reports the error.
1047
1181
  *
1048
1182
  * @param stores Every value lowering stored into an int slot, or into a 64-bit one that holds no time yet.
1049
1183
  * @param wide The slots already 64-bit.
@@ -1056,11 +1190,24 @@ export function inferWideSlots(stores, wide) {
1056
1190
  while (grew) {
1057
1191
  grew = false;
1058
1192
  for (const store of stores) {
1059
- if (inferred.get(store.slot) === 'time')
1193
+ const width = inferred.get(store.slot);
1194
+ if (width === 'time' || width === 'float')
1060
1195
  continue;
1061
1196
  assumedWide = inferred;
1062
1197
  try {
1063
- const { type } = typeSource(store.value, store.math64);
1198
+ // Only a `let` that holds whole numbers widens.
1199
+ if (store.local) {
1200
+ const held = assumedLocal(store.local).type;
1201
+ if (held.kind !== 'int' && held !== INT64_NUMBER)
1202
+ continue;
1203
+ }
1204
+ const { type } = typeSource(store.value, store.math64?.() ?? false);
1205
+ // A `let` given a fraction holds floats.
1206
+ if (store.local && type.kind === 'float') {
1207
+ inferred.set(store.slot, 'float');
1208
+ grew = true;
1209
+ continue;
1210
+ }
1064
1211
  if (type.kind !== 'int64')
1065
1212
  continue;
1066
1213
  const holds = type.source === 'time' ? 'time' : 'number';
@@ -1069,8 +1216,11 @@ export function inferWideSlots(stores, wide) {
1069
1216
  grew = true;
1070
1217
  }
1071
1218
  }
1072
- catch {
1073
- // Lowering the value again, with the widths inferred, reports its error.
1219
+ catch (error) {
1220
+ // The typing pass reports its error, with the widths inferred.
1221
+ if (String(error?.message).startsWith('AOT internal')) {
1222
+ throw error;
1223
+ }
1074
1224
  }
1075
1225
  finally {
1076
1226
  assumedWide = null;
@@ -1079,16 +1229,6 @@ export function inferWideSlots(stores, wide) {
1079
1229
  }
1080
1230
  return inferred;
1081
1231
  }
1082
- /**
1083
- * Whether two sets of slot widths are the same.
1084
- *
1085
- * @param left One set.
1086
- * @param right The other.
1087
- *
1088
- * @returns True when every slot holds the same in both.
1089
- */
1090
- export const sameSlotWidths = (left, right) => left.size === right.size &&
1091
- [...left].every(([slot, holds]) => right.get(slot) === holds);
1092
1232
  /**
1093
1233
  * Whether an operand is written as a number, so a boolean on the other side of `===` never equals it: a
1094
1234
  * numeric literal, a negated one, or a non-boolean state read by name.
@@ -1115,7 +1255,7 @@ const isWrittenAsNumber = (node, environment) => node.type === 'NumericLiteral'
1115
1255
  *
1116
1256
  * @returns The source.
1117
1257
  */
1118
- const binarySource = (node, left, right, environment) => ({
1258
+ export const binarySource = (node, left, right, environment) => ({
1119
1259
  kind: 'binary',
1120
1260
  operator: node.operator,
1121
1261
  left,
@@ -1128,6 +1268,16 @@ const binarySource = (node, left, right, environment) => ({
1128
1268
  rightIsNumber: isWrittenAsNumber(node.right, environment),
1129
1269
  location: node.loc?.start,
1130
1270
  });
1271
+ /**
1272
+ * An onScroll handler read a touch field, which a scroll event doesn't carry.
1273
+ *
1274
+ * @param field The field read.
1275
+ *
1276
+ * @returns The error to throw.
1277
+ */
1278
+ function scrollTouchError(field) {
1279
+ return aotError(`AOT: an onScroll event carries no touch, so it has no "${field}"`, 'read e.scrollX / e.scrollY — the offset is all a scroll event has.');
1280
+ }
1131
1281
  /**
1132
1282
  * Whether `node` is the handler's event, or its `nativeEvent` as React Native code reads it.
1133
1283
  *
@@ -1147,6 +1297,469 @@ function isEventRoot(node, event) {
1147
1297
  node.object.name === event &&
1148
1298
  node.property.name === 'nativeEvent');
1149
1299
  }
1300
+ /**
1301
+ * The type a list item's field reads as.
1302
+ *
1303
+ * @param field The field.
1304
+ *
1305
+ * @returns Its type.
1306
+ */
1307
+ export const fieldType = (field) => field.kind === 'bool' ? BOOL : typeOfSlot(field.kind);
1308
+ /**
1309
+ * A member's key when it is a name: `a.b`, or `a['b']`.
1310
+ *
1311
+ * @param node The member.
1312
+ *
1313
+ * @returns The key, or null for a computed one.
1314
+ */
1315
+ function memberKey(node) {
1316
+ if (!node.computed)
1317
+ return node.property.name;
1318
+ return node.property.type === 'StringLiteral' ? node.property.value : null;
1319
+ }
1320
+ /**
1321
+ * Whether a value holds a value worked out at run time, at any depth.
1322
+ *
1323
+ * @param value The value.
1324
+ *
1325
+ * @returns Whether it does.
1326
+ */
1327
+ const holdsRuntime = (value) => value instanceof RuntimeLeaf ||
1328
+ ((Array.isArray(value) || isPlainObject(value)) &&
1329
+ Object.values(value).some(holdsRuntime));
1330
+ /**
1331
+ * A constant array read by a runtime index, kept as a list whose rows are set at boot and never change.
1332
+ *
1333
+ * @param array The array.
1334
+ * @param node What names it, for its name and errors.
1335
+ * @param environment The expression environment.
1336
+ *
1337
+ * @returns The list.
1338
+ */
1339
+ export function constantListOf(array, node, environment) {
1340
+ const lists = environment.constantLists;
1341
+ if (!lists) {
1342
+ throw new Error('AOT internal: no table for constant lists');
1343
+ }
1344
+ const known = lists.get(array);
1345
+ if (known)
1346
+ return known;
1347
+ if (holdsRuntime(array)) {
1348
+ 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.');
1349
+ }
1350
+ const name = node.type === 'Identifier' ? node.name : 'array';
1351
+ if (array.length > MAX_LIST_CAPACITY) {
1352
+ 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.');
1353
+ }
1354
+ const list = {
1355
+ kind: 'list',
1356
+ name,
1357
+ slotName: `k${lists.size}_${name}`,
1358
+ setter: undefined,
1359
+ struct: inferItemStruct(array, `the array "${name}"`),
1360
+ items: array,
1361
+ capacity: array.length,
1362
+ constant: true,
1363
+ initialAt: node.loc?.start,
1364
+ };
1365
+ lists.set(array, list);
1366
+ return list;
1367
+ }
1368
+ /**
1369
+ * The list a computed member reads a row of by a runtime index: a list state, or a constant array. A constant
1370
+ * array's element at a constant index folds instead.
1371
+ *
1372
+ * @param node The member.
1373
+ * @param environment The expression environment.
1374
+ *
1375
+ * @returns The list, or null when it is neither.
1376
+ */
1377
+ function indexedListOf(node, environment) {
1378
+ return listValueOf(node.object, environment, node.property);
1379
+ }
1380
+ /**
1381
+ * The list an expression names: a list state, a list worked out in render, or a constant array.
1382
+ *
1383
+ * @param node The expression.
1384
+ * @param environment The expression environment.
1385
+ * @param index The index it is read by, when a constant one folds the read instead.
1386
+ *
1387
+ * @returns The list, or null when it is none.
1388
+ */
1389
+ export function listValueOf(node, environment, index) {
1390
+ // A local hides a state of the same name.
1391
+ if (node.type === 'Identifier' && environment.locals.has(node.name)) {
1392
+ return null;
1393
+ }
1394
+ if (node.type === 'Identifier' && environment.state.has(node.name)) {
1395
+ const record = environment.state.get(node.name);
1396
+ return record.kind === 'list' ? record : null;
1397
+ }
1398
+ const derived = derivedListOf(node, environment);
1399
+ if (derived)
1400
+ return derived;
1401
+ const scope = foldScope(environment, environment.constants ?? {});
1402
+ const folds = (part) => {
1403
+ try {
1404
+ return { value: evalStatic(part, scope, 'boot') };
1405
+ }
1406
+ catch (error) {
1407
+ rethrowFoldLimit(error);
1408
+ return null;
1409
+ }
1410
+ };
1411
+ if (index && folds(index))
1412
+ return null;
1413
+ const array = folds(node)?.value;
1414
+ return Array.isArray(array) ? constantListOf(array, node, environment) : null;
1415
+ }
1416
+ /**
1417
+ * 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
1418
+ * plain value by index (`values[i]`). `?.` after an index reads undefined past the list's end.
1419
+ *
1420
+ * @param node The expression.
1421
+ * @param environment The expression environment.
1422
+ *
1423
+ * @returns The item and the path under it, or null when it reads no list item.
1424
+ */
1425
+ function itemPathOf(node, environment) {
1426
+ if (node.type === 'TSNonNullExpression') {
1427
+ return itemPathOf(node.expression, environment);
1428
+ }
1429
+ if (node.type === 'Identifier') {
1430
+ const local = environment.locals.get(node.name);
1431
+ return local?.struct && local.list ? { item: local, path: [] } : null;
1432
+ }
1433
+ if (node.type !== 'MemberExpression' &&
1434
+ node.type !== 'OptionalMemberExpression') {
1435
+ return null;
1436
+ }
1437
+ const key = memberKey(node);
1438
+ if (key !== null) {
1439
+ const base = itemPathOf(node.object, environment);
1440
+ if (!base)
1441
+ return null;
1442
+ const guards = node.optional && !base.path.length && base.item.index !== undefined;
1443
+ return {
1444
+ item: guards ? { ...base.item, guarded: true } : base.item,
1445
+ path: [...base.path, key],
1446
+ };
1447
+ }
1448
+ const list = indexedListOf(node, environment);
1449
+ if (!list)
1450
+ return null;
1451
+ const index = lowerExpr(node.property, environment);
1452
+ whenTyped(() => {
1453
+ if (index.type.kind !== 'int') {
1454
+ 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.');
1455
+ }
1456
+ });
1457
+ // A plain value past the end is undefined; a field of an item there throws in JS, and faults here.
1458
+ const item = rowItemOf(list, { name: `${list.name}[]`, index });
1459
+ return {
1460
+ item: { ...item, guarded: !!item.struct.plain },
1461
+ path: [],
1462
+ };
1463
+ }
1464
+ /**
1465
+ * The source of a read into a list item: a field, or whether an object of fields (or the item) is there, as
1466
+ * an object is truthy.
1467
+ *
1468
+ * @param itemPath The read.
1469
+ * @param location Where it is.
1470
+ *
1471
+ * @returns The source.
1472
+ */
1473
+ function itemSource({ item, path }, location) {
1474
+ const struct = item.struct;
1475
+ const key = path.join('.');
1476
+ const field = struct.fields.find(entry => entry.key === key);
1477
+ if (field && (path.length || struct.plain)) {
1478
+ return {
1479
+ kind: 'fixed',
1480
+ expression: { kind: 'itemField', item, field, type: fieldType(field) },
1481
+ location,
1482
+ };
1483
+ }
1484
+ const fields = path.length ? fieldsUnder(struct, path) : [];
1485
+ if (path.length && !fields.length) {
1486
+ throw new Error(`AOT: unknown field "${key}" on a list item`);
1487
+ }
1488
+ return {
1489
+ kind: 'fixed',
1490
+ expression: { kind: 'itemPresent', item, fields, type: BOOL },
1491
+ location,
1492
+ };
1493
+ }
1494
+ /**
1495
+ * The row of a list a whole item names, `items[i]`, for passing to a component.
1496
+ *
1497
+ * @param node The expression.
1498
+ * @param environment The expression environment.
1499
+ *
1500
+ * @returns The item, or null when it names none.
1501
+ */
1502
+ export function listItemOf(node, environment) {
1503
+ if (node.type !== 'MemberExpression' || !node.computed)
1504
+ return null;
1505
+ const itemPath = itemPathOf(node, environment);
1506
+ return itemPath && !itemPath.item.struct.plain ? itemPath.item : null;
1507
+ }
1508
+ /**
1509
+ * Whether a value is there, where it can be missing: a list item's field, an object of fields or an item, or a
1510
+ * local that stands for a field read.
1511
+ *
1512
+ * @param node The expression.
1513
+ * @param environment The expression environment.
1514
+ *
1515
+ * @returns A boolean expression, or null when the value is always there.
1516
+ */
1517
+ function presenceOf(node, environment) {
1518
+ const itemPath = itemPathOf(node, environment);
1519
+ if (itemPath) {
1520
+ const read = itemSource(itemPath, undefined);
1521
+ const { expression } = read;
1522
+ return expression.kind === 'itemField'
1523
+ ? {
1524
+ kind: 'itemPresent',
1525
+ item: expression.item,
1526
+ fields: [expression.field],
1527
+ type: BOOL,
1528
+ }
1529
+ : expression;
1530
+ }
1531
+ if (node.type === 'Identifier' && environment.locals.has(node.name)) {
1532
+ const local = environment.locals.get(node.name);
1533
+ const read = local.expression ? itemReadOf(local.expression) : null;
1534
+ if (read) {
1535
+ return {
1536
+ kind: 'itemPresent',
1537
+ item: read.item,
1538
+ fields: [read.field],
1539
+ type: BOOL,
1540
+ };
1541
+ }
1542
+ }
1543
+ return null;
1544
+ }
1545
+ /**
1546
+ * Whether an expression is null or undefined, as a constant.
1547
+ *
1548
+ * @param node The expression.
1549
+ * @param environment The expression environment.
1550
+ *
1551
+ * @returns Whether it is.
1552
+ */
1553
+ function isNullish(node, environment) {
1554
+ if (node.type === 'Identifier' && node.name === 'undefined')
1555
+ return true;
1556
+ try {
1557
+ return (evalStatic(node, foldScope(environment, environment.constants ?? {})) ==
1558
+ null);
1559
+ }
1560
+ catch (error) {
1561
+ rethrowFoldLimit(error);
1562
+ return false;
1563
+ }
1564
+ }
1565
+ /**
1566
+ * `x === undefined`, `x !== undefined`, `x == null` and `x != null` (either way round) on a value that can be
1567
+ * missing: whether it is there.
1568
+ *
1569
+ * @param node The comparison.
1570
+ * @param environment The expression environment.
1571
+ *
1572
+ * @returns A boolean expression, or null when it is no such test.
1573
+ */
1574
+ function presenceTestOf(node, environment) {
1575
+ const { operator } = node;
1576
+ if (!['==', '!=', '===', '!=='].includes(operator))
1577
+ return null;
1578
+ const isUndefined = (side) => side.type === 'Identifier' && side.name === 'undefined';
1579
+ const matches = (side) => isUndefined(side) ||
1580
+ ((operator === '==' || operator === '!=') && side.type === 'NullLiteral');
1581
+ const value = matches(node.right)
1582
+ ? node.left
1583
+ : matches(node.left)
1584
+ ? node.right
1585
+ : null;
1586
+ if (!value || value.type === 'PrivateName')
1587
+ return null;
1588
+ const present = presenceOf(value, environment);
1589
+ if (!present)
1590
+ return null;
1591
+ return operator === '!=' || operator === '!=='
1592
+ ? present
1593
+ : { kind: 'unary', operator: '!', operand: present, type: BOOL };
1594
+ }
1595
+ /**
1596
+ * The local a member reads when it names a value worked out at run time in an array or object built in render.
1597
+ *
1598
+ * @param node The member.
1599
+ * @param environment The expression environment.
1600
+ *
1601
+ * @returns The local, or null.
1602
+ */
1603
+ function runtimeLeafOf(node, environment) {
1604
+ const key = memberKey(node);
1605
+ const scope = foldScope(environment, environment.constants ?? {});
1606
+ let container;
1607
+ let index = key;
1608
+ try {
1609
+ container = evalStatic(node.object, scope, 'boot');
1610
+ if (key === null) {
1611
+ index = evalStatic(node.property, scope);
1612
+ }
1613
+ }
1614
+ catch (error) {
1615
+ rethrowFoldLimit(error);
1616
+ return null;
1617
+ }
1618
+ const value = typeof container === 'object' && container !== null
1619
+ ? container[index]
1620
+ : undefined;
1621
+ if (value instanceof HiddenField)
1622
+ throw value.error();
1623
+ return value instanceof RuntimeLeaf ? value.local : null;
1624
+ }
1625
+ /**
1626
+ * Folds an array or object built in render: what folds stays a constant, and each value worked out at run time
1627
+ * becomes a RuntimeLeaf, so a `.map` over it unrolls and its constant fields still fold.
1628
+ *
1629
+ * @param node The expression.
1630
+ * @param environment The expression environment.
1631
+ * @param scope The constants it folds against.
1632
+ *
1633
+ * @returns The value.
1634
+ */
1635
+ export function foldRuntime(node, environment, scope = environment.constants ?? {}) {
1636
+ try {
1637
+ return evalStatic(node, scope, 'boot');
1638
+ }
1639
+ catch (error) {
1640
+ rethrowFoldLimit(error);
1641
+ }
1642
+ if (node.type === 'ArrayExpression') {
1643
+ return node.elements.map(element => {
1644
+ if (!element || element.type === 'SpreadElement') {
1645
+ throw aotError('AOT: an array built in render cannot have holes or spreads', 'write each element out.');
1646
+ }
1647
+ return foldRuntime(element, environment, scope);
1648
+ });
1649
+ }
1650
+ if (node.type === 'ObjectExpression') {
1651
+ const folded = {};
1652
+ for (const property of node.properties) {
1653
+ if (property.type === 'SpreadElement') {
1654
+ const spread = foldRuntime(property.argument, environment, scope);
1655
+ if (!isObjectTree(spread)) {
1656
+ 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}.');
1657
+ }
1658
+ Object.assign(folded, spread);
1659
+ continue;
1660
+ }
1661
+ if (property.type !== 'ObjectProperty' || property.computed) {
1662
+ 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.');
1663
+ }
1664
+ const key = property.key.name ??
1665
+ String(property.key.value);
1666
+ folded[key] = foldRuntime(property.value, environment, scope);
1667
+ }
1668
+ return folded;
1669
+ }
1670
+ return new RuntimeLeaf(lowerLocal(node, environment));
1671
+ }
1672
+ /**
1673
+ * Binds the names an object pattern destructures from an object built in render.
1674
+ *
1675
+ * @param pattern The pattern.
1676
+ * @param value The object.
1677
+ * @param environment The expression environment; the bindings go into its constants.
1678
+ */
1679
+ function bindPattern(pattern, value, environment) {
1680
+ const taken = new Set();
1681
+ for (const property of pattern.properties) {
1682
+ if (property.type === 'RestElement') {
1683
+ if (property.argument.type !== 'Identifier') {
1684
+ throw aotError('AOT: a rest element must be a plain name');
1685
+ }
1686
+ setBinding(environment.constants, property.argument.name, Object.fromEntries(Object.entries(value).filter(([key]) => !taken.has(key))));
1687
+ continue;
1688
+ }
1689
+ const key = propertyKey(property);
1690
+ if (!Object.hasOwn(value, key)) {
1691
+ throw aotError(`AOT: the object has no field "${key}" to destructure`, 'destructure only the fields the object holds, by name.');
1692
+ }
1693
+ taken.add(key);
1694
+ const field = value[key];
1695
+ if (property.value.type === 'Identifier') {
1696
+ setBinding(environment.constants, property.value.name, field);
1697
+ }
1698
+ else if (property.value.type === 'ObjectPattern' && isObjectTree(field)) {
1699
+ bindPattern(property.value, field, environment);
1700
+ }
1701
+ else {
1702
+ 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 `= …`.');
1703
+ }
1704
+ }
1705
+ }
1706
+ /**
1707
+ * Whether every name an object pattern takes is bound already.
1708
+ *
1709
+ * @param pattern The pattern.
1710
+ * @param scope The constants in reach.
1711
+ *
1712
+ * @returns True when each is.
1713
+ */
1714
+ function isPatternBound(pattern, scope) {
1715
+ return pattern.properties.every(property => {
1716
+ if (property.type === 'RestElement')
1717
+ return false;
1718
+ const { value } = property;
1719
+ if (value.type === 'Identifier')
1720
+ return hasBinding(scope, value.name);
1721
+ return value.type === 'ObjectPattern' && isPatternBound(value, scope);
1722
+ });
1723
+ }
1724
+ /**
1725
+ * Binds each `const` of a component body that builds an array or object in render from runtime values, as
1726
+ * foldRuntime folds it. A const that folds is bound already, and a hook's binding is not a literal.
1727
+ *
1728
+ * @param body The component's body.
1729
+ * @param environment Its expression environment; the bindings go into its constants.
1730
+ */
1731
+ export function bindBuiltValues(body, environment) {
1732
+ const scope = environment.constants;
1733
+ for (const statement of body) {
1734
+ if (statement.type !== 'VariableDeclaration' ||
1735
+ statement.kind !== 'const') {
1736
+ continue;
1737
+ }
1738
+ for (const declarator of statement.declarations) {
1739
+ const { id, init } = declarator;
1740
+ if (isContextRead(init))
1741
+ continue; // bound from its provider (see bindContextUses)
1742
+ if (id.type === 'ObjectPattern' && init) {
1743
+ if (isPatternBound(id, scope))
1744
+ continue; // folded already
1745
+ const value = foldRuntime(init, environment, scope);
1746
+ if (!isObjectTree(value)) {
1747
+ throw aotError('AOT: only an object can be destructured', 'destructure an object state, or an object built from fields.');
1748
+ }
1749
+ bindPattern(id, value, environment);
1750
+ continue;
1751
+ }
1752
+ if (id.type !== 'Identifier' ||
1753
+ (init?.type !== 'ArrayExpression' &&
1754
+ init?.type !== 'ObjectExpression') ||
1755
+ hasBinding(scope, id.name) ||
1756
+ environment.locals.has(id.name)) {
1757
+ continue;
1758
+ }
1759
+ setBinding(scope, id.name, foldRuntime(init, environment, scope));
1760
+ }
1761
+ }
1762
+ }
1150
1763
  /**
1151
1764
  * Lowers one JS expression to its source: names resolved, constants folded, and each operand lowered and typed
1152
1765
  * in turn, so an error in it is reported before anything after it.
@@ -1175,21 +1788,27 @@ function sourceOf(node, environment) {
1175
1788
  case 'Identifier': {
1176
1789
  // A name resolves to a local first, then to state, then to a compile-time constant.
1177
1790
  if (environment.locals.has(node.name)) {
1178
- return {
1179
- kind: 'local',
1180
- local: environment.locals.get(node.name),
1181
- location,
1182
- };
1791
+ const local = environment.locals.get(node.name);
1792
+ // An item of a list of plain values is its one field.
1793
+ if (local.struct?.plain && local.list) {
1794
+ return itemSource({ item: local, path: [] }, location);
1795
+ }
1796
+ return { kind: 'local', local, location };
1183
1797
  }
1184
1798
  if (environment.state.has(node.name)) {
1185
1799
  const stateRecord = environment.state.get(node.name);
1186
1800
  if (stateRecord.kind === 'list') {
1187
- throw new Error(`AOT: a list state ("${node.name}") can only be used via .length or .map`);
1801
+ throw new Error(`AOT: a list state ("${node.name}") can only be used via .length, .map or [index]`);
1188
1802
  }
1189
1803
  return { kind: 'state', state: stateRecord, location };
1190
1804
  }
1191
1805
  if (hasBinding(environment.constants, node.name)) {
1192
1806
  const constantValue = environment.constants[node.name];
1807
+ if (constantValue instanceof RuntimeLeaf) {
1808
+ return { kind: 'local', local: constantValue.local, location };
1809
+ }
1810
+ if (constantValue instanceof HiddenField)
1811
+ throw constantValue.error();
1193
1812
  if (isBoot(constantValue))
1194
1813
  return bootSource(constantValue, location);
1195
1814
  if (typeof constantValue === 'number')
@@ -1200,6 +1819,12 @@ function sourceOf(node, environment) {
1200
1819
  if (typeof constantValue === 'boolean') {
1201
1820
  return { kind: 'boolean', value: constantValue, location };
1202
1821
  }
1822
+ if (isObjectTree(constantValue)) {
1823
+ 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'}.`);
1824
+ }
1825
+ }
1826
+ if (readsNativeModule(node.name, environment)) {
1827
+ 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.`);
1203
1828
  }
1204
1829
  throw new Error(`AOT: cannot resolve identifier "${node.name}" in a dynamic expression`);
1205
1830
  }
@@ -1222,6 +1847,16 @@ function sourceOf(node, environment) {
1222
1847
  throw new Error(`AOT: unsupported unary operator "${node.operator}"`);
1223
1848
  }
1224
1849
  case 'BinaryExpression': {
1850
+ // `s.kind === 'busy'`: a test of a tagged object's hidden tag.
1851
+ const tagTest = tagTestOf(node, environment);
1852
+ if (tagTest) {
1853
+ return { kind: 'fixed', expression: lowerTagTest(tagTest), location };
1854
+ }
1855
+ // `field === undefined`, `field != null` …: whether a list item's field is there.
1856
+ const presenceTest = presenceTestOf(node, environment);
1857
+ if (presenceTest) {
1858
+ return { kind: 'fixed', expression: presenceTest, location };
1859
+ }
1225
1860
  // Fold `+ - *` over two whole-number constants as JS would, so a product past int range stays exact.
1226
1861
  const leftConstant = CHECKED_HELPER[node.operator]
1227
1862
  ? staticInt(node.left, environment)
@@ -1237,27 +1872,47 @@ function sourceOf(node, environment) {
1237
1872
  return binarySource(node, operand(node.left), operand(node.right), environment);
1238
1873
  }
1239
1874
  case 'LogicalExpression': {
1240
- // Only `&&` and `||` are supported (not `??`).
1875
+ // `a ?? b`: b where a is a list item's field that isn't there; a value that is always there is a.
1876
+ if (node.operator === '??') {
1877
+ const present = presenceOf(node.left, environment);
1878
+ if (present) {
1879
+ return {
1880
+ kind: 'conditional',
1881
+ test: { kind: 'fixed', expression: present, location },
1882
+ consequent: operand(node.left),
1883
+ alternate: operand(node.right),
1884
+ location,
1885
+ };
1886
+ }
1887
+ return isNullish(node.left, environment)
1888
+ ? operand(node.right)
1889
+ : operand(node.left);
1890
+ }
1891
+ // Otherwise only `&&` and `||`.
1241
1892
  const operator = node.operator === '&&' || node.operator === '||' ? node.operator : null;
1242
1893
  if (!operator) {
1243
1894
  throw new Error(`AOT: unsupported logical operator "${node.operator}"`);
1244
1895
  }
1896
+ // The right side reads a tagged object as the left side's outcome leaves it.
1897
+ const narrowing = narrowOn(node.left, environment);
1245
1898
  return {
1246
1899
  kind: 'logical',
1247
1900
  operator: operator,
1248
1901
  left: operand(node.left),
1249
- right: operand(node.right),
1902
+ right: lowerSource(node.right, narrowed(environment, operator === '&&' ? narrowing.whenTrue : narrowing.whenFalse)).source,
1250
1903
  location,
1251
1904
  };
1252
1905
  }
1253
- case 'ConditionalExpression':
1906
+ case 'ConditionalExpression': {
1907
+ const narrowing = narrowOn(node.test, environment);
1254
1908
  return {
1255
1909
  kind: 'conditional',
1256
1910
  test: operand(node.test),
1257
- consequent: operand(node.consequent),
1258
- alternate: operand(node.alternate),
1911
+ consequent: lowerSource(node.consequent, narrowed(environment, narrowing.whenTrue)).source,
1912
+ alternate: lowerSource(node.alternate, narrowed(environment, narrowing.whenFalse)).source,
1259
1913
  location,
1260
1914
  };
1915
+ }
1261
1916
  case 'MemberExpression': {
1262
1917
  // Static fold: member access that resolves to a compile-time constant (e.g., a .map item's `.key`).
1263
1918
  try {
@@ -1286,31 +1941,27 @@ function sourceOf(node, environment) {
1286
1941
  expression,
1287
1942
  location,
1288
1943
  });
1289
- // `<list>.length` → the runtime count.
1290
- if (object.type === 'Identifier' &&
1291
- environment.state.get(object.name)?.kind === 'list' &&
1292
- prop === 'length') {
1293
- return fixed({
1294
- kind: 'listLength',
1295
- list: environment.state.get(object.name),
1296
- type: INT,
1297
- });
1298
- }
1299
- // `<item>.field` where item is a struct local (a list row's bound element).
1300
- if (object.type === 'Identifier' &&
1301
- environment.locals.get(object.name)?.struct &&
1302
- prop) {
1303
- const item = environment.locals.get(object.name);
1304
- const field = item.struct.fields.find(structField => structField.key === prop);
1305
- if (!field) {
1306
- throw new Error(`AOT: unknown field "${prop}" on a list item`);
1944
+ const available = nativeAvailableOf(node, environment);
1945
+ if (available)
1946
+ return fixed(available);
1947
+ // `<list>.length` → the runtime count, of a filtered or sorted list too.
1948
+ if (prop === 'length') {
1949
+ const list = object.type === 'Identifier'
1950
+ ? environment.state.get(object.name)
1951
+ : derivedListOf(object, environment);
1952
+ if (list?.kind === 'list') {
1953
+ return fixed({ kind: 'listLength', list, type: INT });
1307
1954
  }
1308
- return fixed({
1309
- kind: 'itemField',
1310
- item,
1311
- field,
1312
- type: typeOfSlot(field.kind),
1313
- });
1955
+ }
1956
+ // A value worked out at run time in an array or object built in render.
1957
+ const leaf = runtimeLeafOf(node, environment);
1958
+ if (leaf) {
1959
+ return { kind: 'local', local: leaf, location };
1960
+ }
1961
+ // `item.field`, `item.pos.x`, `items[i].field` and `values[i]`: a field of a list item.
1962
+ const itemPath = itemPathOf(node, environment);
1963
+ if (itemPath) {
1964
+ return itemSource(itemPath, location);
1314
1965
  }
1315
1966
  // `<ref>.current` — a value ref's mutable slot.
1316
1967
  if (object.type === 'Identifier' &&
@@ -1324,12 +1975,25 @@ function sourceOf(node, environment) {
1324
1975
  if (object.type === 'Identifier' &&
1325
1976
  environment.event === object.name &&
1326
1977
  (prop === 'x' || prop === 'y' || prop === 'dx' || prop === 'dy')) {
1978
+ if (environment.scroll)
1979
+ throw scrollTouchError(prop);
1327
1980
  return fixed({ kind: 'event', field: prop, type: INT });
1328
1981
  }
1329
1982
  // `<event>.vx / .vy` — finger velocity (px/ms) at the last move; the engine measures it, a handler cannot.
1330
1983
  if (object.type === 'Identifier' &&
1331
1984
  environment.event === object.name &&
1332
1985
  (prop === 'vx' || prop === 'vy')) {
1986
+ if (environment.scroll)
1987
+ throw scrollTouchError(prop);
1988
+ return fixed({ kind: 'event', field: prop, type: FLOAT });
1989
+ }
1990
+ // `<event>.scrollX / .scrollY` — where an onScroll handler's ScrollView is now.
1991
+ if (object.type === 'Identifier' &&
1992
+ environment.event === object.name &&
1993
+ (prop === 'scrollX' || prop === 'scrollY')) {
1994
+ if (!environment.scroll) {
1995
+ throw aotError('AOT: only an onScroll event carries a scroll offset', 'read e.scrollX / e.scrollY inside an onScroll handler, or ask with scrollTo(ref.current).');
1996
+ }
1333
1997
  return fixed({ kind: 'event', field: prop, type: FLOAT });
1334
1998
  }
1335
1999
  // `<gestureState>.…` — the second argument of a PanResponder callback (see emitPanResponder).
@@ -1358,12 +2022,52 @@ function sourceOf(node, environment) {
1358
2022
  prop === 'PI') {
1359
2023
  return fixed({ kind: 'pi', type: FLOAT });
1360
2024
  }
1361
- 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 ' +
1362
- 'field, event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.layout.*), and ' +
2025
+ // A field of a record a native method returns, read where it can't be kept.
2026
+ let root = node;
2027
+ while (root.type === 'MemberExpression')
2028
+ root = root.object;
2029
+ const unkept = unkeptRecordError(root, environment) ?? unkeptScrollError(root);
2030
+ if (unkept)
2031
+ throw unkept;
2032
+ 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 " +
2033
+ 'field (`item.title`, `items[i].title`), event fields (e.x / e.y / e.dx / e.dy / e.vx / e.vy / e.scrollX / e.scrollY / e.layout.*), and ' +
1363
2034
  'Math.PI — other member access must be a compile-time constant.');
1364
2035
  }
2036
+ case 'OptionalMemberExpression': {
2037
+ // `items[i]?.field`, or `item.pos?.x`: a list item's field, undefined where it isn't there.
2038
+ const itemPath = itemPathOf(node, environment);
2039
+ if (itemPath) {
2040
+ return itemSource(itemPath, location);
2041
+ }
2042
+ 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.');
2043
+ }
1365
2044
  case 'CallExpression': {
1366
2045
  const callee = node.callee;
2046
+ const unkeptScroll = unkeptScrollError(node);
2047
+ if (unkeptScroll)
2048
+ throw unkeptScroll;
2049
+ // `Sensors.read(channel)`: a native method's result.
2050
+ const nativeCallee = nativeCalleeOf(node, environment);
2051
+ if (nativeCallee) {
2052
+ const unkept = unkeptRecordError(node, environment);
2053
+ if (unkept)
2054
+ throw unkept;
2055
+ const call = lowerNativeCall(node, nativeCallee, environment);
2056
+ if (call.import.result === 'void') {
2057
+ const binding = callee.object.name;
2058
+ throw aotError(`AOT: ${binding}.${nativeCallee.method}() returns nothing, so it has no value`, 'call it as a statement of its own.');
2059
+ }
2060
+ return {
2061
+ kind: 'fixed',
2062
+ expression: {
2063
+ kind: 'native',
2064
+ call,
2065
+ // A record was refused above.
2066
+ type: NATIVE_TYPES[call.import.result],
2067
+ },
2068
+ location,
2069
+ };
2070
+ }
1367
2071
  // Date.now() / performance.now() → the engine clock, as 64-bit whole milliseconds.
1368
2072
  if (callee.type === 'MemberExpression' &&
1369
2073
  !callee.computed &&
@@ -1387,6 +2091,28 @@ function sourceOf(node, environment) {
1387
2091
  !environment.shadowedClock?.has(node)) {
1388
2092
  throw dateObjectError();
1389
2093
  }
2094
+ // `text.includes(search)` on strings, a boolean.
2095
+ if (callee.type === 'MemberExpression' &&
2096
+ !callee.computed &&
2097
+ callee.property.type === 'Identifier' &&
2098
+ callee.property.name === 'includes') {
2099
+ return {
2100
+ kind: 'fixed',
2101
+ expression: lowerIncludes(node, environment),
2102
+ location,
2103
+ };
2104
+ }
2105
+ // `a.localeCompare(b)` on strings: -1, 0 or 1.
2106
+ if (callee.type === 'MemberExpression' &&
2107
+ !callee.computed &&
2108
+ callee.property.type === 'Identifier' &&
2109
+ callee.property.name === 'localeCompare') {
2110
+ return {
2111
+ kind: 'fixed',
2112
+ expression: lowerLocaleCompare(node, environment),
2113
+ location,
2114
+ };
2115
+ }
1390
2116
  // Math.*: a division under floor / ceil / round / trunc stays apart, for the typing pass to divide exactly.
1391
2117
  if (callee.type === 'MemberExpression' &&
1392
2118
  callee.object.name === 'Math') {
@@ -1409,6 +2135,10 @@ function sourceOf(node, environment) {
1409
2135
  location,
1410
2136
  };
1411
2137
  }
2138
+ // A helper used as a value: its body as one expression.
2139
+ const helperValue = helperValueOf(node, environment);
2140
+ if (helperValue)
2141
+ return helperValue;
1412
2142
  throw new Error('AOT: unsupported call expression in a dynamic expression');
1413
2143
  }
1414
2144
  case 'NewExpression':
@@ -1429,12 +2159,24 @@ function sourceOf(node, environment) {
1429
2159
  export const lowerSource = withLoc((node, environment) => {
1430
2160
  // Below a node that is not whole-number math, its operands are typed as usual (see keepsMath64Node).
1431
2161
  if (environment.math64 && !keepsMath64Node(node)) {
1432
- environment = { ...environment, math64: false };
2162
+ environment = { ...environment, math64: undefined };
1433
2163
  }
1434
2164
  const source = sourceOf(node, environment);
2165
+ // A constant's type, and one its source or its slot fixes, depends on no slot's width.
2166
+ if (source.kind === 'number' ||
2167
+ source.kind === 'string' ||
2168
+ source.kind === 'boolean' ||
2169
+ source.kind === 'fixed' ||
2170
+ (source.kind === 'state' && isSettledState(source.state)) ||
2171
+ (source.kind === 'ref' &&
2172
+ source.ref.slotKind !== 'int' &&
2173
+ source.ref.slotKind !== 'i64')) {
2174
+ return { source, expression: typeSource(source, false) };
2175
+ }
2176
+ const { math64 } = environment;
1435
2177
  return {
1436
2178
  source,
1437
- expression: typeSource(source, environment.math64 ?? false),
2179
+ expression: typedLater(sourceShape(source), () => typeSource(source, math64?.() ?? false), source),
1438
2180
  };
1439
2181
  });
1440
2182
  /**
@@ -1446,6 +2188,64 @@ export const lowerSource = withLoc((node, environment) => {
1446
2188
  * @returns The typed expression.
1447
2189
  */
1448
2190
  export const lowerExprWide = (node, environment) => lowerSource(node, environment).expression;
2191
+ /**
2192
+ * The shape of a source expression's value, which holds whatever the typing pass makes of its numbers.
2193
+ *
2194
+ * @param source The expression.
2195
+ *
2196
+ * @returns The shape.
2197
+ */
2198
+ export function sourceShape(source) {
2199
+ switch (source.kind) {
2200
+ case 'number':
2201
+ return 'number';
2202
+ case 'string':
2203
+ return 'string';
2204
+ case 'boolean':
2205
+ return 'bool';
2206
+ case 'state':
2207
+ return stateShape(source.state);
2208
+ case 'local':
2209
+ return localShape(source.local);
2210
+ case 'ref':
2211
+ return source.ref.kind === 'node' ? 'node' : 'number';
2212
+ case 'fixed':
2213
+ return shapeOf(source.expression);
2214
+ case 'unary': {
2215
+ if (source.operator === '!')
2216
+ return 'bool';
2217
+ const operand = sourceShape(source.operand);
2218
+ return operand === 'bool' ? 'number' : operand;
2219
+ }
2220
+ case 'binary':
2221
+ return COMPARE.has(source.operator) ? 'bool' : 'number';
2222
+ case 'logical':
2223
+ return sourceShape(source.left) === 'bool' &&
2224
+ sourceShape(source.right) === 'bool'
2225
+ ? 'bool'
2226
+ : 'number';
2227
+ case 'conditional': {
2228
+ const consequent = sourceShape(source.consequent);
2229
+ return consequent === sourceShape(source.alternate)
2230
+ ? consequent
2231
+ : 'number';
2232
+ }
2233
+ case 'math':
2234
+ return 'number';
2235
+ }
2236
+ }
2237
+ /**
2238
+ * The local an expression is a bare read of, if it is one.
2239
+ *
2240
+ * @param lowered The expression, and its source.
2241
+ *
2242
+ * @returns The local, or null.
2243
+ */
2244
+ export function bareLocalOf(lowered) {
2245
+ return lowered.source.kind === 'local'
2246
+ ? lowered.source.local
2247
+ : readLocalOf(lowered.expression);
2248
+ }
1449
2249
  /**
1450
2250
  * What a slot holding an expression's value records about it. A bare local is the Local itself, so a list row keeps
1451
2251
  * its struct (extractProps copies it into a prop).
@@ -1479,11 +2279,22 @@ export function slotValueOf(expression) {
1479
2279
  */
1480
2280
  export function lowerSourcedWide(node, environment) {
1481
2281
  const lowered = lowerSource(node, environment);
1482
- return {
1483
- ...slotValueOf(lowered.expression),
1484
- source: lowered.source,
1485
- expression: lowered.expression,
1486
- };
2282
+ const local = bareLocalOf(lowered);
2283
+ return local
2284
+ ? copyLocal(local, lowered)
2285
+ : holdLater({ ...lowered }, shapeOf(lowered.expression), () => slotValueOf(lowered.expression));
2286
+ }
2287
+ /**
2288
+ * Lowers an expression a name is bound to: the local that every read of the name is.
2289
+ *
2290
+ * @param node The expression.
2291
+ * @param environment The expression environment.
2292
+ *
2293
+ * @returns The local.
2294
+ */
2295
+ export function lowerLocal(node, environment) {
2296
+ const { source, expression } = lowerSourcedWide(node, environment);
2297
+ return holdLater({ source, expression }, shapeOf(expression), () => slotValueOf(expression));
1487
2298
  }
1488
2299
  /**
1489
2300
  * Lowers an expression for a destination that holds an int, a float, or a string. A 64-bit value (a Date.now() /
@@ -1499,15 +2310,18 @@ export function lowerSourcedWide(node, environment) {
1499
2310
  */
1500
2311
  export function lowerExpr(node, environment) {
1501
2312
  const expression = lowerExprWide(node, environment);
1502
- if (expression.type.kind !== 'int64')
1503
- return expression;
1504
- 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, ' +
1505
- 'reduce it to a small number first — e.g. `ms % 1000`, or `Math.floor(ms / 1000) % ' +
1506
- '60`.');
1507
- if (node.loc) {
1508
- error.aotLoc = node.loc.start;
1509
- }
1510
- throw error;
2313
+ whenTyped(() => {
2314
+ if (expression.type.kind !== 'int64')
2315
+ return;
2316
+ 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, ' +
2317
+ 'reduce it to a small number first — e.g. `ms % 1000`, or `Math.floor(ms / 1000) % ' +
2318
+ '60`.');
2319
+ if (node.loc) {
2320
+ error.aotLoc = node.loc.start;
2321
+ }
2322
+ throw error;
2323
+ });
2324
+ return expression;
1511
2325
  }
1512
2326
  /**
1513
2327
  * An aotError pinned to the expression that cannot be lowered to text (lowerTextParts is not withLoc-wrapped).
@@ -1525,6 +2339,351 @@ function textShapeError(node, message, hint) {
1525
2339
  }
1526
2340
  return error;
1527
2341
  }
2342
+ /**
2343
+ * Whether an expression is a compile-time constant.
2344
+ *
2345
+ * @param node The expression.
2346
+ * @param scope The constants a fold may read.
2347
+ *
2348
+ * @returns True when it folds.
2349
+ */
2350
+ function foldsStatically(node, scope) {
2351
+ try {
2352
+ evalStatic(node, scope, 'strict');
2353
+ return true;
2354
+ }
2355
+ catch {
2356
+ return false;
2357
+ }
2358
+ }
2359
+ /**
2360
+ * Whether an expression builds a string at run time: a template literal, a string helper, or a string `+`. Only a
2361
+ * destination that holds text can take one, through lowerText.
2362
+ *
2363
+ * @param node The expression.
2364
+ * @param environment The expression environment.
2365
+ *
2366
+ * @returns True when it builds a string.
2367
+ */
2368
+ export function buildsText(node, environment) {
2369
+ const scope = foldScope(environment, environment.constants ?? {});
2370
+ if (foldsStatically(node, scope))
2371
+ return false;
2372
+ if (node.type === 'TemplateLiteral' ||
2373
+ textCallOf(node, environment, scope) !== null) {
2374
+ return true;
2375
+ }
2376
+ // A helper that returns built text builds it.
2377
+ const returned = returnedExpression(node, environment);
2378
+ if (returned)
2379
+ return buildsText(returned.node, returned.environment);
2380
+ return (node.type === 'BinaryExpression' &&
2381
+ node.operator === '+' &&
2382
+ lowerTextParts(node, environment, scope, true).isString);
2383
+ }
2384
+ /** The string helpers that build text. */
2385
+ const TEXT_METHODS = new Set(['toFixed', 'padStart', 'slice', 'toUpperCase']);
2386
+ /**
2387
+ * The text helper a call is: `String(x)`, or `x.toFixed(n)`, `x.padStart(n, fill)`, `x.slice(start, end)` or
2388
+ * `x.toUpperCase()`. A list's slice is not one.
2389
+ *
2390
+ * @param node The expression.
2391
+ * @param environment The expression environment.
2392
+ * @param scope The constants a fold may read, which may shadow `String`.
2393
+ *
2394
+ * @returns The helper's name, or null for anything else.
2395
+ */
2396
+ function textCallOf(node, environment, scope) {
2397
+ if (node.type !== 'CallExpression')
2398
+ return null;
2399
+ const { callee } = node;
2400
+ if (callee.type === 'Identifier' &&
2401
+ callee.name === 'String' &&
2402
+ !hasBinding(scope, 'String')) {
2403
+ return 'String';
2404
+ }
2405
+ if (callee.type !== 'MemberExpression' ||
2406
+ callee.computed ||
2407
+ callee.property.type !== 'Identifier' ||
2408
+ !TEXT_METHODS.has(callee.property.name)) {
2409
+ return null;
2410
+ }
2411
+ const isList = callee.object.type === 'Identifier' &&
2412
+ environment.state.get(callee.object.name)?.kind === 'list';
2413
+ return isList ? null : callee.property.name;
2414
+ }
2415
+ /**
2416
+ * A compile-time whole number a text helper takes.
2417
+ *
2418
+ * @param node The argument, or undefined when it is left out.
2419
+ * @param fallback The value JS uses when it is left out.
2420
+ * @param what What the argument is, for errors.
2421
+ * @param environment The expression environment.
2422
+ *
2423
+ * @returns The number.
2424
+ */
2425
+ function helperInt(node, fallback, what, environment) {
2426
+ if (!node)
2427
+ return fallback;
2428
+ const value = staticInt(node, environment);
2429
+ if (value === null) {
2430
+ 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.');
2431
+ }
2432
+ return value;
2433
+ }
2434
+ /**
2435
+ * Lowers `x.toFixed(digits)` on a runtime number.
2436
+ *
2437
+ * @param call The call.
2438
+ * @param environment The expression environment.
2439
+ *
2440
+ * @returns The text: the number, printed with that many decimals.
2441
+ */
2442
+ function lowerToFixed(call, environment) {
2443
+ const receiver = call.callee.object;
2444
+ const value = lowerExprWide(receiver, environment);
2445
+ if (shapeOf(value) !== 'number') {
2446
+ throw textShapeError(call, 'AOT: toFixed is only supported on a number', 'JS has toFixed on numbers only; call it on the number itself.');
2447
+ }
2448
+ const digits = helperInt(call.arguments[0], 0, "toFixed's digits", environment);
2449
+ const problem = fixedDigitsProblem(digits);
2450
+ if (problem) {
2451
+ throw textShapeError(call, ...problem);
2452
+ }
2453
+ return { isString: true, parts: [{ kind: 'value', value, digits }] };
2454
+ }
2455
+ /**
2456
+ * Lowers `x.padStart(width, fill)` on a runtime string.
2457
+ *
2458
+ * @param call The call.
2459
+ * @param environment The expression environment.
2460
+ * @param scope The constants a fold may read.
2461
+ *
2462
+ * @returns The text: the string, padded.
2463
+ */
2464
+ function lowerPadStart(call, environment, scope) {
2465
+ const receiver = lowerTextParts(call.callee.object, environment, scope, true);
2466
+ if (!receiver.isString) {
2467
+ throw textShapeError(call, 'AOT: padStart is only supported on a string', 'JS has padStart on strings only; convert first: String(n).padStart(2, "0").');
2468
+ }
2469
+ // The same limits as a constant fold, checked before the receiver so a constant one gets the same error.
2470
+ const width = helperInt(call.arguments[0], 0, "padStart's length", environment);
2471
+ const widthProblem = padWidthProblem(width);
2472
+ if (widthProblem) {
2473
+ throw textShapeError(call, ...widthProblem);
2474
+ }
2475
+ const fillNode = call.arguments[1];
2476
+ let fill = ' ';
2477
+ if (fillNode) {
2478
+ try {
2479
+ fill = evalStatic(fillNode, scope, 'strict');
2480
+ }
2481
+ catch {
2482
+ fill = null;
2483
+ }
2484
+ }
2485
+ const fillProblem = padFillProblem(fill);
2486
+ if (fillProblem) {
2487
+ throw textShapeError(fillNode ?? call, ...fillProblem);
2488
+ }
2489
+ 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")}`.');
2490
+ if (fill === '' || width <= 0) {
2491
+ return { isString: true, parts: [piece] };
2492
+ }
2493
+ return {
2494
+ isString: true,
2495
+ parts: [
2496
+ {
2497
+ ...piece,
2498
+ edits: [
2499
+ ...(piece.edits ?? []),
2500
+ { kind: 'pad', width, fill: fill },
2501
+ ],
2502
+ },
2503
+ ],
2504
+ };
2505
+ }
2506
+ /**
2507
+ * One of slice's positions: a constant cut to a whole number as JS cuts it, or a runtime whole number.
2508
+ *
2509
+ * @param node The argument, or undefined when it is left out.
2510
+ * @param fallback The position JS uses when it is left out.
2511
+ * @param environment The expression environment.
2512
+ * @param scope The constants a fold may read.
2513
+ *
2514
+ * @returns The position.
2515
+ */
2516
+ function slicePosition(node, fallback, environment, scope) {
2517
+ if (!node)
2518
+ return numConst(fallback);
2519
+ if (node.type === 'SpreadElement') {
2520
+ throw textShapeError(node, 'AOT: slice cannot take a spread', 'pass the start and end themselves: text.slice(0, 3).');
2521
+ }
2522
+ let constant = null;
2523
+ try {
2524
+ constant = { value: evalStatic(node, scope, 'strict') };
2525
+ }
2526
+ catch (error) {
2527
+ rethrowFoldLimit(error);
2528
+ }
2529
+ if (constant) {
2530
+ const problem = slicePositionProblem([constant.value]);
2531
+ if (problem) {
2532
+ throw textShapeError(node, ...problem);
2533
+ }
2534
+ const position = Math.trunc(constant.value) || 0;
2535
+ return numConst(Math.max(-TEXT_END, Math.min(TEXT_END, position)));
2536
+ }
2537
+ const position = lowerExpr(node, environment);
2538
+ whenTyped(() => {
2539
+ if (position.type.kind !== 'int') {
2540
+ 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)).');
2541
+ }
2542
+ });
2543
+ return position;
2544
+ }
2545
+ /**
2546
+ * The one piece a helper that edits a printed piece (padStart, slice) can work on.
2547
+ *
2548
+ * @param receiver The text the helper is called on.
2549
+ * @param call The call, for errors.
2550
+ * @param message The error when there is more than one value, or none.
2551
+ * @param hint How to rewrite it.
2552
+ *
2553
+ * @returns The piece.
2554
+ */
2555
+ function onePiece(receiver, call, message, hint) {
2556
+ const pieces = receiver.parts.filter(part => !(part.kind === 'literal' && part.text === ''));
2557
+ const [piece] = pieces;
2558
+ if (pieces.length !== 1 || piece.kind === 'literal') {
2559
+ throw textShapeError(call, message, hint);
2560
+ }
2561
+ return piece;
2562
+ }
2563
+ /**
2564
+ * Lowers `x.slice(start, end)` on a runtime string.
2565
+ *
2566
+ * @param call The call.
2567
+ * @param environment The expression environment.
2568
+ * @param scope The constants a fold may read.
2569
+ *
2570
+ * @returns The text: the part of the string between the two positions.
2571
+ */
2572
+ function lowerSlice(call, environment, scope) {
2573
+ const receiver = lowerTextParts(call.callee.object, environment, scope, true);
2574
+ if (!receiver.isString) {
2575
+ 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(…).');
2576
+ }
2577
+ const [startNode, endNode] = call.arguments;
2578
+ const start = slicePosition(startNode, 0, environment, scope);
2579
+ const end = slicePosition(endNode, TEXT_END, environment, scope);
2580
+ 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)}`.');
2581
+ whenTyped(() => {
2582
+ if (piece.kind === 'value' &&
2583
+ piece.digits &&
2584
+ piece.value.type.kind !== 'float') {
2585
+ 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.');
2586
+ }
2587
+ });
2588
+ return {
2589
+ isString: true,
2590
+ parts: [
2591
+ { ...piece, edits: [...(piece.edits ?? []), { kind: 'slice', start, end }] },
2592
+ ],
2593
+ };
2594
+ }
2595
+ /**
2596
+ * Lowers `x.toUpperCase()` on a runtime string. Its literal text is upper-cased here, and each value as it is
2597
+ * printed; a whole number has no letters to change (see typedParts).
2598
+ *
2599
+ * @param call The call.
2600
+ * @param environment The expression environment.
2601
+ * @param scope The constants a fold may read.
2602
+ *
2603
+ * @returns The text, upper-cased.
2604
+ */
2605
+ function lowerToUpperCase(call, environment, scope) {
2606
+ const receiver = lowerTextParts(call.callee.object, environment, scope, true);
2607
+ if (!receiver.isString) {
2608
+ throw textShapeError(call, 'AOT: toUpperCase is only supported on a string', 'JS has toUpperCase on strings only; convert first: String(on).toUpperCase().');
2609
+ }
2610
+ return {
2611
+ isString: true,
2612
+ parts: receiver.parts.map(part => {
2613
+ if (part.kind === 'literal') {
2614
+ return { ...part, text: part.text.toUpperCase() };
2615
+ }
2616
+ return { ...part, edits: [...(part.edits ?? []), { kind: 'upper' }] };
2617
+ }),
2618
+ };
2619
+ }
2620
+ /**
2621
+ * Lowers `text.includes(search)` on runtime strings.
2622
+ *
2623
+ * @param call The call.
2624
+ * @param environment The expression environment.
2625
+ *
2626
+ * @returns The boolean.
2627
+ */
2628
+ function lowerIncludes(call, environment) {
2629
+ const receiver = call.callee.object;
2630
+ const [needleNode, ...rest] = call.arguments;
2631
+ if (needleNode?.type === 'SpreadElement') {
2632
+ throw aotError('AOT: includes cannot take a spread', 'pass the string to search for: name.includes(x).');
2633
+ }
2634
+ const problem = includesProblem(needleNode ? '' : undefined, rest.length > 0);
2635
+ if (problem) {
2636
+ throw aotError(...problem);
2637
+ }
2638
+ // A string built in place lives in the format buffer, not in a string register.
2639
+ const stringOf = (node, problemOf) => {
2640
+ if (buildsText(node, environment)) {
2641
+ 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).');
2642
+ }
2643
+ const value = lowerExprWide(node, environment);
2644
+ if (shapeOf(value) !== 'string') {
2645
+ throw aotError(...problemOf());
2646
+ }
2647
+ return value;
2648
+ };
2649
+ const haystack = stringOf(receiver, () => [
2650
+ 'AOT: includes is only supported on a string',
2651
+ 'JS has includes on strings and arrays; a package has it on a string only. Compare with === for one value.',
2652
+ ]);
2653
+ const needle = stringOf(needleNode, () => includesProblem(0, false));
2654
+ return { kind: 'stringIncludes', haystack, needle, type: BOOL };
2655
+ }
2656
+ /**
2657
+ * Lowers `text.localeCompare(other)` on runtime strings, which orders them as `<` does, with no locale rules.
2658
+ *
2659
+ * @param call The call.
2660
+ * @param environment The expression environment.
2661
+ *
2662
+ * @returns -1, 0 or 1.
2663
+ */
2664
+ function lowerLocaleCompare(call, environment) {
2665
+ const receiver = call.callee.object;
2666
+ const [otherNode, ...rest] = call.arguments;
2667
+ if (!otherNode || otherNode.type === 'SpreadElement' || rest.length) {
2668
+ 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.');
2669
+ }
2670
+ const stringOf = (node) => {
2671
+ if (buildsText(node, environment)) {
2672
+ 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).');
2673
+ }
2674
+ const value = lowerExprWide(node, environment);
2675
+ if (shapeOf(value) !== 'string') {
2676
+ throw aotError('AOT: localeCompare is only supported on strings', 'compare numbers by subtracting them: (a, b) => a.n - b.n.');
2677
+ }
2678
+ return value;
2679
+ };
2680
+ return {
2681
+ kind: 'stringOrder',
2682
+ left: stringOf(receiver),
2683
+ right: stringOf(otherNode),
2684
+ type: INT,
2685
+ };
2686
+ }
1528
2687
  /**
1529
2688
  * Text a constant renders as a standalone JSX child. React draws nothing for null, undefined, or a
1530
2689
  * boolean (see flattenTextChildren in Flow A), which is not how `+` treats the same values — a
@@ -1534,9 +2693,15 @@ function textShapeError(node, message, hint) {
1534
2693
  *
1535
2694
  * @returns The text React would render for it.
1536
2695
  */
1537
- export const jsxChildText = (value) => value === undefined || value === null || typeof value === 'boolean'
1538
- ? ''
1539
- : String(value);
2696
+ export function jsxChildText(value) {
2697
+ if (value === undefined || value === null || typeof value === 'boolean') {
2698
+ return '';
2699
+ }
2700
+ if (typeof value === 'object' && !Array.isArray(value)) {
2701
+ throw aotError('AOT: an object cannot be a <Text> child', 'React refuses objects as children; render one of its fields: {p.label}.');
2702
+ }
2703
+ return String(value);
2704
+ }
1540
2705
  /**
1541
2706
  * Splits a string-building `+` chain into text parts, following JS's own left-to-right typing: a `+`
1542
2707
  * is a concatenation only once one of its sides is a string, so `n + 1 + 'ms'` still adds before it
@@ -1581,10 +2746,56 @@ function lowerTextParts(node, environment, scope, isOperand = false) {
1581
2746
  return { isString: true, parts: [...leftParts.parts, ...rightParts.parts] };
1582
2747
  }
1583
2748
  }
1584
- // A branch or operand that concatenates needs its own format; refuse before lowerExpr's misleading error.
1585
- const concatenates = (subExpression) => subExpression.type === 'BinaryExpression' &&
2749
+ // A template literal is its strings and values in order, each value printed as String() prints it.
2750
+ if (node.type === 'TemplateLiteral') {
2751
+ const parts = [];
2752
+ node.quasis.forEach((quasi, index) => {
2753
+ parts.push({ kind: 'literal', text: quasi.value.cooked ?? '' });
2754
+ if (index < node.expressions.length) {
2755
+ parts.push(...lowerTextParts(node.expressions[index], environment, scope, true)
2756
+ .parts);
2757
+ }
2758
+ });
2759
+ return { isString: true, parts };
2760
+ }
2761
+ // A helper that returns text on its only path is that text, built where it is called.
2762
+ const returned = returnedExpression(node, environment);
2763
+ if (returned) {
2764
+ return lowerTextParts(returned.node, returned.environment, foldScope(returned.environment, returned.environment.constants), isOperand);
2765
+ }
2766
+ // String(x) prints x as an operand of a string `+` would.
2767
+ const textCall = textCallOf(node, environment, scope);
2768
+ if (textCall === 'String') {
2769
+ const [argument] = node.arguments;
2770
+ if (argument?.type === 'SpreadElement') {
2771
+ throw textShapeError(node, 'AOT: String(...) cannot take a spread', 'pass the value itself: String(n).');
2772
+ }
2773
+ return {
2774
+ isString: true,
2775
+ parts: argument
2776
+ ? lowerTextParts(argument, environment, scope, true).parts
2777
+ : [],
2778
+ };
2779
+ }
2780
+ if (textCall === 'toFixed') {
2781
+ return lowerToFixed(node, environment);
2782
+ }
2783
+ if (textCall === 'padStart') {
2784
+ return lowerPadStart(node, environment, scope);
2785
+ }
2786
+ if (textCall === 'slice') {
2787
+ return lowerSlice(node, environment, scope);
2788
+ }
2789
+ if (textCall === 'toUpperCase') {
2790
+ return lowerToUpperCase(node, environment, scope);
2791
+ }
2792
+ // A branch or operand that builds text needs its own format; refuse before lowerExpr's misleading error.
2793
+ const concatenates = (subExpression) => (subExpression.type === 'BinaryExpression' &&
1586
2794
  subExpression.operator === '+' &&
1587
- lowerTextParts(subExpression, environment, scope, true).isString;
2795
+ lowerTextParts(subExpression, environment, scope, true).isString) ||
2796
+ ((subExpression.type === 'TemplateLiteral' ||
2797
+ textCallOf(subExpression, environment, scope) !== null) &&
2798
+ !foldsStatically(subExpression, scope));
1588
2799
  if (node.type === 'ConditionalExpression' &&
1589
2800
  (concatenates(node.test) ||
1590
2801
  concatenates(node.consequent) ||
@@ -1601,27 +2812,98 @@ function lowerTextParts(node, environment, scope, isOperand = false) {
1601
2812
  // Anything else is one runtime value.
1602
2813
  const value = lowerExprWide(node, environment);
1603
2814
  // `&&`/`||` collapse to 0/1 and a ternary to one slot, so text matches JS only when operands agree in kind.
1604
- if (node.type === 'LogicalExpression' && !isBoolean(value.type)) {
2815
+ if (node.type === 'LogicalExpression' &&
2816
+ node.operator !== '??' &&
2817
+ shapeOf(value) !== 'bool') {
1605
2818
  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 ` +
1606
2819
  `package only has 0/1. Write the branch out instead: {cond ? 'yes' : ''}.`);
1607
2820
  }
2821
+ const narrowing = node.type === 'ConditionalExpression'
2822
+ ? narrowOn(node.test, environment)
2823
+ : null;
1608
2824
  if (node.type === 'ConditionalExpression' &&
1609
- isBoolean(lowerExprWide(node.consequent, environment).type) !==
1610
- isBoolean(lowerExprWide(node.alternate, environment).type)) {
2825
+ (shapeOf(lowerExprWide(node.consequent, narrowed(environment, narrowing.whenTrue))) ===
2826
+ 'bool') !==
2827
+ (shapeOf(lowerExprWide(node.alternate, narrowed(environment, narrowing.whenFalse))) ===
2828
+ 'bool')) {
1611
2829
  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 ' +
1612
2830
  'slot here. Make both branches the same kind.');
1613
2831
  }
2832
+ // A list item's field that isn't there prints as undefined does.
2833
+ const missing = itemReadOf(value)
2834
+ ? { missing: isOperand ? 'undefined' : '' }
2835
+ : {};
1614
2836
  // A boolean prints nothing as a child, "true"/"false" as an operand; isString stays false so `on + n` adds.
1615
- if (isBoolean(value.type)) {
2837
+ if (shapeOf(value) === 'bool') {
1616
2838
  return isOperand
1617
- ? { isString: false, parts: [{ kind: 'booleanWord', value }] }
2839
+ ? { isString: false, parts: [{ kind: 'booleanWord', value, ...missing }] }
1618
2840
  : { isString: false, parts: [{ kind: 'literal', text: '' }] };
1619
2841
  }
1620
2842
  return {
1621
- isString: value.type.kind === 'string',
1622
- parts: [{ kind: 'value', value }],
2843
+ isString: shapeOf(value) === 'string',
2844
+ parts: [{ kind: 'value', value, ...missing }],
1623
2845
  };
1624
2846
  }
2847
+ /**
2848
+ * Settles a text's parts once its values are typed: a whole number has no letters for toUpperCase to change, so
2849
+ * it is printed as it is.
2850
+ *
2851
+ * @param parts The parts.
2852
+ *
2853
+ * @returns The parts.
2854
+ */
2855
+ function typedParts(parts) {
2856
+ const cased = parts.filter(part => part.kind === 'value' && part.edits?.some(edit => edit.kind === 'upper'));
2857
+ if (cased.length) {
2858
+ whenTyped(() => {
2859
+ for (const part of cased) {
2860
+ const { kind } = part.value.type;
2861
+ if (kind !== 'int' && kind !== 'int64')
2862
+ continue;
2863
+ const edits = part.edits.filter(edit => edit.kind !== 'upper');
2864
+ if (edits.length) {
2865
+ part.edits = edits;
2866
+ }
2867
+ else {
2868
+ delete part.edits;
2869
+ }
2870
+ }
2871
+ });
2872
+ }
2873
+ return parts;
2874
+ }
2875
+ /**
2876
+ * Lowers `console.log`'s arguments to the line it prints: each as a string `+` prints it, a space between them.
2877
+ *
2878
+ * @param callArguments The call's arguments.
2879
+ * @param environment The expression environment.
2880
+ *
2881
+ * @returns The line.
2882
+ */
2883
+ export function lowerLogText(callArguments, environment) {
2884
+ const scope = foldScope(environment, environment.constants ?? {});
2885
+ const parts = [];
2886
+ callArguments.forEach((argument, index) => {
2887
+ if (argument.type === 'SpreadElement') {
2888
+ throw textShapeError(argument, 'AOT: console.* cannot take a spread', 'pass each value itself: console.log(a, b).');
2889
+ }
2890
+ // An object or a list that folds would print as `+` prints it, "[object Object]".
2891
+ let folded;
2892
+ try {
2893
+ folded = evalStatic(argument, scope, 'strict');
2894
+ }
2895
+ catch {
2896
+ /* not a compile-time constant */
2897
+ }
2898
+ if (folded !== null && typeof folded === 'object') {
2899
+ throw textShapeError(argument, 'AOT: console.* cannot print an object or a list', 'print its fields or items: console.log(point.x, point.y).');
2900
+ }
2901
+ if (index > 0)
2902
+ parts.push({ kind: 'literal', text: ' ' });
2903
+ parts.push(...lowerTextParts(argument, environment, scope, true).parts);
2904
+ });
2905
+ return { parts: typedParts(parts) };
2906
+ }
1625
2907
  /**
1626
2908
  * Lowers an expression to text for a char-buffer destination (a <Text> body, a string state slot, a
1627
2909
  * <TextInput value>). A string-building `+` chain becomes its parts in order; anything else is one value.
@@ -1634,7 +2916,6 @@ function lowerTextParts(node, environment, scope, isOperand = false) {
1634
2916
  */
1635
2917
  export function lowerText(node, environment, scope = environment.constants ?? {}) {
1636
2918
  return {
1637
- parts: lowerTextParts(node, environment, foldScope(environment, scope))
1638
- .parts,
2919
+ parts: typedParts(lowerTextParts(node, environment, foldScope(environment, scope)).parts),
1639
2920
  };
1640
2921
  }