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,45 +16,55 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { checkNumber, lowerWithChecks, runChecks } from './check.mjs';
20
- import { aotError } from './diagnostics.mjs';
21
- import { evalStatic, setBinding, withUndefined } from './static-eval.mjs';
19
+ import { checkNumber, lowerWithChecks, runChecks, whenTyped } from './check.mjs';
20
+ import { evalStatic, rethrowFoldLimit, setBinding, withUndefined, } from './static-eval.mjs';
22
21
  import { abandonBoot, beginBoot, endBoot, setBootLowering } from './boot.mjs';
23
- import { findShadowedClockCalls, emitSourcedWide, lowerExpr, } from './expressions.mjs';
24
- import { findComponent, declaredNames, moduleScope, collectState, findReturnJSX, collectComponents, collectHelpers, collectImageImports, collectSvgImports, collectCallbacks, collectMemos, collectEffects, bindConst, } from './collect.mjs';
22
+ import { bindBuiltValues, findShadowedClockCalls, foldRuntime, inferWideSlots, lowerLocal, lowerExpr, } from './expressions.mjs';
23
+ import { findComponent, bindFoldedPattern, declaredNames, moduleScope, collectState, settleBootInitials, findReturnJSX, collectComponents, collectHelpers, collectImageImports, collectSvgImports, collectCallbacks, collectMemos, collectEffects, collectNativeEvents, bindConst, } from './collect.mjs';
25
24
  import { collectAnims, collectRefs } from './animations.mjs';
26
- import { lowerEffect } from './handlers.mjs';
25
+ import { lowerEffect, lowerNativeEvent } from './handlers.mjs';
27
26
  import { collectPanResponders } from './pan-responder.mjs';
28
27
  import { emitNode } from './nodes.mjs';
29
28
  import { lowerKeyboardConfig } from './keyboard.mjs';
29
+ import { itemValueAt } from './list-items.mjs';
30
30
  import { normalizeUndefined, parseApp } from './parse.mjs';
31
+ import { collectNativeModules, optionalModulesOf } from './native-modules.mjs';
32
+ import { inlineCustomHooks } from './custom-hooks.mjs';
33
+ import { rewriteWindowDimensions } from './window-dimensions.mjs';
31
34
  import { Out } from './out.mjs';
32
- import { isStateDriven, nodesOf, updatedVectorOf } from './ir/nodes.mjs';
33
- import { nodeReads, vectorReads } from './ir/reads.mjs';
35
+ import { conditionalsOf, isStateDriven, nodesOf, updatedVectorOf, } from './ir/nodes.mjs';
36
+ import { expressionReads, listStates, nodeReads, vectorReads, workedStates, } from './ir/reads.mjs';
37
+ import { wideSlotOf } from './ir/types.mjs';
38
+ import { bindDerivedList, renderBindings } from './list-order.mjs';
39
+ import { bindContextUses, contextsOf, refuseHiddenContexts, } from './contexts.mjs';
34
40
  /*----------------------------------------------------------------------------------------------------------------------
35
41
  - Implementation
36
42
  ---------------------------------------------------------------------------------------------------------------------*/
37
43
  /**
38
- * Settles what only the whole app decides. With nothing for app_update() to re-apply there is no app_update(),
39
- * so no body ends by calling it. A composition that no start waits on has no waits for a stop to end.
44
+ * Settles what only the whole app decides. With nothing for an update to re-apply there is no update,
45
+ * so no body ends by asking for one. A composition that no start waits on has no waits for a stop to end.
40
46
  *
41
- * @param out The lowered app's functions.
42
- * @param hasUpdate The app has an app_update().
47
+ * @param output The lowered app's functions.
48
+ * @param hasUpdate The app has an update.
43
49
  */
