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
@@ -0,0 +1,2103 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*
17
+ * The package backend: lowers the IR to a Flow B program for one panel.
18
+ *
19
+ * The tree becomes the root template and its constant prop sets. State, refs and values worked out at boot are
20
+ * slots in the arena. Handlers, timer callbacks, effects, the boot function and the update function are
21
+ * bytecode (codegen.mts). The update re-sets a node when a state it reads changed, sets
22
+ * the props of a node that reads only boot values once, in its first pass, and queues the effects.
23
+ *
24
+ * An <Svg> drawing is a tape (vectors.mts): a baked one is committed when its node is built, and the update
25
+ * rebuilds one state drives, after the nodes. setKeyboardConfig is the keyboard table, which
26
+ * the runtime hands the engine at load.
27
+ *
28
+ * Animations (animations.mts): each animation is a leaf descriptor, each on_complete callback an
29
+ * animation-done function, each completion a helper.
30
+ *
31
+ * A list is a pool of rows in the arena. Its `.map` is a row template, built once per row in the update's first
32
+ * pass; a row shows while the list holds it. Rows whose nodes and handlers
33
+ * are the same share a template, and a row handler reads its item through the row it was built for.
34
+ *
35
+ * A conditional on state is a branch template for each branch that has an element. The update destroys a branch
36
+ * once its test picks another, then builds the one picked, before the first sibling after it that is built. All
37
+ * the destroys of a pass come before its builds, so the panel's nodes are the most any one state of the app shows
38
+ * at once. A conditional in a list row builds every branch with the row instead, and shows the one picked.
39
+ *
40
+ * A PanResponder is a handler for each responder event and a query function for each should-set predicate,
41
+ * bound on each node that spreads it. Its gesture state is slots, kept by its grant, release and terminate
42
+ * handlers, and a callback reads the gesture through them and EVT.
43
+ *
44
+ * An effect runs after an update pass, and one that set state asks for another, which shows what it set, as
45
+ * React renders again after an effect sets state. A dep-driven effect checks its deps itself, when it runs,
46
+ * each in turn. The mount effects run one after another, after the first pass; one that set state has the
47
+ * pass after it queue the next.
48
+ */
49
+ /*----------------------------------------------------------------------------------------------------------------------
50
+ - Imports
51
+ ---------------------------------------------------------------------------------------------------------------------*/
52
+ import { aotError, constantText, ENGINE_STRING_MAX, locateError, } from '../diagnostics.mjs';
53
+ import { hasRuntimeProps, isStateDriven, nodesOf, branchElements, stateDrivenVectorOf, updatedVectorOf, } from '../ir/nodes.mjs';
54
+ import { expressionReads, listReads, nodeReads, vectorReads, workedReads, } from '../ir/reads.mjs';
55
+ import { armedFlag } from '../ir/functions.mjs';
56
+ import { AnimationPlan, doneFunctions, startPressFade } from './animations.mjs';
57
+ import { Arena } from './arena.mjs';
58
+ import { FunctionBuilder, OP } from './bytecode.mjs';
59
+ import { internedStates } from './enums.mjs';
60
+ import { longestLiteral, stringCaps } from './string-caps.mjs';
61
+ import { Codegen, notYet } from './codegen.mjs';
62
+ import { BindingKind, ENGINE_VALUES, EventField, FLAG_DEBUG, FRAME_CELLS, FunctionKind, MAX_SPANS, NONE, Resource, SlotFlag, TemplateKind, ValueType, } from './format.mjs';
63
+ import { abiProp, constantPropEntry, floatBits, stringPropEntry, } from './props.mjs';
64
+ import { ProgramTables } from './tables.mjs';
65
+ import { itemValueAt, rowEntries } from '../list-items.mjs';
66
+ import { commitDrawing, VectorPlan } from './vectors.mjs';
67
+ import { lowerCheck } from './checks.mjs';
68
+ import { MAX_NATIVE_EVENTS } from '../native-modules.mjs';
69
+ /*----------------------------------------------------------------------------------------------------------------------
70
+ - Constants
71
+ ---------------------------------------------------------------------------------------------------------------------*/
72
+ /** The most a u16 count or size in the format holds: a row's bytes, a panel's nodes, the row fields. */
73
+ const MAX_U16 = 0xffff;
74
+ /** BUILD's instance operand when the template is no list row's. */
75
+ const NO_REGISTER = 0xff;
76
+ /** The most fields a row has: ROWGET names one in a byte. */
77
+ const MAX_ROW_FIELDS = 255;
78
+ /** Key kind → its ERKeyboardKey type. */
79
+ const KEY_TYPES = {
80
+ char: 'ER_KEYBOARD_KEY_CHAR',
81
+ layer: 'ER_KEYBOARD_KEY_LAYER',
82
+ backspace: 'ER_KEYBOARD_KEY_BACKSPACE',
83
+ done: 'ER_KEYBOARD_KEY_DONE',
84
+ };
85
+ /** The highlight layer that means "never highlighted". */
86
+ const NEVER_HIGHLIGHTED = 255;
87
+ /** A TextSpan's constant fields, in their ABI ids' order. */
88
+ const SPAN_FIELDS = [
89
+ 'color',
90
+ 'font_size',
91
+ 'font_weight',
92
+ 'font_style',
93
+ 'text_decoration',
94
+ 'letter_spacing',
95
+ ];
96
+ /*----------------------------------------------------------------------------------------------------------------------
97
+ - Implementation
98
+ ---------------------------------------------------------------------------------------------------------------------*/
99
+ /**
100
+ * Refuses what a package can't lower yet, pointing at where it is.
101
+ *
102
+ * @param what What the app uses.
103
+ * @param location Where in the source, when it is known.
104
+ */
105
+ function notYetAt(what, location) {
106
+ try {
107
+ notYet(what);
108
+ }
109
+ catch (error) {
110
+ locateError(error, location);
111
+ throw error;
112
+ }
113
+ }
114
+ /** Whether the update sets a node's props once, at load: they read only boot values, or it has spans. */
115
+ const isSetOnce = (node) => !isStateDriven(node) && (hasRuntimeProps(node) || node.spans !== null);
116
+ /*----------------------------------------------------------------------------------------------------------------------
117
+ - Slots
118
+ ---------------------------------------------------------------------------------------------------------------------*/
119
+ /**
120
+ * Every string local a statement list declares.
121
+ *
122
+ * @param statements The statements.
123
+ * @param found Collects each local's name.
124
+ */
125
+ function stringLocals(statements, found) {
126
+ for (const statement of statements) {
127
+ if (statement.kind === 'declareLocal' &&
128
+ statement.initializer.type.kind === 'string') {
129
+ found.add(statement.name);
130
+ }
131
+ else if (statement.kind === 'if') {
132
+ stringLocals(statement.consequent, found);
133
+ stringLocals(statement.alternate ?? [], found);
134
+ }
135
+ else if (statement.kind === 'block') {
136
+ stringLocals(statement.body, found);
137
+ }
138
+ else if (statement.kind === 'loop') {
139
+ stringLocals(statement.body, found);
140
+ stringLocals(statement.step, found);
141
+ }
142
+ }
143
+ }
144
+ /**
145
+ * Every native call in a value that returns strings, at any depth: each copies them into buffers of its own.
146
+ *
147
+ * @param value The statements, or any part of them.
148
+ * @param found Collects the calls.
149
+ * @param seen What has been walked, so a value reached twice is walked once.
150
+ */
151
+ function stringNativeCalls(value, found, seen = new Set()) {
152
+ if (!value || typeof value !== 'object' || seen.has(value))
153
+ return;
154
+ seen.add(value);
155
+ if (Array.isArray(value)) {
156
+ value.forEach(child => stringNativeCalls(child, found, seen));
157
+ return;
158
+ }
159
+ const record = value;
160
+ const call = record;
161
+ if (call.import &&
162
+ call.callArguments &&
163
+ call.import.results.includes('string')) {
164
+ found.add(call);
165
+ }
166
+ for (const [key, child] of Object.entries(record)) {
167
+ // Where a value came from repeats its reads, and a location holds none.
168
+ if (key !== 'source' && key !== 'location') {
169
+ stringNativeCalls(child, found, seen);
170
+ }
171
+ }
172
+ }
173
+ /**
174
+ * Every updateVector call a statement list makes.
175
+ *
176
+ * @param statements The statements.
177
+ * @param found Collects the calls.
178
+ */
179
+ function updateVectors(statements, found) {
180
+ for (const statement of statements) {
181
+ if (statement.kind === 'updateVector') {
182
+ found.push(statement);
183
+ }
184
+ else if (statement.kind === 'if') {
185
+ updateVectors(statement.consequent, found);
186
+ updateVectors(statement.alternate ?? [], found);
187
+ }
188
+ else if (statement.kind === 'block') {
189
+ updateVectors(statement.body, found);
190
+ }
191
+ else if (statement.kind === 'loop') {
192
+ updateVectors(statement.body, found);
193
+ updateVectors(statement.step, found);
194
+ }
195
+ }
196
+ }
197
+ /**
198
+ * Every state and list a statement list sets.
199
+ *
200
+ * @param statements The statements.
201
+ * @param found Collects the states.
202
+ */
203
+ function statesSet(statements, found) {
204
+ for (const statement of statements) {
205
+ if (statement.kind === 'setState' || statement.kind === 'setStateText') {
206
+ found.add(statement.state);
207
+ }
208
+ else if ('list' in statement) {
209
+ found.add(statement.list);
210
+ }
211
+ else if (statement.kind === 'if') {
212
+ statesSet(statement.consequent, found);
213
+ statesSet(statement.alternate ?? [], found);
214
+ }
215
+ else if (statement.kind === 'block') {
216
+ statesSet(statement.body, found);
217
+ }
218
+ else if (statement.kind === 'loop') {
219
+ statesSet(statement.body, found);
220
+ statesSet(statement.step, found);
221
+ }
222
+ }
223
+ }
224
+ /**
225
+ * The type a dep's copy is kept in.
226
+ *
227
+ * @param dependency The dep.
228
+ *
229
+ * @returns Its type.
230
+ */
231
+ function depType(dependency) {
232
+ switch (dependency.type.kind) {
233
+ case 'bool':
234
+ case 'float':
235
+ case 'int64':
236
+ case 'string':
237
+ return dependency.type.kind;
238
+ default:
239
+ return 'int';
240
+ }
241
+ }
242
+ /**
243
+ * Whether a dep-driven effect or its cleanup sets state, so an update runs after it.
244
+ *
245
+ * @param effect The effect.
246
+ *
247
+ * @returns Whether it does.
248
+ */
249
+ const setsState = (effect) => {
250
+ const states = new Set();
251
+ statesSet(effect.body, states);
252
+ statesSet(effect.cleanup ?? [], states);
253
+ return states.size > 0;
254
+ };
255
+ /**
256
+ * Whether a mount effect sets state, so an update runs after it.
257
+ *
258
+ * @param mountEffect The mount effect.
259
+ *
260
+ * @returns Whether it does.
261
+ */
262
+ const mountUpdates = (mountEffect) => mountEffect.kind === 'inline'
263
+ ? mountEffect.callback.updatesState
264
+ : mountEffect.kind === 'call' && mountEffect.updatesState;
265
+ /**
266
+ * Every statement list the program runs outside the update and boot functions.
267
+ *
268
+ * @param app The app.
269
+ *
270
+ * @returns The lists.
271
+ */
272
+ function bodies(app) {
273
+ const { output } = app;
274
+ return [
275
+ ...output.handlers.flatMap(handler => handler.kind === 'callback'
276
+ ? [handler.callback.body]
277
+ : handler.kind === 'panEvent' && handler.event.callback
278
+ ? [handler.event.callback.body]
279
+ : []),
280
+ ...output.timerFunctions.map(timer => timer.callback.body),
281
+ ...output.nativeEventHandlers.map(handler => handler.callback.body),
282
+ ...output.effectFunctions.map(effectFunction => effectFunction.kind === 'mount'
283
+ ? effectFunction.body
284
+ : effectFunction.kind === 'cleanup'
285
+ ? effectFunction.effect.cleanup
286
+ : effectFunction.effect.body),
287
+ ...output.mountEffects.flatMap(mountEffect => mountEffect.kind === 'inline' ? [mountEffect.callback.body] : []),
288
+ ...completionsOf(app).map(completion => completion.body),
289
+ ];
290
+ }
291
+ /**
292
+ * Every animation completion, in the order the app declares them.
293
+ *
294
+ * @param app The app.
295
+ *
296
+ * @returns The completions.
297
+ */
298
+ const completionsOf = (app) => app.output.animationCallbacks.flatMap(callback => callback.kind === 'completion' ? [callback.completion] : []);
299
+ /**
300
+ * A state's slot: a scalar's own, or a list's pool.
301
+ *
302
+ * @param state The state.
303
+ * @param slots The program's slots.
304
+ *
305
+ * @returns The slot.
306
+ */
307
+ const stateSlotOf = (state, slots) => state.kind === 'list'
308
+ ? slots.lists.get(state).slot
309
+ : slots.states.get(state);
310
+ /**
311
+ * The first node an element builds.
312
+ *
313
+ * @param element The element.
314
+ *
315
+ * @returns The node.
316
+ */
317
+ const firstNode = (element) => element.kind === 'component' ? firstNode(element.root) : element.node;
318
+ /**
319
+ * Walks a tree for its pools and the conditionals that build their branches, and the branch each node sits in.
320
+ * A list inside a list's row is refused.
321
+ *
322
+ * @param element The element.
323
+ * @param within The branch it sits in, or null.
324
+ * @param plan Collects what the walk finds.
325
+ * @param arena Lays out each conditional's slots.
326
+ */
327
+ function planTree(element, within, plan, arena) {
328
+ if (element.kind === 'component') {
329
+ planTree(element.root, within, plan, arena);
330
+ return;
331
+ }
332
+ const { node } = element;
333
+ if (within) {
334
+ plan.places.set(node, within);
335
+ }
336
+ node.children.forEach((child, index) => {
337
+ const after = node.children.slice(index + 1);
338
+ if (child.kind === 'element') {
339
+ planTree(child.element, within, plan, arena);
340
+ }
341
+ else if (child.kind === 'conditional' && child.toggle) {
342
+ branchElements(child).forEach(branch => planTree(branch, within, plan, arena));
343
+ }
344
+ else if (child.kind === 'conditional') {
345
+ const branching = {
346
+ conditional: child,
347
+ alternatives: branchElements(child),
348
+ templates: [],
349
+ parent: node,
350
+ after,
351
+ anchors: [],
352
+ within,
353
+ built: arena.slot(ValueType.int, 0),
354
+ root: arena.slot(ValueType.node),
355
+ nested: [],
356
+ };
357
+ plan.branchings.push(branching);
358
+ for (let outer = within; outer; outer = outer.branching.within) {
359
+ outer.branching.nested.push(branching);
360
+ }
361
+ branching.alternatives.forEach((alternative, place) => planTree(alternative, { branching, alternative: place + 1 }, plan, arena));
362
+ }
363
+ else {
364
+ for (const row of child.rows) {
365
+ const nested = nodesOf(row).find(rowNode => rowNode.children.some(rowChild => rowChild.kind === 'pool'));
366
+ if (nested) {
367
+ notYetAt('a list inside a list row', nested.location);
368
+ }
369
+ if (within) {
370
+ nodesOf(row).forEach(rowNode => plan.places.set(rowNode, within));
371
+ }
372
+ }
373
+ plan.pools.push({
374
+ list: child.list,
375
+ rows: child.rows,
376
+ parent: node,
377
+ after,
378
+ anchors: [],
379
+ within,
380
+ templates: [],
381
+ });
382
+ }
383
+ });
384
+ }
385
+ /**
386
+ * The siblings something goes before, in order: each branch until one that is always built when they are.
387
+ *
388
+ * @param after The siblings after it.
389
+ * @param pools The tree's pools.
390
+ * @param branchings The tree's conditionals that build their branches.
391
+ *
392
+ * @returns The anchors; none when it goes last.
393
+ */
394
+ function anchorsOf(after, pools, branchings) {
395
+ const anchors = [];
396
+ for (const child of after) {
397
+ const first = child.kind === 'element'
398
+ ? child.element
399
+ : child.kind === 'pool'
400
+ ? (pools.find(pool => pool.rows === child.rows)?.rows[0] ?? null)
401
+ : child.toggle
402
+ ? (branchElements(child)[0] ?? null)
403
+ : null;
404
+ if (first) {
405
+ anchors.push({ kind: 'node', node: firstNode(first) });
406
+ return anchors;
407
+ }
408
+ if (child.kind === 'conditional' && !child.toggle) {
409
+ anchors.push({
410
+ kind: 'branching',
411
+ branching: branchings.find(branching => branching.conditional === child),
412
+ });
413
+ }
414
+ }
415
+ return anchors;
416
+ }
417
+ /**
418
+ * Plans every slot the program uses, then lays the arena out.
419
+ *
420
+ * @param app The app.
421
+ * @param tables The program's tables.
422
+ * @param caps The buffer sizes, and the timers that run at once.
423
+ *
424
+ * @returns The slots, the node handles, and the bookkeeping bits.
425
+ */
426
+ function planSlots(app, tables, caps) {
427
+ const { output } = app;
428
+ const arena = new Arena();
429
+ const animations = new AnimationPlan(app, arena);
430
+ const slots = {
431
+ arena,
432
+ tables,
433
+ states: new Map(),
434
+ lists: new Map(),
435
+ refs: new Map(),
436
+ boot: new Map(),
437
+ stringLocals: new Map(),
438
+ nativeStrings: new Map(),
439
+ enums: new Map(),
440
+ kept: new Map(),
441
+ hoisted: new Map(),
442
+ armed: new Map(),
443
+ timerFunctions: new Map(),
444
+ animations,
445
+ gestures: new Map(),
446
+ vectors: new VectorPlan(arena),
447
+ };
448
+ // String state with a closed set of values is an interned enum, starting at its initial value (the first).
449
+ for (const [state, values] of internedStates(app)) {
450
+ slots.enums.set(state, {
451
+ set: slots.enums.size,
452
+ values,
453
+ });
454
+ }
455
+ // Each string buffer is sized from the values that reach it.
456
+ const stringCap = stringCaps(app, new Map([...slots.enums].map(([state, { values }]) => [state, values])), caps.listStrCap - 1);
457
+ // State, each with a dirty bit when a node reads it.
458
+ for (const state of app.state) {
459
+ if (state.kind === 'list') {
460
+ continue;
461
+ }
462
+ const interned = slots.enums.get(state);
463
+ // One the boot function sets starts at 0, so nothing of the build's panel is left in the package.
464
+ const initial = state.bootInitial ? 0 : state.initial;
465
+ const slot = interned
466
+ ? Object.assign(arena.slot(ValueType.enum, 0), { aux: interned.set })
467
+ : state.slotKind === 'string'
468
+ ? arena.slot(ValueType.string, tables.string(String(initial)), stringCap.state(state))
469
+ : state.slotKind === 'i64'
470
+ ? arena.slot(ValueType.int64, tables.constant64(BigInt(Math.trunc(Number(initial)))))
471
+ : state.slotKind === 'float'
472
+ ? arena.slot(ValueType.float, floatBits(Number(initial)))
473
+ : arena.slot(state.isBoolean ? ValueType.bool : ValueType.int, Math.trunc(Number(initial)) | 0);
474
+ // A host value an effect's deps may read runs an update when it is set.
475
+ if (state.isWatched || (state.host && output.dependencyEffects.length)) {
476
+ arena.track(slot);
477
+ }
478
+ slots.states.set(state, slot);
479
+ }
480
+ // The copy a body keeps of a state it sets and then reads: a slot like the state's, which nothing watches.
481
+ for (const state of output.keptStates) {
482
+ const interned = slots.enums.get(state);
483
+ slots.kept.set(state, interned
484
+ ? Object.assign(arena.slot(ValueType.enum, 0), { aux: interned.set })
485
+ : state.slotKind === 'string'
486
+ ? arena.slot(ValueType.string, tables.string(''), stringCap.state(state))
487
+ : state.slotKind === 'i64'
488
+ ? arena.slot(ValueType.int64, tables.constant64(0n))
489
+ : state.slotKind === 'float'
490
+ ? arena.slot(ValueType.float, 0)
491
+ : arena.slot(state.isBoolean ? ValueType.bool : ValueType.int, 0));
492
+ }
493
+ // A list is a pool of rows, empty at load; the boot function appends its first items. Each row field is
494
+ // 4-aligned, and a string field holds its cap and a terminator.
495
+ const rows = [];
496
+ for (const state of app.state) {
497
+ if (state.kind !== 'list') {
498
+ continue;
499
+ }
500
+ if (!state.struct.fields.length) {
501
+ notYet(`list state "${state.name}", whose items have no fields`);
502
+ }
503
+ const entries = rowEntries(state.struct);
504
+ if (entries.length > MAX_ROW_FIELDS) {
505
+ throw aotError(`AOT: list state "${state.name}" has ${entries.length} fields, but a package row holds ${MAX_ROW_FIELDS}`, 'give the items fewer fields, or fewer that some items leave out (each of those takes two).');
506
+ }
507
+ let size = 0;
508
+ const fields = entries.map(({ field, presence }) => {
509
+ const isString = !presence && field.kind === 'string';
510
+ const capacity = isString ? stringCap.field(state, field.key) : 0;
511
+ const entry = {
512
+ type: presence ? ValueType.bool : ValueType[field.kind],
513
+ cap: capacity,
514
+ offset: size,
515
+ };
516
+ size += isString ? (capacity + 1 + 3) & ~3 : 4;
517
+ return entry;
518
+ });
519
+ if (size > MAX_U16) {
520
+ throw aotError(`AOT: a row of list state "${state.name}" takes ${size} bytes, but a package row holds ${MAX_U16 - 3}`, 'shorten its strings, or give the items fewer text fields.');
521
+ }
522
+ const slot = arena.list(rows.length, size, state.capacity);
523
+ rows.push({ size, fields });
524
+ if (state.isWatched) {
525
+ arena.track(slot);
526
+ }
527
+ // An appended item's text is built in a buffer of its own, then copied into the row.
528
+ const buffers = new Map(state.struct.fields
529
+ .filter(field => field.kind === 'string')
530
+ .map(field => [
531
+ field.key,
532
+ arena.slot(ValueType.string, undefined, stringCap.field(state, field.key)),
533
+ ]));
534
+ slots.lists.set(state, { slot, buffers });
535
+ }
536
+ const fieldCount = rows.reduce((count, row) => count + row.fields.length, 0);
537
+ if (fieldCount > MAX_U16) {
538
+ throw aotError(`AOT: the lists have ${fieldCount} fields in all, but a package holds ${MAX_U16}`, 'use fewer lists, or give their items fewer fields.');
539
+ }
540
+ for (const ref of app.refs) {
541
+ if (ref.kind !== 'value') {
542
+ continue;
543
+ }
544
+ slots.refs.set(ref, ref.slotKind === 'i64'
545
+ ? arena.slot(ValueType.int64, tables.constant64(BigInt(Math.trunc(ref.initial))))
546
+ : ref.slotKind === 'float'
547
+ ? arena.slot(ValueType.float, floatBits(ref.initial))
548
+ : arena.slot(ValueType.int, Math.trunc(ref.initial) | 0));
549
+ }
550
+ // Boot values: a fraction is kept as a double.
551
+ for (const bootSlot of app.boot.slots) {
552
+ const slot = bootSlot.type.kind === 'float'
553
+ ? arena.slot(ValueType.double)
554
+ : bootSlot.type.kind === 'string'
555
+ ? arena.slot(ValueType.string, undefined, bootSlot.initializer.kind === 'expr'
556
+ ? longestLiteral(bootSlot.initializer.expression)
557
+ : 1)
558
+ : arena.slot(bootSlot.type.kind === 'bool' ? ValueType.bool : ValueType.int);
559
+ slot.flags |= SlotFlag.bootOnly;
560
+ slots.boot.set(bootSlot, slot);
561
+ }
562
+ // The effect locals a cleanup reads, and each effect's armed flag and copy of each dep.
563
+ for (const declaration of output.effectDeclarations) {
564
+ if (declaration.kind === 'local') {
565
+ slots.hoisted.set(declaration.name, declaration.slotKind === 'string'
566
+ ? arena.slot(ValueType.string, undefined, stringCap.local(declaration.name))
567
+ : arena.slot(declaration.slotKind === 'i64'
568
+ ? ValueType.int64
569
+ : declaration.slotKind === 'float'
570
+ ? ValueType.float
571
+ : ValueType.int));
572
+ }
573
+ else if (declaration.kind === 'armed') {
574
+ slots.armed.set(armedFlag(declaration.effect.id), arena.slot(ValueType.bool));
575
+ }
576
+ }
577
+ const copies = new Map();
578
+ for (const effect of output.dependencyEffects) {
579
+ copies.set(effect, effect.dependencies.map(dependency => {
580
+ const type = depType(dependency);
581
+ return {
582
+ type,
583
+ slot: type === 'string'
584
+ ? arena.slot(ValueType.string, undefined, stringCap.value(dependency))
585
+ : arena.slot(ValueType[type]),
586
+ };
587
+ }));
588
+ }
589
+ const locals = new Set();
590
+ for (const body of bodies(app)) {
591
+ stringLocals(body, locals);
592
+ }
593
+ for (const state of app.state) {
594
+ if (state.kind === 'scalar' && state.worked) {
595
+ stringLocals(state.worked.rebuild, locals);
596
+ }
597
+ }
598
+ for (const name of locals) {
599
+ if (!slots.hoisted.has(name)) {
600
+ slots.stringLocals.set(name, arena.slot(ValueType.string, undefined, stringCap.local(name)));
601
+ }
602
+ }
603
+ // A native call's string result can be anything a write holds. A record's strings take a buffer each, one after
604
+ // another, as CALLNS names the first.
605
+ const nativeCalls = new Set();
606
+ stringNativeCalls(bodies(app), nativeCalls);
607
+ for (const call of nativeCalls) {
608
+ const buffers = call.import.results
609
+ .filter(type => type === 'string')
610
+ .map(() => arena.slot(ValueType.string, undefined, ENGINE_STRING_MAX.ER_TEXT_MAX));
611
+ slots.nativeStrings.set(call, buffers[0]);
612
+ }
613
+ const nodes = nodesOf(app.root);
614
+ // A <TextInput>'s onChangeText reads the input's text, through its handle.
615
+ const handles = new Map();
616
+ const readsInput = (node) => node.wiring.some(wire => wire.kind === 'event' && wire.event === 'ER_EVENT_CHANGE_TEXT');
617
+ // An updateVector call draws on the node its ref holds: the last one built with it.
618
+ const calls = [];
619
+ for (const body of bodies(app)) {
620
+ updateVectors(body, calls);
621
+ }
622
+ const drawnRefs = new Set(calls.map(call => call.node));
623
+ const refNodes = new Map();
624
+ for (const node of nodes) {
625
+ for (const wire of node.wiring) {
626
+ if (wire.kind === 'ref' && drawnRefs.has(wire.slot)) {
627
+ refNodes.set(wire.slot, node);
628
+ }
629
+ }
630
+ }
631
+ const drawnOn = new Set(refNodes.values());
632
+ const reached = (node) => isStateDriven(node) ||
633
+ isSetOnce(node) ||
634
+ readsInput(node) ||
635
+ stateDrivenVectorOf(node) !== null;
636
+ const { pools, branchings, places } = {
637
+ pools: [],
638
+ branchings: [],
639
+ places: new Map(),
640
+ };
641
+ planTree(app.root, null, { pools, branchings, places }, arena);
642
+ for (const placed of [...pools, ...branchings]) {
643
+ placed.anchors = anchorsOf(placed.after, pools, branchings);
644
+ }
645
+ // Rows and branches are built under their parent, before an anchor.
646
+ const builtUnder = new Set([...pools, ...branchings].flatMap(placed => [
647
+ placed.parent,
648
+ ...placed.anchors.flatMap(anchor => anchor.kind === 'node' ? [anchor.node] : []),
649
+ ]));
650
+ // A row's node keeps its handle in an array by the row, one array for each place in the row that needs one.
651
+ const rowHandles = new Map();
652
+ for (const pool of pools) {
653
+ const arrays = [];
654
+ const anchoring = pool.rows.length > 0 && builtUnder.has(firstNode(pool.rows[0]));
655
+ pool.rows.forEach((rowElement, row) => nodesOf(rowElement).forEach((node, place) => {
656
+ if (readsInput(node)) {
657
+ notYetAt('onChangeText in a list row', node.location);
658
+ }
659
+ if (drawnOn.has(node)) {
660
+ notYetAt('updateVector on a node in a list row', node.location);
661
+ }
662
+ // Every row's first node, when the first row's is an anchor, so the rows can still share a template.
663
+ if (reached(node) || (anchoring && place === 0)) {
664
+ arrays[place] ??= arena.slot(ValueType.node, 0, pool.list.capacity);
665
+ rowHandles.set(node, { array: arrays[place], row });
666
+ }
667
+ }));
668
+ }
669
+ // A branch's first node keeps its handle in its conditional's slot, which every branch of it shares.
670
+ for (const branching of branchings) {
671
+ for (const alternative of branching.alternatives) {
672
+ handles.set(firstNode(alternative), branching.root);
673
+ }
674
+ }
675
+ for (const node of nodes) {
676
+ if (drawnOn.has(node) && places.has(node)) {
677
+ const error = aotError('AOT: updateVector draws on a node a conditional builds and destroys', 'keep the node built and show it with visible={…} instead.');
678
+ locateError(error, node.location);
679
+ throw error;
680
+ }
681
+ if (!rowHandles.has(node) &&
682
+ !handles.has(node) &&
683
+ (reached(node) || builtUnder.has(node) || drawnOn.has(node))) {
684
+ handles.set(node, arena.slot(ValueType.node));
685
+ }
686
+ }
687
+ for (const [ref, node] of refNodes) {
688
+ slots.vectors.refNodes.set(ref, handles.get(node));
689
+ }
690
+ const inputText = nodes.some(readsInput)
691
+ ? arena.slot(ValueType.string, undefined, ENGINE_STRING_MAX.ER_TEXT_MAX)
692
+ : null;
693
+ // Each PanResponder's gesture state.
694
+ for (const pan of output.panResponders) {
695
+ slots.gestures.set(pan.statePrefix, {
696
+ granted: arena.slot(ValueType.bool),
697
+ baseDeltaX: arena.slot(ValueType.int),
698
+ baseDeltaY: arena.slot(ValueType.int),
699
+ x0: arena.slot(ValueType.int),
700
+ y0: arena.slot(ValueType.int),
701
+ });
702
+ }
703
+ const requestsUpdate = output.handlers.some(handler => handler.kind === 'callback'
704
+ ? handler.callback.updatesState
705
+ : handler.kind === 'panEvent' && !!handler.event.callback?.updatesState) ||
706
+ output.timerFunctions.some(timer => timer.callback.updatesState) ||
707
+ output.nativeEventHandlers.some(handler => handler.callback.updatesState) ||
708
+ output.mountEffects.some(mountUpdates) ||
709
+ output.dependencyEffects.some(setsState) ||
710
+ completionsOf(app).some(completion => completion.updatesState);
711
+ const requested = requestsUpdate
712
+ ? arena.track(arena.slot(ValueType.bool))
713
+ : null;
714
+ const hasEffects = output.dependencyEffects.length > 0 || output.mountEffects.length > 0;
715
+ const once = hasEffects ||
716
+ pools.length ||
717
+ nodes.some(node => isStateDriven(node) || isSetOnce(node) || stateDrivenVectorOf(node))
718
+ ? arena.track(arena.slot(ValueType.bool))
719
+ : null;
720
+ // The mount effects run each dep-driven effect first, so its checks wait for the last of them.
721
+ const checksQueued = output.dependencyEffects.length
722
+ ? arena.slot(ValueType.bool, 1)
723
+ : null;
724
+ // The first mount effect is queued by the first pass.
725
+ const mountNext = output.mountEffects.length
726
+ ? arena.slot(ValueType.int, 1)
727
+ : null;
728
+ if (output.timerFunctions.length) {
729
+ arena.timerTable(caps.maxTimers);
730
+ }
731
+ // A pass queues each dep-driven effect's check unless a batch is waiting to start, so the queue holds one waiting
732
+ // batch, the rest of the one running, and the next mount effect.
733
+ if (hasEffects) {
734
+ arena.eventQueue(2 * output.dependencyEffects.length + 1);
735
+ }
736
+ arena.layOut();
737
+ return {
738
+ slots,
739
+ handles,
740
+ rowHandles,
741
+ rows,
742
+ pools,
743
+ branchings,
744
+ places,
745
+ inputText,
746
+ requested,
747
+ once,
748
+ effects: { copies, checksQueued, mountNext },
749
+ };
750
+ }
751
+ /*----------------------------------------------------------------------------------------------------------------------
752
+ - Templates
753
+ ---------------------------------------------------------------------------------------------------------------------*/
754
+ /**
755
+ * A node's constant props as a prop set: its style, then a placeholder,
756
+ * text, and image known at compile time.
757
+ *
758
+ * @param node The node.
759
+ * @param lowering The program being lowered.
760
+ *
761
+ * @returns The set's entries.
762
+ */
763
+ function constantProps(node, lowering) {
764
+ const { tables } = lowering.slots;
765
+ const entries = node.constantProps.map(prop => constantPropEntry(prop.field, prop.value));
766
+ if (node.placeholder != null) {
767
+ entries.push(stringPropEntry('placeholder', tables.string(node.placeholder)));
768
+ }
769
+ const text = node.text ? constantText(node.text) : null;
770
+ if (text !== null) {
771
+ entries.push(stringPropEntry('text', tables.string(text)));
772
+ }
773
+ // The runtime only loads a package whose images are all in its own asset pack.
774
+ if (node.image?.kind === 'static') {
775
+ if (!lowering.images.has(node.image.name)) {
776
+ throw aotError(`AOT: the package has no image named "${node.image.name}"`, 'import the image file, so the build bakes it into the package.');
777
+ }
778
+ entries.push(stringPropEntry('image_name', tables.string(node.image.name)));
779
+ }
780
+ return entries;
781
+ }
782
+ /**
783
+ * The handler function an event on a node runs, made the first time. A handler bound to two events is one
784
+ * function per event, since a function's kind is the event it is entered with, and an onChangeText one per
785
+ * input, since it reads its own. Each row has its own handler; rows whose handlers have the same
786
+ * code share one function, so they can share a template.
787
+ *
788
+ * @param name The handler.
789
+ * @param eventName The event, an ER_EVENT_* name.
790
+ * @param node The node it is bound to.
791
+ * @param lowering The program being lowered.
792
+ * @param inRow Whether the node is in a list row.
793
+ *
794
+ * @returns The function's index.
795
+ */
796
+ function handlerFunction(name, eventName, node, lowering, inRow) {
797
+ // A PanResponder's handlers are wired as a responder, not by name.
798
+ const handler = lowering.app.output.handlers.find(candidate => candidate.kind !== 'panEvent' && candidate.name === name);
799
+ if (!handler || handler.kind === 'panEvent') {
800
+ throw new Error(`AOT internal: no handler "${name}"`);
801
+ }
802
+ // A press fade runs the app's own handler for the event after it, when it has one.
803
+ const then = handler.kind === 'pressFade'
804
+ ? handler.then
805
+ ? lowering.app.output.handlers.find(candidate => candidate.kind === 'callback' && candidate.name === handler.then)
806
+ : null
807
+ : handler;
808
+ if (then === undefined || (then && then.kind !== 'callback')) {
809
+ throw new Error(`AOT internal: no handler for "${name}"`);
810
+ }
811
+ const readsInput = eventName === 'ER_EVENT_CHANGE_TEXT';
812
+ const made = {
813
+ callback: then?.callback ?? { body: [], updatesState: false },
814
+ fade: handler.kind === 'pressFade' ? handler.fade : null,
815
+ event: ENGINE_VALUES.get(eventName),
816
+ name,
817
+ input: readsInput
818
+ ? { node: lowering.handles.get(node), text: lowering.inputText }
819
+ : undefined,
820
+ inRow,
821
+ };
822
+ // Compared by code alone, so where each handler is in the source doesn't keep two apart.
823
+ const key = inRow
824
+ ? `row ${JSON.stringify({ ...handlerBody({ ...made, index: NONE }, lowering), debug: undefined })}`
825
+ : `${name} ${eventName}${readsInput ? ` ${node.id}` : ''}`;
826
+ const existing = lowering.handlers.get(key);
827
+ if (existing) {
828
+ return existing.index;
829
+ }
830
+ const index = lowering.handlers.size;
831
+ lowering.handlers.set(key, { ...made, index });
832
+ return index;
833
+ }
834
+ /**
835
+ * A PanResponder's bindings: a handler for each of its events, then a query function for each predicate.
836
+ * Each function is made once, however many nodes spread the responder.
837
+ *
838
+ * @param pan The responder.
839
+ * @param lowering The program being lowered.
840
+ *
841
+ * @returns The bindings.
842
+ */
843
+ function responderBindings(pan, lowering) {
844
+ const made = (key, entry) => {
845
+ const existing = lowering.handlers.get(key);
846
+ if (existing) {
847
+ return existing.index;
848
+ }
849
+ const index = lowering.handlers.size;
850
+ lowering.handlers.set(key, { ...entry, index });
851
+ return index;
852
+ };
853
+ const common = { fade: null, input: undefined, inRow: false };
854
+ return [
855
+ ...pan.events.map(event => {
856
+ const kind = ENGINE_VALUES.get(event.event);
857
+ return {
858
+ kind: BindingKind.event,
859
+ event: kind,
860
+ target: made(`pan ${pan.functionPrefix} ${event.role}`, {
861
+ ...common,
862
+ callback: event.callback ?? { body: [], updatesState: false },
863
+ event: kind,
864
+ name: `${pan.name} ${event.role}`,
865
+ gesture: { statePrefix: pan.statePrefix, role: event.role },
866
+ }),
867
+ };
868
+ }),
869
+ ...pan.queries.map(query => {
870
+ const kind = ENGINE_VALUES.get(query.query);
871
+ return {
872
+ kind: BindingKind.query,
873
+ event: kind,
874
+ target: made(`pan ${pan.functionPrefix} query ${kind}`, {
875
+ ...common,
876
+ callback: { body: [], updatesState: false },
877
+ event: FunctionKind.query + kind,
878
+ name: `${pan.name} query`,
879
+ test: query.test,
880
+ }),
881
+ };
882
+ }),
883
+ ];
884
+ }
885
+ /**
886
+ * An element and everything under it as template nodes, each before its children. A conditional's branches are
887
+ * branch templates of their own, except in a list row, where all of them are built and the update shows the
888
+ * chosen one. A list's rows are row templates of their own. What a node needs that a package can't lower yet is
889
+ * refused at the node's element.
890
+ *
891
+ * @param element The element.
892
+ * @param lowering The program being lowered.
893
+ * @param nodes Collects the template nodes.
894
+ * @param inRow Whether the element is a list row's.
895
+ */
896
+ function templateNodes(element, lowering, nodes, inRow = false) {
897
+ if (element.kind === 'component') {
898
+ templateNodes(element.root, lowering, nodes, inRow);
899
+ return;
900
+ }
901
+ const { node } = element;
902
+ let children;
903
+ try {
904
+ const bindings = [];
905
+ for (const wire of node.wiring) {
906
+ if (wire.kind === 'bind') {
907
+ bindings.push(lowering.slots.animations.binding(wire.bind));
908
+ }
909
+ else if (wire.kind === 'event') {
910
+ bindings.push({
911
+ kind: BindingKind.event,
912
+ event: ENGINE_VALUES.get(wire.event),
913
+ target: handlerFunction(wire.handler, wire.event, node, lowering, inRow),
914
+ });
915
+ }
916
+ else if (wire.kind === 'responder') {
917
+ bindings.push(...responderBindings(wire.pan, lowering));
918
+ }
919
+ else if (wire.kind === 'vectorTables') {
920
+ // A drawing state drives is committed by the update instead, and a ref needs nothing itself.
921
+ const tape = lowering.slots.vectors.tableTape(wire.tables);
922
+ if (tape !== null) {
923
+ bindings.push({ kind: BindingKind.tape, event: 0, target: tape });
924
+ }
925
+ }
926
+ }
927
+ children = node.children.flatMap(child => child.kind === 'element'
928
+ ? [child.element]
929
+ : child.kind === 'conditional' && child.toggle
930
+ ? branchElements(child)
931
+ : []);
932
+ // A node the update sets starts with no props.
933
+ const handle = inRow
934
+ ? lowering.rowHandles.get(node)?.array
935
+ : lowering.handles.get(node);
936
+ nodes.push({
937
+ type: ENGINE_VALUES.get(node.type),
938
+ children: children.length,
939
+ props: isStateDriven(node) || isSetOnce(node)
940
+ ? NONE
941
+ : lowering.slots.tables.propSet(constantProps(node, lowering)),
942
+ handle: handle?.index ?? NONE,
943
+ bindings: bindings.length ? lowering.bindings.length : 0,
944
+ bindingCount: bindings.length,
945
+ });
946
+ lowering.bindings.push(...bindings);
947
+ }
948
+ catch (error) {
949
+ locateError(error, node.location);
950
+ throw error;
951
+ }
952
+ for (const child of children) {
953
+ templateNodes(child, lowering, nodes, inRow);
954
+ }
955
+ }
956
+ /**
957
+ * Each list row's template. Rows whose nodes and bindings are the same share one.
958
+ *
959
+ * @param lowering The program being lowered.
960
+ */
961
+ function rowTemplates(lowering) {
962
+ const made = new Map();
963
+ for (const pool of lowering.pools) {
964
+ pool.templates = pool.rows.map(row => {
965
+ const first = lowering.bindings.length;
966
+ const nodes = [];
967
+ templateNodes(row, lowering, nodes, true);
968
+ const key = JSON.stringify({
969
+ nodes: nodes.map(node => ({
970
+ ...node,
971
+ bindings: node.bindingCount ? node.bindings - first : 0,
972
+ })),
973
+ bindings: lowering.bindings.slice(first),
974
+ });
975
+ const existing = made.get(key);
976
+ if (existing !== undefined) {
977
+ lowering.bindings.length = first;
978
+ return existing;
979
+ }
980
+ // The root template is first, so a row template's index is its place after it.
981
+ const index = lowering.templates.push({ kind: TemplateKind.row, nodes });
982
+ made.set(key, index);
983
+ return index;
984
+ });
985
+ }
986
+ }
987
+ /**
988
+ * Each branch's template, for every conditional that builds its branches.
989
+ *
990
+ * @param lowering The program being lowered.
991
+ */
992
+ function branchTemplates(lowering) {
993
+ for (const branching of lowering.branchings) {
994
+ branching.templates = branching.alternatives.map(alternative => {
995
+ const nodes = [];
996
+ templateNodes(alternative, lowering, nodes);
997
+ // The root template is first, so a branch template's index is its place after it.
998
+ return lowering.templates.push({ kind: TemplateKind.branch, nodes });
999
+ });
1000
+ }
1001
+ }
1002
+ /**
1003
+ * The most nodes an element and everything under it hold at once: every row of a list, and the largest branch
1004
+ * of a conditional, or all of them in a list row.
1005
+ *
1006
+ * @param element The element.
1007
+ * @param counts How many a node counts for.
1008
+ *
1009
+ * @returns The nodes.
1010
+ */
1011
+ function mostBuilt(element, counts) {
1012
+ if (element.kind === 'component') {
1013
+ return mostBuilt(element.root, counts);
1014
+ }
1015
+ const sum = (elements) => elements.reduce((total, each) => total + mostBuilt(each, counts), 0);
1016
+ let total = counts(element.node);
1017
+ for (const child of element.node.children) {
1018
+ if (child.kind === 'element') {
1019
+ total += mostBuilt(child.element, counts);
1020
+ }
1021
+ else if (child.kind === 'pool') {
1022
+ total += sum(child.rows);
1023
+ }
1024
+ else if (child.toggle) {
1025
+ total += sum(branchElements(child));
1026
+ }
1027
+ else {
1028
+ total += Math.max(0, ...branchElements(child).map(branch => mostBuilt(branch, counts)));
1029
+ }
1030
+ }
1031
+ return total;
1032
+ }
1033
+ /*----------------------------------------------------------------------------------------------------------------------
1034
+ - Functions
1035
+ ---------------------------------------------------------------------------------------------------------------------*/
1036
+ /**
1037
+ * Sets a node's props again: its constant set, what state drives, its image and its text, then spans when it
1038
+ * has them and the update sets it once.
1039
+ *
1040
+ * @param codegen The update function's codegen.
1041
+ * @param node The node.
1042
+ * @param lowering The program being lowered.
1043
+ */
1044
+ function setNode(codegen, node, lowering) {
1045
+ const { builder } = codegen;
1046
+ const { tables } = lowering.slots;
1047
+ const spans = isSetOnce(node) ? node.spans : null;
1048
+ if (spans && spans.length > MAX_SPANS) {
1049
+ notYet(`more than ${MAX_SPANS} nested <Text> spans`);
1050
+ }
1051
+ // Span styles are props too.
1052
+ const entries = constantProps(node, lowering);
1053
+ spans?.forEach((span, index) => SPAN_FIELDS.forEach(field => entries.push(constantPropEntry(`spans[${index}].${field}`, span[field]))));
1054
+ builder.abx('PROPS', 0, tables.propSet(entries));
1055
+ for (const { field, value } of node.stateProps) {
1056
+ codegen.setProp(field, value);
1057
+ }
1058
+ if (node.image?.kind === 'value') {
1059
+ const image = node.image.value;
1060
+ codegen.scoped(() => builder.abx('PSETS', codegen.valueAs(image, 'string').index, abiProp('image_name').id));
1061
+ }
1062
+ if (node.text && constantText(node.text) === null) {
1063
+ const { parts } = node.text;
1064
+ codegen.scoped(() => {
1065
+ codegen.text(parts);
1066
+ builder.abc('FMTTEXT');
1067
+ });
1068
+ }
1069
+ spans?.forEach((span, index) => {
1070
+ builder.abx('FMTK', 0, tables.string(span.text));
1071
+ builder.abc('FMTSPAN', index);
1072
+ });
1073
+ if (spans) {
1074
+ builder.abc('SPANS', spans.length);
1075
+ }
1076
+ codegen.scoped(() => builder.abc('COMMIT', nodeHandle(codegen, node, lowering).index));
1077
+ }
1078
+ /**
1079
+ * A node's handle: from its slot, or a list row's from its handle array.
1080
+ *
1081
+ * @param codegen The function's codegen.
1082
+ * @param node The node.
1083
+ * @param lowering The program being lowered.
1084
+ *
1085
+ * @returns A node register.
1086
+ */
1087
+ function nodeHandle(codegen, node, lowering) {
1088
+ const { builder } = codegen;
1089
+ const handle = builder.register('node');
1090
+ const inRow = lowering.rowHandles.get(node);
1091
+ if (inRow) {
1092
+ builder.abc('GETNI', handle.index, codegen.load('int', inRow.row).index, 0, inRow.array.index);
1093
+ }
1094
+ else {
1095
+ builder.abx('GET64', handle.index, lowering.handles.get(node).index);
1096
+ }
1097
+ return handle;
1098
+ }
1099
+ /**
1100
+ * Builds under a parent, before the first anchor that is built: emits the BUILD for each node it may go before.
1101
+ *
1102
+ * @param codegen The update function's codegen.
1103
+ * @param parent The parent's handle.
1104
+ * @param anchors What it goes before.
1105
+ * @param lowering The program being lowered.
1106
+ * @param build Emits the BUILD, before a node.
1107
+ */
1108
+ function buildBefore(codegen, parent, anchors, lowering, build) {
1109
+ const { builder } = codegen;
1110
+ const done = builder.label();
1111
+ for (const anchor of anchors) {
1112
+ if (anchor.kind === 'node') {
1113
+ codegen.scoped(() => build(nodeHandle(codegen, anchor.node, lowering)));
1114
+ builder.place(done);
1115
+ return;
1116
+ }
1117
+ const absent = builder.label();
1118
+ codegen.scoped(() => {
1119
+ const { branching } = anchor;
1120
+ builder.branch('JF', absent, codegen.truthy(codegen.get(branching.built)));
1121
+ const before = builder.register('node');
1122
+ builder.abx('GET64', before.index, branching.root.index);
1123
+ build(before);
1124
+ builder.branch('JMP', done);
1125
+ });
1126
+ builder.place(absent);
1127
+ }
1128
+ // BUILD before the parent itself puts it last.
1129
+ build(parent);
1130
+ builder.place(done);
1131
+ }
1132
+ /**
1133
+ * Builds every row of a list under its parent, last row first, each before the row after it.
1134
+ *
1135
+ * @param codegen The update function's codegen.
1136
+ * @param pool The list's pool.
1137
+ * @param lowering The program being lowered.
1138
+ */
1139
+ function buildPool(codegen, pool, lowering) {
1140
+ const { builder } = codegen;
1141
+ codegen.scoped(() => {
1142
+ const parent = nodeHandle(codegen, pool.parent, lowering);
1143
+ const row = builder.register('int');
1144
+ const built = [builder.register('node'), builder.register('node')];
1145
+ const last = pool.templates.length - 1;
1146
+ for (let index = last; index >= 0; index--) {
1147
+ builder.abx('LOADI', row.index, index);
1148
+ const build = (before) => builder.abc('BUILD', built[index % 2].index, parent.index, before.index, pool.templates[index] | (row.index << 16));
1149
+ if (index === last) {
1150
+ buildBefore(codegen, parent, pool.anchors, lowering, build);
1151
+ }
1152
+ else {
1153
+ build(built[(index + 1) % 2]);
1154
+ }
1155
+ }
1156
+ });
1157
+ }
1158
+ /**
1159
+ * Runs `body` only while a branch is built; at the root, always.
1160
+ *
1161
+ * @param codegen The update function's codegen.
1162
+ * @param within The branch, or null.
1163
+ * @param body Emits what it guards.
1164
+ */
1165
+ function whileBuilt(codegen, within, body) {
1166
+ if (!within) {
1167
+ body();
1168
+ return;
1169
+ }
1170
+ const { builder } = codegen;
1171
+ const skip = builder.label();
1172
+ codegen.scoped(() => {
1173
+ builder.branch('JF', skip, codegen.same(codegen.get(within.branching.built), codegen.load('int', within.alternative)));
1174
+ body();
1175
+ });
1176
+ builder.place(skip);
1177
+ }
1178
+ /**
1179
+ * The branch a conditional's tests pick: its number, or 0 for one that builds nothing.
1180
+ *
1181
+ * @param codegen The function's codegen.
1182
+ * @param branching The conditional.
1183
+ *
1184
+ * @returns An int register.
1185
+ */
1186
+ function picked(codegen, branching) {
1187
+ const { builder } = codegen;
1188
+ const choice = builder.register('int');
1189
+ const pick = (branch) => {
1190
+ if (branch?.kind !== 'conditional') {
1191
+ builder.abx('LOADI', choice.index, branch ? branching.alternatives.indexOf(branch) + 1 : 0);
1192
+ return;
1193
+ }
1194
+ const otherwise = builder.label();
1195
+ const end = builder.label();
1196
+ codegen.scoped(() => builder.branch('JF', otherwise, codegen.condition(branch.test)));
1197
+ pick(branch.whenTrue);
1198
+ builder.branch('JMP', end);
1199
+ builder.place(otherwise);
1200
+ pick(branch.whenFalse);
1201
+ builder.place(end);
1202
+ };
1203
+ pick(branching.conditional);
1204
+ return choice;
1205
+ }
1206
+ /**
1207
+ * The state a conditional's tests read, those of the conditionals that are its branches included.
1208
+ *
1209
+ * @param conditional The conditional.
1210
+ *
1211
+ * @returns Its reads.
1212
+ */
1213
+ function conditionalReads(conditional) {
1214
+ const reads = new Set();
1215
+ const tests = [
1216
+ expressionReads(conditional.test),
1217
+ ...[conditional.whenTrue, conditional.whenFalse].map(branch => branch?.kind === 'conditional' ? conditionalReads(branch) : new Set()),
1218
+ ];
1219
+ for (const found of tests) {
1220
+ if (!found) {
1221
+ return null;
1222
+ }
1223
+ found.forEach(state => reads.add(state));
1224
+ }
1225
+ return reads;
1226
+ }
1227
+ /**
1228
+ * The dirty bits of a set of slots, as a mask per dirty word.
1229
+ *
1230
+ * @param slots The slots.
1231
+ *
1232
+ * @returns Each word's mask.
1233
+ */
1234
+ function dirtyMasks(slots) {
1235
+ const words = new Map();
1236
+ for (const slot of slots) {
1237
+ const word = slot.dirtyBit >> 5;
1238
+ words.set(word, ((words.get(word) ?? 0) | (1 << (slot.dirtyBit & 31))) >>> 0);
1239
+ }
1240
+ return words;
1241
+ }
1242
+ /**
1243
+ * Runs `body` only when one of a set of dirty bits is set in this update pass.
1244
+ *
1245
+ * @param builder The update function.
1246
+ * @param slots The slots whose bits guard it.
1247
+ * @param body Emits what it guards.
1248
+ */
1249
+ function whenDirty(builder, slots, body) {
1250
+ const run = builder.label();
1251
+ const skip = builder.label();
1252
+ for (const [word, mask] of dirtyMasks(slots)) {
1253
+ builder.branchIfDirty(word, mask, run);
1254
+ }
1255
+ builder.branch('JMP', skip);
1256
+ builder.place(run);
1257
+ body();
1258
+ builder.place(skip);
1259
+ }
1260
+ /**
1261
+ * Writes a constant to a 4-byte slot.
1262
+ *
1263
+ * @param codegen The function's codegen.
1264
+ * @param slot The slot.
1265
+ * @param value The value.
1266
+ */
1267
+ function setConstant(codegen, slot, value) {
1268
+ codegen.scoped(() => codegen.builder.abx('SET32', codegen.load(slot.type === ValueType.bool ? 'bool' : 'int', value).index, slot.index));
1269
+ }
1270
+ /**
1271
+ * The update function: the branches a state change no longer picks destroyed, what it sets again, each node when
1272
+ * a state it reads changed, and the nodes set once in the first pass; then the branches picked built, each with
1273
+ * all of its props; then the effects it runs, queued.
1274
+ *
1275
+ * @param lowering The program being lowered.
1276
+ *
1277
+ * @returns The function, or null when nothing needs it.
1278
+ */
1279
+ function updateFunction(lowering) {
1280
+ const { output } = lowering.app;
1281
+ const nodes = nodesOf(lowering.app.root);
1282
+ const updated = nodes.filter(isStateDriven);
1283
+ const setOnce = nodes.filter(isSetOnce);
1284
+ const drawings = nodes.flatMap(node => {
1285
+ const vector = stateDrivenVectorOf(node);
1286
+ return vector ? [{ node, vector }] : [];
1287
+ });
1288
+ const derivedLists = lowering.app.state.flatMap(state => state.kind === 'list' && state.derived ? [state] : []);
1289
+ const workedValues = lowering.app.state.flatMap(state => state.kind === 'scalar' && state.worked ? [state] : []);
1290
+ if (!derivedLists.length &&
1291
+ !workedValues.length &&
1292
+ !updated.length &&
1293
+ !setOnce.length &&
1294
+ !drawings.length &&
1295
+ !lowering.branchings.length &&
1296
+ !output.dependencyEffects.length &&
1297
+ !output.mountEffects.length) {
1298
+ return null;
1299
+ }
1300
+ const builder = new FunctionBuilder(FunctionKind.update, 'the update');
1301
+ const codegen = new Codegen(builder, lowering.slots);
1302
+ const { mountNext } = lowering.effects;
1303
+ const located = (node, lower) => {
1304
+ builder.at(node.location);
1305
+ try {
1306
+ lower();
1307
+ }
1308
+ catch (error) {
1309
+ locateError(error, node.location);
1310
+ throw error;
1311
+ }
1312
+ };
1313
+ const draw = (node, vector) => located(node, () => commitDrawing(codegen, vector, lowering.slots.vectors, () => nodeHandle(codegen, node, lowering)));
1314
+ // Set again when a state it reads changed; what reads something no state write flags (a ref, the clock) is
1315
+ // set on every pass.
1316
+ const whenRead = (reads, lower) => {
1317
+ const bits = reads
1318
+ ? [...reads].map(state => stateSlotOf(state, lowering.slots))
1319
+ : [];
1320
+ if (bits.length && bits.every(slot => slot.flags & SlotFlag.tracked)) {
1321
+ whenDirty(builder, bits, lower);
1322
+ }
1323
+ else {
1324
+ lower();
1325
+ }
1326
+ };
1327
+ const end = builder.label();
1328
+ // The lists filtered or sorted in render, and the values memos and helpers loop for, worked out first, each after
1329
+ // what it reads, as what reads them counts what they read.
1330
+ const rebuilds = [
1331
+ ...derivedLists.map(list => ({
1332
+ order: list.derived.order ?? 0,
1333
+ reads: () => listReads(list),
1334
+ statements: list.derived.rebuild,
1335
+ })),
1336
+ ...workedValues.map(value => ({
1337
+ order: value.worked.order,
1338
+ reads: () => workedReads(value),
1339
+ statements: value.worked.rebuild,
1340
+ })),
1341
+ ];
1342
+ if (workedValues.length)
1343
+ rebuilds.sort((a, b) => a.order - b.order);
1344
+ for (const { reads, statements } of rebuilds) {
1345
+ whenRead(reads(), () => codegen.scoped(() => codegen.statements(statements)));
1346
+ }
1347
+ // The branches a test no longer picks, destroyed before anything is built, with the conditionals in them.
1348
+ const { branchings, places } = lowering;
1349
+ for (const branching of branchings) {
1350
+ codegen.scoped(() => {
1351
+ const kept = builder.label();
1352
+ const built = codegen.get(branching.built);
1353
+ builder.branch('JF', kept, codegen.truthy(built));
1354
+ whenRead(conditionalReads(branching.conditional), () => codegen.scoped(() => {
1355
+ builder.branch('JT', kept, codegen.same(picked(codegen, branching), built));
1356
+ const root = builder.register('node');
1357
+ builder.abx('GET64', root.index, branching.root.index);
1358
+ builder.abc('DESTROY', root.index);
1359
+ for (const each of [branching, ...branching.nested]) {
1360
+ setConstant(codegen, each.built, 0);
1361
+ }
1362
+ }));
1363
+ builder.place(kept);
1364
+ });
1365
+ }
1366
+ // The rows, the props that read only boot values, and the drawings that do, built once, outside the branches.
1367
+ const atRoot = (node) => !places.has(node);
1368
+ const rootPools = lowering.pools.filter(pool => !pool.within);
1369
+ const rootSetOnce = setOnce.filter(atRoot);
1370
+ const builtOnce = drawings.filter(({ node }) => !updatedVectorOf(node) && atRoot(node));
1371
+ if (rootSetOnce.length || rootPools.length || builtOnce.length) {
1372
+ whenDirty(builder, [lowering.once], () => {
1373
+ rootPools.forEach(pool => buildPool(codegen, pool, lowering));
1374
+ rootSetOnce.forEach(node => located(node, () => setNode(codegen, node, lowering)));
1375
+ builtOnce.forEach(({ node, vector }) => draw(node, vector));
1376
+ });
1377
+ }
1378
+ // The nodes, then the drawings, each only while its branch is built.
1379
+ for (const node of updated) {
1380
+ located(node, () => whenRead(nodeReads(node), () => whileBuilt(codegen, places.get(node), () => setNode(codegen, node, lowering))));
1381
+ }
1382
+ for (const { node, vector } of drawings) {
1383
+ if (updatedVectorOf(node)) {
1384
+ whenRead(vectorReads(vector), () => whileBuilt(codegen, places.get(node), () => draw(node, vector)));
1385
+ }
1386
+ }
1387
+ // The branches picked that aren't built, outer ones first: each built with its rows, then all of its props.
1388
+ for (const branching of branchings) {
1389
+ const skip = builder.label();
1390
+ whileBuilt(codegen, branching.within, () => codegen.scoped(() => {
1391
+ builder.branch('JT', skip, codegen.truthy(codegen.get(branching.built)));
1392
+ const choice = picked(codegen, branching);
1393
+ branching.alternatives.forEach((_, place) => {
1394
+ const alternative = place + 1;
1395
+ const other = builder.label();
1396
+ codegen.scoped(() => {
1397
+ builder.branch('JF', other, codegen.same(choice, codegen.load('int', alternative)));
1398
+ const parent = nodeHandle(codegen, branching.parent, lowering);
1399
+ const root = builder.register('node');
1400
+ buildBefore(codegen, parent, branching.anchors, lowering, before => builder.abc('BUILD', root.index, parent.index, before.index, branching.templates[place] | (NO_REGISTER << 16)));
1401
+ setConstant(codegen, branching.built, alternative);
1402
+ const inside = (within) => within?.branching === branching &&
1403
+ within.alternative === alternative;
1404
+ lowering.pools
1405
+ .filter(pool => inside(pool.within))
1406
+ .forEach(pool => buildPool(codegen, pool, lowering));
1407
+ nodes
1408
+ .filter(node => inside(places.get(node)) &&
1409
+ (isStateDriven(node) || isSetOnce(node)))
1410
+ .forEach(node => located(node, () => setNode(codegen, node, lowering)));
1411
+ drawings
1412
+ .filter(({ node }) => inside(places.get(node)))
1413
+ .forEach(({ node, vector }) => draw(node, vector));
1414
+ builder.branch('JMP', skip);
1415
+ });
1416
+ builder.place(other);
1417
+ });
1418
+ }));
1419
+ builder.place(skip);
1420
+ }
1421
+ // Each dep-driven effect checks its deps when it runs, each in turn. A batch already waiting sees what this pass
1422
+ // shows, so another isn't queued.
1423
+ const { checksQueued } = lowering.effects;
1424
+ if (checksQueued) {
1425
+ codegen.scoped(() => {
1426
+ const skip = builder.label();
1427
+ const waiting = builder.register('bool');
1428
+ builder.abx('GET32', waiting.index, checksQueued.index);
1429
+ builder.branch('JT', skip, waiting);
1430
+ setConstant(codegen, checksQueued, 1);
1431
+ for (const check of lowering.effectFunctions.checks) {
1432
+ builder.abx('EFFECT', 0, check);
1433
+ }
1434
+ builder.place(skip);
1435
+ });
1436
+ }
1437
+ // The first mount effect, then each one after a mount effect that set state.
1438
+ if (mountNext) {
1439
+ const { mounts } = lowering.effectFunctions;
1440
+ const queued = output.mountEffects.flatMap((_, index) => index === 0 || mountUpdates(output.mountEffects[index - 1])
1441
+ ? [index]
1442
+ : []);
1443
+ for (const index of queued) {
1444
+ codegen.scoped(() => {
1445
+ const skip = builder.label();
1446
+ const next = builder.register('int');
1447
+ const isNext = builder.register('bool');
1448
+ builder.abx('GET32', next.index, mountNext.index);
1449
+ builder.abc('EQ', isNext.index, next.index, codegen.load('int', index + 1).index);
1450
+ builder.branch('JF', skip, isNext);
1451
+ builder.abx('EFFECT', 0, mounts[index]);
1452
+ builder.place(skip);
1453
+ });
1454
+ }
1455
+ setConstant(codegen, mountNext, 0);
1456
+ }
1457
+ builder.place(end);
1458
+ return builder.finish();
1459
+ }
1460
+ /**
1461
+ * Toggles the request bit, so the update runs after a function that set state, even when no value changed.
1462
+ *
1463
+ * @param codegen The function's codegen.
1464
+ * @param lowering The program being lowered.
1465
+ */
1466
+ function requestUpdate(codegen, lowering) {
1467
+ const { requested } = lowering;
1468
+ if (!requested) {
1469
+ return;
1470
+ }
1471
+ const { builder } = codegen;
1472
+ codegen.scoped(() => {
1473
+ const flag = builder.register('bool');
1474
+ builder.abx('GET32', flag.index, requested.index);
1475
+ builder.abc('NOT', flag.index, flag.index);
1476
+ builder.abx('SET32', flag.index, requested.index);
1477
+ });
1478
+ }
1479
+ /**
1480
+ * A handler's function.
1481
+ *
1482
+ * @param handler The handler.
1483
+ * @param lowering The program being lowered.
1484
+ *
1485
+ * @returns The function.
1486
+ */
1487
+ function handlerBody(handler, lowering) {
1488
+ const builder = new FunctionBuilder(handler.event, `handler ${handler.name}`);
1489
+ // A row's handler is entered with its row, in its first register.
1490
+ const row = handler.inRow ? builder.reserved('int') : undefined;
1491
+ const codegen = new Codegen(builder, lowering.slots, {
1492
+ input: handler.input,
1493
+ row,
1494
+ });
1495
+ if (handler.test) {
1496
+ return builder.finish(0, codegen.condition(handler.test));
1497
+ }
1498
+ if (handler.fade) {
1499
+ startPressFade(codegen, handler.fade, lowering.slots.animations);
1500
+ }
1501
+ const end = builder.label();
1502
+ if (handler.gesture) {
1503
+ keepGesture(codegen, handler.gesture, 'before', end, lowering);
1504
+ }
1505
+ codegen.statements(handler.callback.body);
1506
+ if (handler.callback.updatesState) {
1507
+ requestUpdate(codegen, lowering);
1508
+ }
1509
+ if (handler.gesture) {
1510
+ keepGesture(codegen, handler.gesture, 'after', end, lowering);
1511
+ }
1512
+ builder.place(end);
1513
+ return builder.finish(row ? 1 : 0);
1514
+ }
1515
+ /**
1516
+ * What a PanResponder event's handler keeps of the gesture around the app's callback: the grant
1517
+ * anchors it, unless it is already granted; release and terminate clear it after the callback; those and move
1518
+ * do nothing unless it is granted.
1519
+ *
1520
+ * @param codegen The handler's codegen.
1521
+ * @param gesture The responder's gesture state, and the handler's role.
1522
+ * @param when Before the callback, or after it.
1523
+ * @param end The end of the handler, where it returns.
1524
+ * @param lowering The program being lowered.
1525
+ */
1526
+ function keepGesture(codegen, gesture, when, end, lowering) {
1527
+ const { builder } = codegen;
1528
+ const slots = lowering.slots.gestures.get(gesture.statePrefix);
1529
+ const { role } = gesture;
1530
+ codegen.scoped(() => {
1531
+ if (when === 'before' && role !== 'reject') {
1532
+ const granted = codegen.get(slots.granted);
1533
+ builder.branch(role === 'grant' ? 'JT' : 'JF', end, granted);
1534
+ }
1535
+ if (when === 'before' && role === 'grant') {
1536
+ codegen.set(slots.granted, codegen.load('bool', 1));
1537
+ const fields = [
1538
+ [slots.baseDeltaX, EventField.dx],
1539
+ [slots.baseDeltaY, EventField.dy],
1540
+ [slots.x0, EventField.x],
1541
+ [slots.y0, EventField.y],
1542
+ ];
1543
+ for (const [slot, field] of fields) {
1544
+ const value = builder.register('int');
1545
+ builder.abc('EVT', value.index, field);
1546
+ codegen.set(slot, value);
1547
+ }
1548
+ }
1549
+ if (when === 'after' && (role === 'release' || role === 'terminate')) {
1550
+ codegen.set(slots.granted, codegen.load('bool', 0));
1551
+ const zero = codegen.load('int', 0);
1552
+ codegen.set(slots.baseDeltaX, zero);
1553
+ codegen.set(slots.baseDeltaY, zero);
1554
+ }
1555
+ });
1556
+ }
1557
+ /**
1558
+ * A setTimeout or setInterval callback's function.
1559
+ *
1560
+ * @param name The callback's name.
1561
+ * @param callback The callback.
1562
+ * @param lowering The program being lowered.
1563
+ *
1564
+ * @returns The function.
1565
+ */
1566
+ function timerBody(name, callback, lowering) {
1567
+ const builder = new FunctionBuilder(FunctionKind.timer, `timer ${name}`);
1568
+ const codegen = new Codegen(builder, lowering.slots);
1569
+ codegen.statements(callback.body);
1570
+ if (callback.updatesState) {
1571
+ requestUpdate(codegen, lowering);
1572
+ }
1573
+ return builder.finish();
1574
+ }
1575
+ /**
1576
+ * The handlers of each native event the app subscribes to, in the order they lowered.
1577
+ *
1578
+ * @param handlers Every useNativeEvent's handler.
1579
+ *
1580
+ * @returns Them, grouped by event.
1581
+ */
1582
+ function byEvent(handlers) {
1583
+ const groups = new Map();
1584
+ for (const handler of handlers) {
1585
+ const { name, version, signature } = handler.event;
1586
+ const key = `${name} ${version} ${signature}`;
1587
+ groups.set(key, [...(groups.get(key) ?? []), handler]);
1588
+ }
1589
+ return [...groups.values()];
1590
+ }
1591
+ /**
1592
+ * A native event's function: entered with its values, it runs each subscriber whose component is mounted. Whether
1593
+ * each one is mounted is read before any of them runs, as Flow A calls the subscribers it had when the event came.
1594
+ *
1595
+ * @param handlers The event's subscribers.
1596
+ * @param lowering The program being lowered.
1597
+ *
1598
+ * @returns The function.
1599
+ */
1600
+ function nativeEventBody(handlers, lowering) {
1601
+ const { event } = handlers[0];
1602
+ const builder = new FunctionBuilder(FunctionKind.nativeEvent, `native event ${event.name}`);
1603
+ // The event's values from register 0, laid out as the runtime enters the function: an int64 on an even register.
1604
+ const values = event.params.map(type => builder.reserved(type));
1605
+ const last = values.at(-1);
1606
+ const parameterCells = last
1607
+ ? last.index + (last.type === 'int64' ? 2 : 1)
1608
+ : 0;
1609
+ const codegenOf = (handler) => new Codegen(builder, lowering.slots, {
1610
+ values: new Map(handler.values.map((name, position) => [name, values[position]])),
1611
+ });
1612
+ const mounted = handlers.map(handler => {
1613
+ if (!handler.mounted) {
1614
+ return null;
1615
+ }
1616
+ const test = handler.mounted;
1617
+ const kept = builder.reserved('bool');
1618
+ const codegen = codegenOf(handler);
1619
+ codegen.scoped(() => builder.abc('MOVE', kept.index, codegen.condition(test).index));
1620
+ return kept;
1621
+ });
1622
+ handlers.forEach((handler, index) => {
1623
+ const skip = builder.label();
1624
+ if (mounted[index]) {
1625
+ builder.branch('JF', skip, mounted[index]);
1626
+ }
1627
+ codegenOf(handler).statements(handler.callback.body);
1628
+ builder.place(skip);
1629
+ });
1630
+ if (handlers.some(handler => handler.callback.updatesState)) {
1631
+ requestUpdate(codegenOf(handlers[0]), lowering);
1632
+ }
1633
+ return builder.finish(parameterCells);
1634
+ }
1635
+ /**
1636
+ * An animation completion's helper: entered with what it was passed, which the body reads as `finished`.
1637
+ *
1638
+ * @param completion The completion.
1639
+ * @param lowering The program being lowered.
1640
+ *
1641
+ * @returns The function.
1642
+ */
1643
+ function completionBody(completion, lowering) {
1644
+ const builder = new FunctionBuilder(FunctionKind.helper, `completion ${completion.name}`);
1645
+ const finished = builder.reserved('bool');
1646
+ const codegen = new Codegen(builder, lowering.slots, { finished });
1647
+ codegen.statements(completion.body);
1648
+ if (completion.updatesState) {
1649
+ requestUpdate(codegen, lowering);
1650
+ }
1651
+ return builder.finish(1);
1652
+ }
1653
+ /**
1654
+ * The register-stack cells each function's deepest call path takes, its own frame included, as the runtime's
1655
+ * verifier works it out. A function only calls later ones.
1656
+ *
1657
+ * @param functions The functions.
1658
+ *
1659
+ * @returns The deepest.
1660
+ */
1661
+ function stackCells(functions) {
1662
+ const depths = [];
1663
+ for (let index = functions.length - 1; index >= 0; index--) {
1664
+ const { code, types } = functions[index];
1665
+ let deepest = 0;
1666
+ for (let at = 0; at < code.length; at += wordsOf(code[at])) {
1667
+ if ((code[at] & 0xff) === OP.CALL.code) {
1668
+ deepest = Math.max(deepest, depths[code[at] >>> 16]);
1669
+ }
1670
+ }
1671
+ depths[index] = FRAME_CELLS + types.length + deepest;
1672
+ }
1673
+ return Math.max(0, ...depths);
1674
+ }
1675
+ /**
1676
+ * How many of some instructions a function has.
1677
+ *
1678
+ * @param programFunction The function.
1679
+ * @param names The opcodes.
1680
+ *
1681
+ * @returns The count.
1682
+ */
1683
+ function countOps(programFunction, names) {
1684
+ const codes = new Set(names.map(name => OP[name].code));
1685
+ let count = 0;
1686
+ for (let at = 0; at < programFunction.code.length; at += wordsOf(programFunction.code[at])) {
1687
+ count += codes.has(programFunction.code[at] & 0xff) ? 1 : 0;
1688
+ }
1689
+ return count;
1690
+ }
1691
+ /**
1692
+ * An instruction's length, from its first word.
1693
+ *
1694
+ * @param word The word.
1695
+ *
1696
+ * @returns Its length in words.
1697
+ */
1698
+ const wordsOf = (word) => Object.values(OP).find(opcode => opcode.code === (word & 0xff)).words;
1699
+ /**
1700
+ * A dep-driven effect's run: the last run's cleanup, if that run reached it, then the body.
1701
+ *
1702
+ * @param effect The effect.
1703
+ * @param codegen The function's codegen.
1704
+ * @param lowering The program being lowered.
1705
+ */
1706
+ function runEffect(effect, codegen, lowering) {
1707
+ const { builder } = codegen;
1708
+ if (effect.hasCleanup) {
1709
+ const armed = lowering.slots.armed.get(armedFlag(effect.id));
1710
+ const skip = builder.label();
1711
+ codegen.scoped(() => {
1712
+ const flag = builder.register('bool');
1713
+ builder.abx('GET32', flag.index, armed.index);
1714
+ builder.branch('JF', skip, flag);
1715
+ });
1716
+ setConstant(codegen, armed, 0);
1717
+ codegen.body(effect.cleanup ?? []);
1718
+ builder.place(skip);
1719
+ }
1720
+ codegen.body(effect.body);
1721
+ }
1722
+ /**
1723
+ * The function a dep-driven effect runs in after an update pass: it copies each dep that changed,
1724
+ * and runs the effect if one did.
1725
+ *
1726
+ * @param effect The effect.
1727
+ * @param lowering The program being lowered.
1728
+ *
1729
+ * @returns The function.
1730
+ */
1731
+ function checkedEffect(effect, lowering) {
1732
+ const builder = new FunctionBuilder(FunctionKind.effect, `effect ${effect.id}`);
1733
+ const end = builder.label();
1734
+ // An early `return` still ends at the request.
1735
+ const ran = builder.label();
1736
+ const codegen = new Codegen(builder, lowering.slots, { onReturn: ran });
1737
+ const copies = lowering.effects.copies.get(effect);
1738
+ // The batch has started, so a write from here on needs one of its own.
1739
+ if (effect === lowering.app.output.dependencyEffects[0]) {
1740
+ setConstant(codegen, lowering.effects.checksQueued, 0);
1741
+ }
1742
+ const changed = builder.register('bool');
1743
+ builder.abx('LOADI', changed.index, 0);
1744
+ effect.dependencies.forEach((dependency, index) => {
1745
+ const { slot, type } = copies[index];
1746
+ codegen.scoped(() => {
1747
+ const value = codegen.valueAs(dependency, type);
1748
+ const same = builder.label();
1749
+ builder.branch('JT', same, codegen.same(value, codegen.get(slot)));
1750
+ codegen.set(slot, value);
1751
+ builder.abx('LOADI', changed.index, 1);
1752
+ builder.place(same);
1753
+ });
1754
+ });
1755
+ builder.branch('JF', end, changed);
1756
+ runEffect(effect, codegen, lowering);
1757
+ builder.place(ran);
1758
+ if (setsState(effect)) {
1759
+ requestUpdate(codegen, lowering);
1760
+ }
1761
+ builder.place(end);
1762
+ return builder.finish();
1763
+ }
1764
+ /**
1765
+ * The function a mount effect runs in, after the first update. One that set
1766
+ * state has the next pass queue the mount effect after it; any other queues it itself.
1767
+ *
1768
+ * @param index The mount effect's place in the order.
1769
+ * @param lowering The program being lowered.
1770
+ *
1771
+ * @returns The function.
1772
+ */
1773
+ function mountEffect(index, lowering) {
1774
+ const { output } = lowering.app;
1775
+ const mount = output.mountEffects[index];
1776
+ const builder = new FunctionBuilder(FunctionKind.effect, `mount effect ${index}`);
1777
+ const end = builder.label();
1778
+ const codegen = new Codegen(builder, lowering.slots, { onReturn: end });
1779
+ switch (mount.kind) {
1780
+ case 'inline':
1781
+ codegen.statements(mount.callback.body);
1782
+ break;
1783
+ case 'call': {
1784
+ const called = output.effectFunctions.find(effectFunction => effectFunction.kind === 'mount' && effectFunction.name === mount.name);
1785
+ codegen.statements(called?.kind === 'mount' ? called.body : []);
1786
+ break;
1787
+ }
1788
+ case 'depEffect':
1789
+ runEffect(mount.effect, codegen, lowering);
1790
+ break;
1791
+ }
1792
+ builder.place(end);
1793
+ // A dep-driven effect keeps a copy of each dep, taken after it ran.
1794
+ if (mount.kind === 'depEffect') {
1795
+ const copies = lowering.effects.copies.get(mount.effect);
1796
+ mount.effect.dependencies.forEach((dependency, dependencyIndex) => codegen.scoped(() => codegen.set(copies[dependencyIndex].slot, codegen.valueAs(dependency, copies[dependencyIndex].type))));
1797
+ }
1798
+ const hasNext = index + 1 < output.mountEffects.length;
1799
+ if (mountUpdates(mount)) {
1800
+ requestUpdate(codegen, lowering);
1801
+ if (hasNext) {
1802
+ setConstant(codegen, lowering.effects.mountNext, index + 2);
1803
+ }
1804
+ }
1805
+ else if (hasNext) {
1806
+ builder.abx('EFFECT', 0, lowering.effectFunctions.mounts[index + 1]);
1807
+ }
1808
+ // After the last, the dep-driven effects check what the mount effects changed.
1809
+ if (!hasNext) {
1810
+ for (const check of lowering.effectFunctions.checks) {
1811
+ builder.abx('EFFECT', 0, check);
1812
+ }
1813
+ }
1814
+ return builder.finish();
1815
+ }
1816
+ /**
1817
+ * Appends a list's first items: a missing field is 0 or "", and a whole
1818
+ * number field is the value rounded.
1819
+ *
1820
+ * @param list The list.
1821
+ * @param codegen The boot function's codegen.
1822
+ * @param lowering The program being lowered.
1823
+ */
1824
+ function appendInitialItems(list, codegen, lowering) {
1825
+ const { builder } = codegen;
1826
+ const entries = rowEntries(list.struct);
1827
+ for (const item of list.items) {
1828
+ codegen.scoped(() => {
1829
+ const row = builder.consecutive(entries.map(({ field, presence }) => presence ? 'bool' : field.kind === 'string' ? 'string' : field.kind));
1830
+ entries.forEach(({ field, presence }, index) => {
1831
+ const { present, value } = itemValueAt(item, field);
1832
+ if (field.kind === 'string' && !presence) {
1833
+ builder.abx('LOADS', row[index].index, lowering.slots.tables.string(present ? String(value) : ''));
1834
+ return;
1835
+ }
1836
+ const number = presence || field.kind === 'bool'
1837
+ ? Number(presence ? present : !!value)
1838
+ : Number(value) || 0;
1839
+ const kind = presence
1840
+ ? 'bool'
1841
+ : field.kind;
1842
+ codegen.scoped(() => builder.abc('MOVE', row[index].index, codegen.load(kind, kind === 'float' ? number : Math.round(number))
1843
+ .index));
1844
+ });
1845
+ builder.abx('APPEND', row[0].index, lowering.slots.lists.get(list).slot.index);
1846
+ });
1847
+ }
1848
+ }
1849
+ /**
1850
+ * The boot function: the values worked out from the panel size, in double precision, and
1851
+ * each list's first items.
1852
+ *
1853
+ * @param bootSlots The values.
1854
+ * @param lowering The program being lowered.
1855
+ *
1856
+ * @returns The function, or null when the app has none.
1857
+ */
1858
+ function bootFunction(bootSlots, lowering) {
1859
+ const lists = lowering.app.state.filter((state) => state.kind === 'list' && state.items.length > 0);
1860
+ // A slot read only by a state's start is among bootSlots.
1861
+ if (!bootSlots.length && !lists.length) {
1862
+ return null;
1863
+ }
1864
+ const builder = new FunctionBuilder(FunctionKind.boot, 'the boot values');
1865
+ const codegen = new Codegen(builder, lowering.slots, { inDoubles: true });
1866
+ for (const list of lists) {
1867
+ appendInitialItems(list, codegen, lowering);
1868
+ }
1869
+ for (const bootSlot of bootSlots) {
1870
+ const slot = lowering.slots.boot.get(bootSlot);
1871
+ const { initializer } = bootSlot;
1872
+ codegen.scoped(() => {
1873
+ if (initializer.kind === 'screen') {
1874
+ const size = builder.register('int');
1875
+ builder.abx('SCREEN', size.index, initializer.dimension === 'width' ? 0 : 1);
1876
+ codegen.set(slot, size);
1877
+ }
1878
+ else if (initializer.kind === 'native') {
1879
+ const available = builder.register('bool');
1880
+ builder.abx('AVAIL', available.index, initializer.module);
1881
+ codegen.set(slot, available);
1882
+ }
1883
+ else {
1884
+ codegen.set(slot, codegen.value(initializer.expression));
1885
+ }
1886
+ });
1887
+ }
1888
+ // A state that starts at a value worked out at boot, after every value it can read.
1889
+ for (const state of lowering.app.state) {
1890
+ if (state.kind !== 'scalar' || !state.bootInitial)
1891
+ continue;
1892
+ const { bootInitial } = state;
1893
+ codegen.scoped(() => codegen.set(lowering.slots.states.get(state), codegen.value({
1894
+ kind: 'boot',
1895
+ slot: bootInitial,
1896
+ type: bootInitial.type,
1897
+ })));
1898
+ }
1899
+ return builder.finish();
1900
+ }
1901
+ /**
1902
+ * The keyboard table: setKeyboardConfig's look and layout, each size and key field cut to the bytes the engine's
1903
+ * ERKeyboardConfig keeps it in.
1904
+ *
1905
+ * @param keyboard The keyboard.
1906
+ * @param tables The program's tables.
1907
+ *
1908
+ * @returns The table.
1909
+ */
1910
+ function keyboardTable(keyboard, tables) {
1911
+ const byte = (value) => (value ?? 0) & 0xff;
1912
+ const string = (text) => text == null ? NONE : tables.string(text);
1913
+ return {
1914
+ layers: (keyboard.layers ?? []).map(layer => layer.map(row => row.map(key => ({
1915
+ label: string(key.label),
1916
+ text: string(key.text),
1917
+ type: ENGINE_VALUES.get(KEY_TYPES[key.kind]),
1918
+ layer: byte(key.layer),
1919
+ span: byte(key.span),
1920
+ highlight: byte(key.highlightLayer ?? NEVER_HIGHLIGHTED),
1921
+ })))),
1922
+ rowHeight: (keyboard.rowHeight ?? 0) & 0xffff,
1923
+ gridColumns: byte(keyboard.gridColumns),
1924
+ keyGap: byte(keyboard.keyGap),
1925
+ keyRadius: byte(keyboard.keyRadius),
1926
+ fontSize: byte(keyboard.fontSize),
1927
+ panelColor: keyboard.panelColor ?? 0,
1928
+ keyColor: keyboard.keyColor ?? 0,
1929
+ keyActiveColor: keyboard.keyActiveColor ?? 0,
1930
+ labelColor: keyboard.labelColor ?? 0,
1931
+ };
1932
+ }
1933
+ /*----------------------------------------------------------------------------------------------------------------------
1934
+ - Program
1935
+ ---------------------------------------------------------------------------------------------------------------------*/
1936
+ /**
1937
+ * Lowers an app to a program for one panel.
1938
+ *
1939
+ * @param app The lowered app.
1940
+ * @param options The compile's options: the panel, and the string cap.
1941
+ *
1942
+ * @returns The program.
1943
+ */
1944
+ export function lowerPackage(app, options) {
1945
+ const { screen } = options;
1946
+ const tables = new ProgramTables();
1947
+ const lowering = {
1948
+ app,
1949
+ ...planSlots(app, tables, options.caps),
1950
+ images: new Set(app.images.map(image => image.name)),
1951
+ handlers: new Map(),
1952
+ bindings: [],
1953
+ templates: [],
1954
+ effectFunctions: { checks: [], mounts: [] },
1955
+ };
1956
+ const { output } = app;
1957
+ // A row's handlers are compared by their code before the functions are numbered, so each timer they start
1958
+ // stands in by its own place until then.
1959
+ output.timerFunctions.forEach((timer, index) => lowering.slots.timerFunctions.set(timer.name, index));
1960
+ // A root the app's tree fills. The runtime sizes it to the real panel.
1961
+ const nodes = [
1962
+ {
1963
+ type: ENGINE_VALUES.get('ER_NODE_VIEW'),
1964
+ children: 1,
1965
+ props: tables.propSet([]),
1966
+ handle: NONE,
1967
+ bindings: 0,
1968
+ bindingCount: 0,
1969
+ },
1970
+ ];
1971
+ templateNodes(app.root, lowering, nodes);
1972
+ branchTemplates(lowering);
1973
+ rowTemplates(lowering);
1974
+ // Every row is built, whether the list holds it or not, and the largest branch of each conditional; the root
1975
+ // template's own node too.
1976
+ const nodeCount = 1 + mostBuilt(app.root, () => 1);
1977
+ const vectorNodes = mostBuilt(app.root, node => node.type === 'ER_NODE_VECTOR' ? 1 : 0);
1978
+ if (nodeCount > MAX_U16) {
1979
+ throw aotError(`AOT: the app needs ${nodeCount} nodes, but a package holds ${MAX_U16}`, 'lower ER_AOT_LIST_CAP (the listCap option), or give the list rows fewer nodes.');
1980
+ }
1981
+ // Handlers first, as the bindings number them, then the timer callbacks, the effects, and the boot and
1982
+ // update functions. Each is numbered before any code is written, since code names them.
1983
+ let next = lowering.handlers.size;
1984
+ for (const timer of output.timerFunctions) {
1985
+ lowering.slots.timerFunctions.set(timer.name, next++);
1986
+ }
1987
+ if (output.nativeEventHandlers.length > MAX_NATIVE_EVENTS) {
1988
+ throw aotError(`AOT: the app subscribes to native events ${output.nativeEventHandlers.length} times, but a package holds ` +
1989
+ `${MAX_NATIVE_EVENTS}`, 'each useNativeEvent counts once, and once for each row of a list it is in: subscribe in the component ' +
1990
+ 'that holds the list instead.');
1991
+ }
1992
+ // An optional module's methods and events are all listed, used or not, so that whether it is there agrees with
1993
+ // Flow A, which looks for them all. An event nothing subscribes to has no function.
1994
+ for (const module of output.optionalModules) {
1995
+ module.methods.forEach(method => tables.nativeImport(method));
1996
+ }
1997
+ const subscribed = byEvent(output.nativeEventHandlers);
1998
+ const nativeEvent = (event, handler) => ({
1999
+ name: tables.string(event.name),
2000
+ version: event.version,
2001
+ signature: tables.string(event.signature),
2002
+ function: handler,
2003
+ module: event.module ?? NONE,
2004
+ });
2005
+ const nativeEvents = subscribed.map(([{ event }]) => nativeEvent(event, next++));
2006
+ const subscribedNames = new Set(subscribed.map(([{ event }]) => event.name));
2007
+ for (const module of output.optionalModules) {
2008
+ for (const event of module.events) {
2009
+ if (!subscribedNames.has(event.name)) {
2010
+ nativeEvents.push(nativeEvent(event, NONE));
2011
+ }
2012
+ }
2013
+ }
2014
+ if (nativeEvents.length > MAX_NATIVE_EVENTS) {
2015
+ throw aotError(`AOT: the app lists ${nativeEvents.length} native events, but a package holds ${MAX_NATIVE_EVENTS}`, 'an optional module counts every event its interface declares; declare fewer events.');
2016
+ }
2017
+ lowering.effectFunctions = {
2018
+ checks: output.dependencyEffects.map(() => next++),
2019
+ mounts: output.mountEffects.map(() => next++),
2020
+ };
2021
+ // Then the animations' done functions, and the completions they and the rest call, after every caller.
2022
+ const { animations } = lowering.slots;
2023
+ animations.number(next, next + animations.doneFunctions.size);
2024
+ const functions = [
2025
+ ...[...lowering.handlers.values()].map(handler => handlerBody(handler, lowering)),
2026
+ ...output.timerFunctions.map(timer => timerBody(timer.name, timer.callback, lowering)),
2027
+ ...subscribed.map(handlers => nativeEventBody(handlers, lowering)),
2028
+ ...output.dependencyEffects.map(effect => checkedEffect(effect, lowering)),
2029
+ ...output.mountEffects.map((_, index) => mountEffect(index, lowering)),
2030
+ ...doneFunctions(animations, builder => new Codegen(builder, lowering.slots)),
2031
+ ...[...animations.completions.values()].map(completion => completionBody(completion, lowering)),
2032
+ ];
2033
+ const boot = bootFunction(app.boot.slots, lowering);
2034
+ const update = updateFunction(lowering);
2035
+ const bootIndex = boot ? functions.push(boot) - 1 : NONE;
2036
+ const updateIndex = update ? functions.push(update) - 1 : NONE;
2037
+ // A completion that arrives while a function runs waits in the queue: each running tree's, and each one a
2038
+ // single function's starts and stops can end at once.
2039
+ if (animations.entries) {
2040
+ const ends = Math.max(0, ...functions.map(programFunction => countOps(programFunction, ['ASTART', 'AVSET', 'ASTOP'])));
2041
+ lowering.slots.arena.eventQueue(animations.entries + 2 * ends);
2042
+ }
2043
+ const { regions, bytes } = lowering.slots.arena.regions(stackCells(functions));
2044
+ // Host values, by name, for erb_input_find().
2045
+ const inputs = app.state
2046
+ .filter((state) => state.kind === 'scalar' && state.host)
2047
+ .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)
2048
+ .map(state => ({
2049
+ name: tables.string(state.name),
2050
+ slot: lowering.slots.states.get(state).index,
2051
+ }));
2052
+ return {
2053
+ flags: FLAG_DEBUG,
2054
+ panels: [
2055
+ {
2056
+ width: screen.width,
2057
+ height: screen.height,
2058
+ check: lowerCheck(app.boot.assumptions, screen),
2059
+ arenaBytes: bytes,
2060
+ nodeCount,
2061
+ rootTemplate: 0,
2062
+ bootFunction: bootIndex,
2063
+ updateFunction: updateIndex,
2064
+ },
2065
+ ],
2066
+ needs: [
2067
+ ...(vectorNodes
2068
+ ? [{ resource: Resource.vectorNodes, amount: vectorNodes }]
2069
+ : []),
2070
+ // Each animated value runs one engine animation at a time.
2071
+ ...(animations.values.size
2072
+ ? [
2073
+ {
2074
+ resource: Resource.animationValues,
2075
+ amount: animations.values.size,
2076
+ },
2077
+ { resource: Resource.animations, amount: animations.values.size },
2078
+ ]
2079
+ : []),
2080
+ ...(app.images.length
2081
+ ? [{ resource: Resource.images, amount: app.images.length }]
2082
+ : []),
2083
+ ],
2084
+ strings: tables.strings,
2085
+ const32: tables.const32,
2086
+ const64: tables.const64,
2087
+ regions,
2088
+ slots: lowering.slots.arena.slots,
2089
+ enums: [...lowering.slots.enums.values()].map(({ values }) => values.map(value => tables.string(value))),
2090
+ rows: lowering.rows,
2091
+ propSets: tables.propSets,
2092
+ templates: [{ kind: TemplateKind.root, nodes }, ...lowering.templates],
2093
+ bindings: lowering.bindings,
2094
+ functions,
2095
+ animations: animations.animations,
2096
+ imports: tables.imports,
2097
+ nativeEvents,
2098
+ inputs,
2099
+ interpolations: animations.interpolations,
2100
+ tapes: lowering.slots.vectors.tapes,
2101
+ keyboard: app.keyboard ? keyboardTable(app.keyboard, tables) : null,
2102
+ };
2103
+ }