44
- function settleFunctions(out, hasUpdate) {
45
- const idleOwners = new Set([...out.animWaits.values()]
50
+ function settleFunctions(output, hasUpdate) {
51
+ const idleOwners = new Set([...output.animationWaits.values()]
46
52
  .filter(record => !record.isStarted)
47
53
  .map(record => record.owner));
48
- const settleStmts = (stmts) => {
49
- for (const stmt of stmts) {
50
- if (stmt.kind === 'stopAnimations') {
51
- if (stmt.waitOwner !== null && idleOwners.has(stmt.waitOwner)) {
52
- stmt.waitOwner = null;
54
+ const settleStmts = (statements) => {
55
+ for (const statement of statements) {
56
+ if (statement.kind === 'stopAnimations') {
57
+ if (statement.waitOwner !== null &&
58
+ idleOwners.has(statement.waitOwner)) {
59
+ statement.waitOwner = null;
53
60
  }
54
61
  }
55
- else if (stmt.kind === 'if') {
56
- settleStmts(stmt.consequent);
57
- settleStmts(stmt.alternate ?? []);
62
+ else if (statement.kind === 'if') {
63
+ settleStmts(statement.consequent);
64
+ settleStmts(statement.alternate ?? []);
65
+ }
66
+ else if (statement.kind === 'block' || statement.kind === 'loop') {
67
+ settleStmts(statement.body);
58
68
  }
59
69
  }
60
70
  };
@@ -66,7 +76,7 @@ function settleFunctions(out, hasUpdate) {
66
76
  }
67
77
  settleStmts(callback.body);
68
78
  };
69
- for (const handler of out.handlers) {
79
+ for (const handler of output.handlers) {
70
80
  if (handler.kind === 'callback') {
71
81
  settle(handler.callback);
72
82
  }
@@ -74,15 +84,18 @@ function settleFunctions(out, hasUpdate) {
74
84
  settle(handler.event.callback);
75
85
  }
76
86
  }
77
- for (const timer of out.timerFns) {
87
+ for (const timer of output.timerFunctions) {
78
88
  settle(timer.callback);
79
89
  }
80
- for (const animationCallback of out.animCbs) {
90
+ for (const handler of output.nativeEventHandlers) {
91
+ settle(handler.callback);
92
+ }
93
+ for (const animationCallback of output.animationCallbacks) {
81
94
  if (animationCallback.kind === 'completion') {
82
95
  settle(animationCallback.completion);
83
96
  }
84
97
  }
85
- for (const effectFunction of out.effectFns) {
98
+ for (const effectFunction of output.effectFunctions) {
86
99
  if (effectFunction.kind === 'mount') {
87
100
  settleStmts(effectFunction.body);
88
101
  }
@@ -93,7 +106,7 @@ function settleFunctions(out, hasUpdate) {
93
106
  settleStmts(effectFunction.effect.body);
94
107
  }
95
108
  }
96
- for (const mountEffect of out.mountEffects) {
109
+ for (const mountEffect of output.mountEffects) {
97
110
  if (mountEffect.kind === 'inline') {
98
111
  settle(mountEffect.callback);
99
112
  }
@@ -103,23 +116,33 @@ function settleFunctions(out, hasUpdate) {
103
116
  }
104
117
  }
105
118
  /**
106
- * Flags each state a node or drawing reads, so a write to it marks it changed and app_update() sets them again.
107
- * A node that also reads something untracked is set on every update, so its reads need no flag.
119
+ * Flags each state a node, drawing, or conditional reads, so a write to it marks it changed and the update sets
120
+ * them again. One that also reads something untracked is set on every update, so its reads need no flag.
108
121
  *
109
- * @param nodes The app's nodes.
122
+ * @param root The app's tree.
123
+ * @param derivedLists The lists filtered, sorted or split in render.
124
+ * @param workedValues The values memos and helpers loop for in render.
110
125
  */
111
- function watchState(nodes) {
112
- for (const node of nodes) {
113
- const vector = updatedVectorOf(node);
114
- for (const reads of [nodeReads(node), vector && vectorReads(vector)]) {
115
- reads?.forEach(record => {
116
- record.isWatched = true;
117
- });
118
- }
126
+ function watchState(root, derivedLists, workedValues) {
127
+ const reads = [
128
+ ...nodesOf(root).flatMap(node => {
129
+ const vector = updatedVectorOf(node);
130
+ return [nodeReads(node), vector && vectorReads(vector)];
131
+ }),
132
+ ...conditionalsOf(root).map(conditional => expressionReads(conditional.test)),
133
+ // A handler can read a filtered or sorted list that nothing draws, which must still be rebuilt.
134
+ ...derivedLists.map(listStates),
135
+ // So can a value a memo or a helper loops for.
136
+ ...workedValues.map(workedStates),
137
+ ];
138
+ for (const read of reads) {
139
+ read?.forEach(record => {
140
+ record.isWatched = true;
141
+ });
119
142
  }
120
143
  }
121
144
  /**
122
- * Refuses state C cannot hold: a number in a list item that has no C form, and a host value that would take
145
+ * Refuses state a package cannot hold: a number in a list item that isn't finite, and a host value that would take
123
146
  * the name of the setter every app exports for the wall clock. A field an item leaves out starts at 0.
124
147
  *
125
148
  * @param stateRecords The app's state, then each inlined instance's.
@@ -130,9 +153,10 @@ function checkStateRecords(stateRecords) {
130
153
  continue;
131
154
  for (const item of record.items) {
132
155
  for (const field of record.struct.fields) {
133
- const value = item[field.key];
134
- if (field.kind === 'string' || value == null)
156
+ const { present, value } = itemValueAt(item, field);
157
+ if (field.kind === 'string' || field.kind === 'bool' || !present) {
135
158
  continue;
159
+ }
136
160
  const number = Number(value);
137
161
  if (field.kind === 'float' || !Number.isFinite(number)) {
138
162
  checkNumber(number);
@@ -140,25 +164,42 @@ function checkStateRecords(stateRecords) {
140
164
  }
141
165
  }
142
166
  }
143
- if (stateRecords.some(record => record.kind === 'scalar' && record.host && record.name === 'wall_clock')) {
144
- throw aotError('AOT: useHostValue("wall_clock") would collide with er_app_set_wall_clock()', 'rename the host value — every app exports er_app_set_wall_clock() for Date.now().');
167
+ }
168
+ /**
169
+ * Widens each int slot that has to hold 64 bits. A state or ref slot is typed from its initial value, so
170
+ * `useState(0)` is an int until a setter stores Date.now() in it; the values lowering stored into the int slots
171
+ * say which hold a timestamp or a number past the int range, following one through every slot it reaches.
172
+ *
173
+ * @param wide Takes the slots widened, and what each holds.
174
+ * @param stores Every value lowering stored into an int slot.
175
+ */
176
+ function widenSlots(wide, stores) {
177
+ for (const [slot, width] of inferWideSlots(stores, new Map())) {
178
+ wide.set(slot, width);
179
+ }
180
+ for (const { slot, target } of stores) {
181
+ const width = wideSlotOf(wide, slot);
182
+ if (target && width) {
183
+ target.slotKind = 'i64';
184
+ target.widened = width;
185
+ }
145
186
  }
146
187
  }
147
188
  /**
148
- * Lowers a Flow B app's JSX (or TSX) source, then runs the check pass over what lowering recorded. Pure (no
149
- * I/O); writeApp (assemble.mts) writes the result as C.
189
+ * Lowers a Flow B app's JSX (or TSX) source, widens the slots that hold 64 bits, then runs the typing pass and
190
+ * the check pass over what lowering recorded. Pure (no I/O); the package backend (package/) writes the result.
150
191
  *
151
- * @param src The App.jsx/App.tsx source text.
152
- * @param opts compileSource's options, resolved (see resolveOptions).
153
- * @param wide State/ref slots to declare 64-bit (see compileWidened).
154
- * @param stores Collects every value stored into an int slot.
192
+ * @param source The App.jsx/App.tsx source text.
193
+ * @param options compilePackage's options, resolved (see resolveOptions).
155
194
  *
156
195
  * @returns The lowered app.
157
196
  */
158
- export function lowerApp(src, opts, wide, stores) {
159
- beginBoot();
197
+ export function lowerApp(source, options) {
198
+ beginBoot(source);
160
199
  try {
161
- const { result, checks } = lowerWithChecks(() => lowerProgram(src, opts, wide, stores));
200
+ const wide = new Map();
201
+ const stores = [];
202
+ const { result, checks } = lowerWithChecks(() => lowerProgram(source, options, wide, stores), () => widenSlots(wide, stores));
162
203
  const app = { ...result, boot: endBoot(), checks };
163
204
  runChecks(app.checks);
164
205
  return app;
@@ -171,58 +212,119 @@ export function lowerApp(src, opts, wide, stores) {
171
212
  * Runs the compiler passes over the parsed app, from its module scope and hooks through the element tree to its
172
213
  * effects, recording the values the check pass checks.
173
214
  *
174
- * @param src The App.jsx/App.tsx source text.
175
- * @param opts compileSource's options, resolved (see resolveOptions).
176
- * @param wide State/ref slots to declare 64-bit (see compileWidened).
215
+ * @param source The App.jsx/App.tsx source text.
216
+ * @param options compilePackage's options, resolved (see resolveOptions).
217
+ * @param wide Takes the slots the typing pass widens.
177
218
  * @param stores Collects every value stored into an int slot.
178
219
  *
179
220
  * @returns The lowered app, without its checks.
180
221
  */
181
- function lowerProgram(src, opts, wide, stores) {
222
+ function lowerProgram(source, options, wide, stores) {
182
223
  // Parse the app and prepare the AST for the passes below.
183
- const ast = parseApp(src, opts);
224
+ let nativeModules = new Map();
225
+ const ast = parseApp(source, options, typed => {
226
+ nativeModules = collectNativeModules(typed.program, options.nativeFiles);
227
+ });
184
228
  normalizeUndefined(ast);
229
+ rewriteWindowDimensions(ast);
230
+ inlineCustomHooks(ast);
231
+ refuseHiddenContexts(ast);
185
232
  const shadowedClock = findShadowedClockCalls(ast);
186
233
  // Seed the module scope with image imports (each is its baked-name string) so consts that use them can fold.
187
- const { screen } = opts;
234
+ const { screen } = options;
188
235
  const imageImports = collectImageImports(ast.program);
189
236
  const svgImports = collectSvgImports(ast.program);
190
237
  const imageSeed = Object.fromEntries([...imageImports].map(([local, imageImport]) => [local, imageImport.name]));
191
238
  const scope = moduleScope(ast.program, screen, imageSeed);
192
239
  // Snapshot module bindings before App's consts fold in: child components close over these, not App's shadows.
193
- const moduleConsts = { ...scope };
240
+ const moduleConstants = { ...scope };
194
241
  const component = findComponent(ast.program);
195
242
  // Hide redeclared module names, then fold the body's static consts so responsive `if`s resolve at compile time.
196
243
  for (const name of declaredNames(component.body.body)) {
197
244
  delete scope[name];
198
245
  }
246
+ // What the module itself can read, where a context's default is worked out.
247
+ const imageNames = new Map([...imageImports].map(([, imageImport]) => [
248
+ imageImport.name,
249
+ imageImport.importPath,
250
+ ])); // asset name → path
251
+ const moduleEnvironment = {
252
+ state: new Map(),
253
+ locals: new Map(),
254
+ constants: moduleConstants,
255
+ moduleConstants,
256
+ animations: new Map(),
257
+ refs: new Map(),
258
+ pans: new Map(),
259
+ callbacks: new Map(),
260
+ helpers: collectHelpers({ type: 'BlockStatement', body: [], directives: [] }, ast.program),
261
+ imageNames,
262
+ svgImports,
263
+ svgArtifacts: options.svgArtifacts || {},
264
+ caps: options.caps,
265
+ wide,
266
+ stores,
267
+ shadowedClock,
268
+ constantLists: new Map(),
269
+ derivedLists: new Map(),
270
+ workedValues: new Map(),
271
+ splitLists: new Map(),
272
+ functionProps: new Map(),
273
+ children: null,
274
+ nativeModules,
275
+ };
276
+ moduleEnvironment.contexts = {
277
+ records: contextsOf(ast.program),
278
+ defaults: moduleEnvironment,
279
+ };
280
+ // The App has no provider above it, so a context it reads is the default.
281
+ const appLocals = new Map();
282
+ const appFunctionProps = new Map();
283
+ const contextNames = bindContextUses(component.body, moduleEnvironment, {
284
+ scope,
285
+ locals: appLocals,
286
+ functionProps: appFunctionProps,
287
+ lists: new Map(),
288
+ });
199
289
  for (const statement of component.body.body) {
200
290
  if (statement.type !== 'VariableDeclaration' ||
201
291
  statement.kind !== 'const') {
202
292
  continue;
203
293
  }
204
- for (const decl of statement.declarations) {
205
- if (decl.id.type !== 'Identifier' || !decl.init)
294
+ for (const declarator of statement.declarations) {
295
+ if (declarator.id.type === 'ObjectPattern' && declarator.init) {
296
+ try {
297
+ bindFoldedPattern(scope, declarator.id, declarator.init);
298
+ }
299
+ catch (error) {
300
+ rethrowFoldLimit(error); // not a fold, so bindBuiltValues binds it
301
+ }
302
+ continue;
303
+ }
304
+ if (declarator.id.type !== 'Identifier' || !declarator.init)
305
+ continue;
306
+ if (contextNames.has(declarator.id.name))
206
307
  continue;
207
308
  try {
208
- setBinding(scope, decl.id.name, bindConst(decl.id.name, evalStatic(decl.init, withUndefined(scope), 'boot')));
309
+ setBinding(scope, declarator.id.name, bindConst(declarator.id.name, evalStatic(declarator.init, withUndefined(scope), 'boot')));
209
310
  }
210
- catch {
311
+ catch (error) {
312
+ rethrowFoldLimit(error);
211
313
  // A dynamic const must hide a same-named module const, or the JSX quietly renders the module value.
212
- delete scope[decl.id.name];
314
+ delete scope[declarator.id.name];
213
315
  }
214
316
  }
215
317
  }
216
318
  // Collect the component's state; a state name hides any module const of the same name from the folds.
217
- const state = collectState(component.body, scope, opts.caps, '', wide);
319
+ const state = collectState(component.body, scope, options.caps, '', ast.program);
218
320
  for (const name of state.byName.keys()) {
219
321
  delete scope[name];
220
322
  }
221
323
  // Collect the component's other hooks, plus the file's helpers and child components.
222
324
  const rootJSX = findReturnJSX(component.body, scope);
223
- const anims = collectAnims(component.body, scope);
224
- const refs = collectRefs(component.body, scope, '', wide);
225
- for (const name of [...anims.keys(), ...refs.keys()]) {
325
+ const animations = collectAnims(component.body, scope);
326
+ const refs = collectRefs(component.body, scope);
327
+ for (const name of [...animations.keys(), ...refs.keys()]) {
226
328
  delete scope[name];
227
329
  }
228
330
  const pans = collectPanResponders(component.body);
@@ -230,82 +332,115 @@ function lowerProgram(src, opts, wide, stores) {
230
332
  const memos = collectMemos(component.body);
231
333
  const helpers = collectHelpers(component.body, ast.program);
232
334
  const components = collectComponents(ast.program);
233
- const imageNames = new Map([...imageImports].map(([, imageImport]) => [
234
- imageImport.name,
235
- imageImport.importPath,
236
- ])); // asset name → path
237
335
  // The expression environment every emitter compiles against.
238
- const env = {
336
+ const environment = {
239
337
  state: state.byName,
240
- locals: new Map(),
241
- consts: scope,
242
- moduleConsts, // what an inlined child component sees (see emitComponent)
243
- animations: anims,
338
+ locals: appLocals,
339
+ constants: scope,
340
+ moduleConstants, // what an inlined child component sees (see emitComponent)
341
+ animations: animations,
244
342
  refs,
245
343
  pans,
246
344
  callbacks,
247
345
  helpers,
248
346
  imageNames,
249
347
  svgImports,
250
- svgArtifacts: opts.svgArtifacts || {},
251
- caps: opts.caps,
348
+ svgArtifacts: options.svgArtifacts || {},
349
+ caps: options.caps,
252
350
  wide,
253
351
  stores,
254
352
  shadowedClock,
353
+ constantLists: moduleEnvironment.constantLists,
354
+ derivedLists: moduleEnvironment.derivedLists,
355
+ workedValues: moduleEnvironment.workedValues,
356
+ splitLists: moduleEnvironment.splitLists,
357
+ functionProps: appFunctionProps,
358
+ contexts: moduleEnvironment.contexts,
359
+ nativeModules,
255
360
  };
256
361
  // A value worked out at boot lowers its slot against the app's environment.
257
- setBootLowering(env, lowerExpr);
258
- // Before emit, fold each memo or inline its C expression at each use (no cache needed: dep tracking re-applies).
259
- for (const [name, expr] of memos) {
362
+ setBootLowering(environment, lowerExpr);
363
+ settleBootInitials(state.byName.values());
364
+ // Before emit, fold each memo or inline its expression at each use (no cache needed: dep tracking re-applies).
365
+ for (const { name, expression, isMemo } of renderBindings(component.body, memos)) {
366
+ if (!isMemo) {
367
+ bindDerivedList(name, expression, environment);
368
+ continue;
369
+ }
260
370
  try {
261
- setBinding(scope, name, bindConst(name, evalStatic(expr, scope, 'boot')));
371
+ setBinding(scope, name, bindConst(name, evalStatic(expression, scope, 'boot')));
262
372
  }
263
- catch {
264
- const cExpr = emitSourcedWide(expr, env);
265
- env.locals.set(name, {
266
- code: `(${cExpr.code})`,
267
- cType: cExpr.cType,
268
- isBool: cExpr.isBool,
269
- lit: cExpr.lit,
270
- wide: cExpr.wide,
271
- source: cExpr.source,
272
- });
373
+ catch (error) {
374
+ rethrowFoldLimit(error);
375
+ if (bindDerivedList(name, expression, environment)) {
376
+ continue;
377
+ }
378
+ if (expression.type === 'ArrayExpression' ||
379
+ expression.type === 'ObjectExpression') {
380
+ setBinding(scope, name, foldRuntime(expression, environment));
381
+ continue;
382
+ }
383
+ environment.locals.set(name, lowerLocal(expression, environment));
273
384
  delete scope[name]; // a runtime binding beats a module const of its name in every fold
274
385
  }
275
386
  }
276
- // Emit the scene graph from the root JSX; `out` collects every generated fragment.
277
- const out = new Out(components, ast.program);
387
+ bindBuiltValues(component.body.body, environment);
388
+ // Emit the scene graph from the root JSX; `output` collects everything else it lowers.
389
+ const output = new Out(components, ast.program);
390
+ output.release = Boolean(options.release);
391
+ output.optionalModules = optionalModulesOf(nativeModules);
278
392
  const keyboard = lowerKeyboardConfig(ast.program); // a module-level setKeyboardConfig({...})
279
- const root = emitNode(rootJSX, scope, out, env, state);
393
+ const root = emitNode(rootJSX, scope, output, environment, state);
280
394
  // Emit registered only the images it reached; a dynamic source can't be enumerated, so bake every import.
281
- if (out.bakeAllImages) {
395
+ if (output.bakeAllImages) {
282
396
  for (const [, imageImport] of imageImports) {
283
- out.images.set(imageImport.name, imageImport.importPath);
397
+ output.images.set(imageImport.name, imageImport.importPath);
284
398
  }
285
399
  }
286
- // Lower effects (mount-once or dep-driven) after emit, so out.timerFns/usesTimers include handler timers too.
400
+ // Lower effects (mount-once or dep-driven) after emit, so output.timerFunctions includes handler timers too.
287
401
  for (const effect of collectEffects(component.body)) {
288
- lowerEffect(effect, env, state, out);
402
+ lowerEffect(effect, environment, state, output);
289
403
  }
290
- // app_update() exists only when something has to be re-applied after a state change.
291
- const hasUpdate = nodesOf(root).some(node => isStateDriven(node) || updatedVectorOf(node) !== null) || out.depEffects.length > 0;
292
- settleFunctions(out, hasUpdate);
293
- if (hasUpdate) {
294
- watchState(nodesOf(root));
404
+ for (const call of collectNativeEvents(component.body)) {
405
+ lowerNativeEvent(call, environment, state, output);
295
406
  }
296
- const stateRecords = [...state.byName.values(), ...out.childStateRecords];
407
+ // An update exists only when something has to be re-applied after a state change, or a list filtered or sorted
408
+ // in render rebuilt.
409
+ const derivedLists = [...environment.derivedLists.values()].flatMap(lists => [...lists.values()]);
410
+ const workedValues = [...environment.workedValues.values()].flatMap(values => [...values.values()]);
411
+ // What the tree reads is known once it is typed.
412
+ whenTyped(() => {
413
+ const hasUpdate = nodesOf(root).some(node => isStateDriven(node) || updatedVectorOf(node) !== null) ||
414
+ conditionalsOf(root).some(conditional => !conditional.toggle) ||
415
+ output.dependencyEffects.length > 0 ||
416
+ derivedLists.length > 0 ||
417
+ workedValues.length > 0;
418
+ settleFunctions(output, hasUpdate);
419
+ if (hasUpdate) {
420
+ watchState(root, derivedLists, workedValues);
421
+ }
422
+ });
423
+ const stateRecords = [
424
+ ...state.byName.values(),
425
+ ...output.childStateRecords,
426
+ ...environment.constantLists.values(),
427
+ ...derivedLists,
428
+ ...workedValues,
429
+ ...[...environment.splitLists.values()].flatMap(lists => [
430
+ ...lists.values(),
431
+ ]),
432
+ ];
297
433
  checkStateRecords(stateRecords);
298
434
  return {
299
435
  state: stateRecords,
300
- refs: [...refs.values(), ...out.childRefs],
301
- animations: [...anims.values(), ...out.childAnimations],
436
+ refs: [...refs.values(), ...output.childRefs],
437
+ animations: [...animations.values(), ...output.childAnimations],
302
438
  keyboard,
303
439
  root,
304
- hasUpdate,
305
- images: [...out.images.entries()].map(([name, importPath]) => ({
440
+ images: [...output.images.entries()].map(([name, importPath]) => ({
306
441
  name,
307
442
  importPath,
308
443
  })),
309
- out,
444
+ output,
310
445
  };
311
446
  }