embedded-react 0.18.0 → 0.20.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 (117) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +8 -4
  3. package/aot/compile.mjs +178 -58
  4. package/aot/compiler/animations.mjs +290 -281
  5. package/aot/compiler/boot.mjs +70 -33
  6. package/aot/compiler/branch-merge.mjs +4 -3
  7. package/aot/compiler/check.mjs +9 -9
  8. package/aot/compiler/collect.mjs +324 -205
  9. package/aot/compiler/control-flow.mjs +209 -197
  10. package/aot/compiler/diagnostics.mjs +22 -25
  11. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  12. package/aot/compiler/elements/dial.mjs +91 -77
  13. package/aot/compiler/elements/flat-list.mjs +24 -22
  14. package/aot/compiler/elements/image.mjs +51 -50
  15. package/aot/compiler/elements/modal.mjs +31 -30
  16. package/aot/compiler/elements/props.mjs +23 -23
  17. package/aot/compiler/elements/switch.mjs +42 -34
  18. package/aot/compiler/elements/text-input.mjs +34 -32
  19. package/aot/compiler/expressions.mjs +372 -333
  20. package/aot/compiler/handlers.mjs +473 -387
  21. package/aot/compiler/ir/functions.mjs +11 -1
  22. package/aot/compiler/ir/nodes.mjs +4 -4
  23. package/aot/compiler/ir/reads.mjs +19 -19
  24. package/aot/compiler/ir/types.mjs +14 -14
  25. package/aot/compiler/ir/vectors.mjs +5 -1
  26. package/aot/compiler/keyboard.mjs +17 -7
  27. package/aot/compiler/lower.mjs +77 -80
  28. package/aot/compiler/nodes.mjs +169 -152
  29. package/aot/compiler/options.mjs +35 -30
  30. package/aot/compiler/out.mjs +18 -22
  31. package/aot/compiler/package/animations.mjs +669 -0
  32. package/aot/compiler/package/arena.mjs +252 -0
  33. package/aot/compiler/package/assemble.mjs +177 -0
  34. package/aot/compiler/package/bytecode.mjs +286 -0
  35. package/aot/compiler/package/checks.mjs +1022 -0
  36. package/aot/compiler/package/codegen.mjs +1329 -0
  37. package/aot/compiler/package/enums.mjs +138 -0
  38. package/aot/compiler/package/format.mjs +760 -0
  39. package/aot/compiler/package/layouts.mjs +136 -0
  40. package/aot/compiler/package/lower.mjs +1606 -0
  41. package/aot/compiler/package/props.mjs +118 -0
  42. package/aot/compiler/package/tables.mjs +103 -0
  43. package/aot/compiler/package/vectors.mjs +502 -0
  44. package/aot/compiler/package/writer.mjs +664 -0
  45. package/aot/compiler/pan-responder.mjs +69 -61
  46. package/aot/compiler/parse.mjs +21 -21
  47. package/aot/compiler/static-eval.mjs +25 -23
  48. package/aot/compiler/style-text.mjs +161 -172
  49. package/aot/compiler/svg.mjs +477 -251
  50. package/aot/screenshot-smoke.mjs +55 -41
  51. package/aot/style-map.mjs +102 -90
  52. package/assets/bake-font.mjs +123 -77
  53. package/assets/bake-image.mjs +39 -22
  54. package/assets/bake-svg.mjs +361 -262
  55. package/assets/build-builtin-font.mjs +14 -10
  56. package/assets/emit-c.mjs +83 -62
  57. package/assets/emit-container.mjs +124 -38
  58. package/assets/emit-pack.mjs +77 -67
  59. package/assets/font-config.mjs +9 -6
  60. package/assets/font-sizes.mjs +163 -123
  61. package/assets/glyph-coverage.mjs +74 -54
  62. package/assets/index.mjs +31 -9
  63. package/assets/rasterize.mjs +126 -99
  64. package/assets/svg-loader.mjs +8 -8
  65. package/build.mjs +16 -14
  66. package/cli.mjs +359 -172
  67. package/compile-bin.mjs +5 -5
  68. package/flash.mjs +537 -0
  69. package/hotreload/dev-device.mjs +90 -33
  70. package/hotreload/pack-app.mjs +55 -43
  71. package/hotreload/pack-split.mjs +46 -37
  72. package/hotreload/package-transfer.mjs +175 -0
  73. package/hotreload/protocol.mjs +51 -38
  74. package/hotreload/uploader.mjs +38 -27
  75. package/hotreload/watch-tree.mjs +19 -19
  76. package/pack-container.mjs +31 -23
  77. package/package.json +11 -12
  78. package/persist-transform.mjs +34 -28
  79. package/qjsc-wasm.mjs +25 -14
  80. package/sim/embedded-react.cjs +1 -1
  81. package/sim/embedded-react.js +1 -1
  82. package/sim/embedded-react.wasm +0 -0
  83. package/sim/index.html +94 -85
  84. package/sim-server.mjs +101 -82
  85. package/src/embedded-react/Animated.js +24 -24
  86. package/src/embedded-react/Easing.js +1 -1
  87. package/src/embedded-react/FlatList.js +4 -4
  88. package/src/embedded-react/LayoutAnimation.js +8 -5
  89. package/src/embedded-react/PanResponder.js +75 -71
  90. package/src/embedded-react/Pressable.js +2 -8
  91. package/src/embedded-react/SectionList.js +6 -6
  92. package/src/embedded-react/StyleSheet.js +4 -3
  93. package/src/embedded-react/TouchableOpacity.js +13 -8
  94. package/src/embedded-react/index.d.ts +5 -5
  95. package/src/embedded-react/layout-anim-config.js +10 -4
  96. package/src/embedded-react/list-child.js +5 -5
  97. package/src/embedded-react/named-colors.js +1 -1
  98. package/src/embedded-react/split-style.js +11 -11
  99. package/src/embedded-react/svg-ops.js +760 -593
  100. package/src/embedded-react/useHostValue.js +3 -3
  101. package/src/embedded-react/usePersistentState.js +6 -6
  102. package/src/embedded-react/warn-props.js +1 -1
  103. package/src/host-config.js +60 -53
  104. package/src/props.js +49 -41
  105. package/src/renderer.js +7 -4
  106. package/aot/compiler/assemble.mjs +0 -944
  107. package/aot/compiler/c/animations.mjs +0 -436
  108. package/aot/compiler/c/boot.mjs +0 -127
  109. package/aot/compiler/c/expressions.mjs +0 -270
  110. package/aot/compiler/c/functions.mjs +0 -268
  111. package/aot/compiler/c/keyboard.mjs +0 -96
  112. package/aot/compiler/c/nodes.mjs +0 -303
  113. package/aot/compiler/c/pan-responder.mjs +0 -136
  114. package/aot/compiler/c/statements.mjs +0 -319
  115. package/aot/compiler/c/text.mjs +0 -83
  116. package/aot/compiler/c/vectors.mjs +0 -381
  117. package/aot/compiler/c-syntax.mjs +0 -127
@@ -0,0 +1,1606 @@
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 PanResponder is a handler for each responder event and a query function for each should-set predicate,
36
+ * bound on each node that spreads it. Its gesture state is slots, kept by its grant, release and terminate
37
+ * handlers, and a callback reads the gesture through them and EVT.
38
+ *
39
+ * An effect runs inside an update pass, so the state it sets shows at the next pass that isn't its own, not at
40
+ * once. The VM runs a pass whenever state changed, so a pass that only an
41
+ * effect's write started keeps what changed in a pending flag, and the next pass a handler, a timer or the
42
+ * load started sets it. A dep-driven effect checks its deps itself, when it runs,
43
+ * each in turn. The mount effects run one after another, after the first pass; one that set state has the
44
+ * pass after it queue the next.
45
+ */
46
+ /*----------------------------------------------------------------------------------------------------------------------
47
+ - Imports
48
+ ---------------------------------------------------------------------------------------------------------------------*/
49
+ import { aotError, constantText, ENGINE_STRING_MAX, locateError, } from '../diagnostics.mjs';
50
+ import { hasRuntimeProps, isStateDriven, nodesOf, branchElements, stateDrivenVectorOf, updatedVectorOf, } from '../ir/nodes.mjs';
51
+ import { nodeReads, vectorReads } from '../ir/reads.mjs';
52
+ import { armedFlag } from '../ir/functions.mjs';
53
+ import { AnimationPlan, doneFunctions, startPressFade } from './animations.mjs';
54
+ import { Arena } from './arena.mjs';
55
+ import { FunctionBuilder, OP } from './bytecode.mjs';
56
+ import { internedStates } from './enums.mjs';
57
+ import { Codegen, notYet } from './codegen.mjs';
58
+ import { BindingKind, ENGINE_VALUES, EventField, FLAG_DEBUG, FRAME_CELLS, FunctionKind, MAX_SPANS, NONE, Resource, SlotFlag, TemplateKind, ValueType, } from './format.mjs';
59
+ import { abiProp, constantPropEntry, floatBits, stringPropEntry, } from './props.mjs';
60
+ import { ProgramTables } from './tables.mjs';
61
+ import { commitDrawing, VectorPlan } from './vectors.mjs';
62
+ import { lowerCheck } from './checks.mjs';
63
+ /*----------------------------------------------------------------------------------------------------------------------
64
+ - Constants
65
+ ---------------------------------------------------------------------------------------------------------------------*/
66
+ /** The most a u16 count or size in the format holds: a row's bytes, a panel's nodes, the row fields. */
67
+ const MAX_U16 = 0xffff;
68
+ /** The most fields a row has: ROWGET names one in a byte. */
69
+ const MAX_ROW_FIELDS = 255;
70
+ /** Key kind → its ERKeyboardKey type. */
71
+ const KEY_TYPES = {
72
+ char: 'ER_KEYBOARD_KEY_CHAR',
73
+ layer: 'ER_KEYBOARD_KEY_LAYER',
74
+ backspace: 'ER_KEYBOARD_KEY_BACKSPACE',
75
+ done: 'ER_KEYBOARD_KEY_DONE',
76
+ };
77
+ /** The highlight layer that means "never highlighted". */
78
+ const NEVER_HIGHLIGHTED = 255;
79
+ /** A TextSpan's constant fields, in their ABI ids' order. */
80
+ const SPAN_FIELDS = [
81
+ 'color',
82
+ 'font_size',
83
+ 'font_weight',
84
+ 'font_style',
85
+ 'text_decoration',
86
+ 'letter_spacing',
87
+ ];
88
+ /*----------------------------------------------------------------------------------------------------------------------
89
+ - Implementation
90
+ ---------------------------------------------------------------------------------------------------------------------*/
91
+ /**
92
+ * Refuses what a package can't lower yet, pointing at where it is.
93
+ *
94
+ * @param what What the app uses.
95
+ * @param location Where in the source, when it is known.
96
+ */
97
+ function notYetAt(what, location) {
98
+ try {
99
+ notYet(what);
100
+ }
101
+ catch (error) {
102
+ locateError(error, location);
103
+ throw error;
104
+ }
105
+ }
106
+ /** Whether the update sets a node's props once, at load: they read only boot values, or it has spans. */
107
+ const isSetOnce = (node) => !isStateDriven(node) && (hasRuntimeProps(node) || node.spans !== null);
108
+ /*----------------------------------------------------------------------------------------------------------------------
109
+ - Slots
110
+ ---------------------------------------------------------------------------------------------------------------------*/
111
+ /**
112
+ * The most bytes a boot value's string can be: its longest literal, since nothing else reaches it at boot.
113
+ *
114
+ * @param expression The value.
115
+ *
116
+ * @returns The bytes.
117
+ */
118
+ function longestLiteral(expression) {
119
+ let longest = 0;
120
+ const walk = (value) => {
121
+ if (!value || typeof value !== 'object') {
122
+ return;
123
+ }
124
+ const node = value;
125
+ if (node.kind === 'string' && typeof node.value === 'string') {
126
+ longest = Math.max(longest, Buffer.byteLength(node.value, 'utf8'));
127
+ return;
128
+ }
129
+ Object.values(node).forEach(walk);
130
+ };
131
+ walk(expression);
132
+ return Math.max(longest, 1);
133
+ }
134
+ /**
135
+ * Every string local a statement list declares, with its cap.
136
+ *
137
+ * @param statements The statements.
138
+ * @param found Collects each local's name and cap.
139
+ */
140
+ function stringLocals(statements, found) {
141
+ for (const statement of statements) {
142
+ if (statement.kind === 'declareLocal' &&
143
+ statement.initializer.type.kind === 'string') {
144
+ found.set(statement.name, Math.max(found.get(statement.name) ?? 0, statement.stringCapacity - 1));
145
+ }
146
+ else if (statement.kind === 'if') {
147
+ stringLocals(statement.consequent, found);
148
+ stringLocals(statement.alternate ?? [], found);
149
+ }
150
+ }
151
+ }
152
+ /**
153
+ * Every updateVector call a statement list makes.
154
+ *
155
+ * @param statements The statements.
156
+ * @param found Collects the calls.
157
+ */
158
+ function updateVectors(statements, found) {
159
+ for (const statement of statements) {
160
+ if (statement.kind === 'updateVector') {
161
+ found.push(statement);
162
+ }
163
+ else if (statement.kind === 'if') {
164
+ updateVectors(statement.consequent, found);
165
+ updateVectors(statement.alternate ?? [], found);
166
+ }
167
+ }
168
+ }
169
+ /**
170
+ * Every state and list a statement list sets.
171
+ *
172
+ * @param statements The statements.
173
+ * @param found Collects the states.
174
+ */
175
+ function statesSet(statements, found) {
176
+ for (const statement of statements) {
177
+ if (statement.kind === 'setState' || statement.kind === 'setStateText') {
178
+ found.add(statement.state);
179
+ }
180
+ else if ('list' in statement) {
181
+ found.add(statement.list);
182
+ }
183
+ else if (statement.kind === 'if') {
184
+ statesSet(statement.consequent, found);
185
+ statesSet(statement.alternate ?? [], found);
186
+ }
187
+ }
188
+ }
189
+ /**
190
+ * The type a dep's copy is kept in.
191
+ *
192
+ * @param dependency The dep.
193
+ *
194
+ * @returns Its type.
195
+ */
196
+ function depType(dependency) {
197
+ switch (dependency.type.kind) {
198
+ case 'bool':
199
+ case 'float':
200
+ case 'int64':
201
+ case 'string':
202
+ return dependency.type.kind;
203
+ default:
204
+ return 'int';
205
+ }
206
+ }
207
+ /**
208
+ * Whether a mount effect sets state, so an update runs after it.
209
+ *
210
+ * @param mountEffect The mount effect.
211
+ *
212
+ * @returns Whether it does.
213
+ */
214
+ const mountUpdates = (mountEffect) => mountEffect.kind === 'inline'
215
+ ? mountEffect.callback.updatesState
216
+ : mountEffect.kind === 'call' && mountEffect.updatesState;
217
+ /**
218
+ * Every statement list the program runs outside the update and boot functions.
219
+ *
220
+ * @param app The app.
221
+ *
222
+ * @returns The lists.
223
+ */
224
+ function bodies(app) {
225
+ const { output } = app;
226
+ return [
227
+ ...output.handlers.flatMap(handler => handler.kind === 'callback'
228
+ ? [handler.callback.body]
229
+ : handler.kind === 'panEvent' && handler.event.callback
230
+ ? [handler.event.callback.body]
231
+ : []),
232
+ ...output.timerFunctions.map(timer => timer.callback.body),
233
+ ...output.effectFunctions.map(effectFunction => effectFunction.kind === 'mount'
234
+ ? effectFunction.body
235
+ : effectFunction.kind === 'cleanup'
236
+ ? effectFunction.effect.cleanup
237
+ : effectFunction.effect.body),
238
+ ...output.mountEffects.flatMap(mountEffect => mountEffect.kind === 'inline' ? [mountEffect.callback.body] : []),
239
+ ...completionsOf(app).map(completion => completion.body),
240
+ ];
241
+ }
242
+ /**
243
+ * Every animation completion, in the order the app declares them.
244
+ *
245
+ * @param app The app.
246
+ *
247
+ * @returns The completions.
248
+ */
249
+ const completionsOf = (app) => app.output.animationCallbacks.flatMap(callback => callback.kind === 'completion' ? [callback.completion] : []);
250
+ /**
251
+ * A state's slot: a scalar's own, or a list's pool.
252
+ *
253
+ * @param state The state.
254
+ * @param slots The program's slots.
255
+ *
256
+ * @returns The slot.
257
+ */
258
+ const stateSlotOf = (state, slots) => state.kind === 'list'
259
+ ? slots.lists.get(state).slot
260
+ : slots.states.get(state);
261
+ /**
262
+ * The first node an element builds.
263
+ *
264
+ * @param element The element.
265
+ *
266
+ * @returns The node.
267
+ */
268
+ const firstNode = (element) => element.kind === 'component' ? firstNode(element.root) : element.node;
269
+ /**
270
+ * Every `.map` over a list under an element, in tree order, with the node its rows go under and the one they go
271
+ * before. A list inside a list's row is refused.
272
+ *
273
+ * @param element The element.
274
+ * @param found Collects the pools.
275
+ */
276
+ function poolsOf(element, found) {
277
+ if (element.kind === 'component') {
278
+ poolsOf(element.root, found);
279
+ return;
280
+ }
281
+ const { node } = element;
282
+ node.children.forEach((child, index) => {
283
+ if (child.kind === 'element') {
284
+ poolsOf(child.element, found);
285
+ }
286
+ else if (child.kind === 'conditional') {
287
+ branchElements(child).forEach(branch => poolsOf(branch, found));
288
+ }
289
+ else {
290
+ for (const row of child.rows) {
291
+ const nested = nodesOf(row).find(rowNode => rowNode.children.some(rowChild => rowChild.kind === 'pool'));
292
+ if (nested) {
293
+ notYetAt('a list inside a list row', nested.location);
294
+ }
295
+ }
296
+ // The rows go before the next node the parent builds itself.
297
+ const after = node.children
298
+ .slice(index + 1)
299
+ .flatMap(sibling => sibling.kind === 'element'
300
+ ? [sibling.element]
301
+ : sibling.kind === 'conditional'
302
+ ? branchElements(sibling)
303
+ : []);
304
+ found.push({
305
+ list: child.list,
306
+ rows: child.rows,
307
+ parent: node,
308
+ anchor: after.length ? firstNode(after[0]) : null,
309
+ templates: [],
310
+ });
311
+ }
312
+ });
313
+ }
314
+ /**
315
+ * Plans every slot the program uses, then lays the arena out.
316
+ *
317
+ * @param app The app.
318
+ * @param tables The program's tables.
319
+ * @param caps The buffer sizes, and the timers that run at once.
320
+ *
321
+ * @returns The slots, the node handles, and the bookkeeping bits.
322
+ */
323
+ function planSlots(app, tables, caps) {
324
+ const { listStrCap: listStringCapacity } = caps;
325
+ const { output } = app;
326
+ const arena = new Arena();
327
+ const animations = new AnimationPlan(app, arena);
328
+ const slots = {
329
+ arena,
330
+ tables,
331
+ states: new Map(),
332
+ lists: new Map(),
333
+ refs: new Map(),
334
+ boot: new Map(),
335
+ stringLocals: new Map(),
336
+ enums: new Map(),
337
+ hoisted: new Map(),
338
+ armed: new Map(),
339
+ timerFunctions: new Map(),
340
+ animations,
341
+ gestures: new Map(),
342
+ vectors: new VectorPlan(arena),
343
+ };
344
+ // String state with a closed set of values is an interned enum, starting at its initial value (the first).
345
+ for (const [state, values] of internedStates(app)) {
346
+ slots.enums.set(state, {
347
+ set: slots.enums.size,
348
+ values,
349
+ });
350
+ }
351
+ // State, each with a dirty bit when a node reads it.
352
+ for (const state of app.state) {
353
+ if (state.kind === 'list') {
354
+ continue;
355
+ }
356
+ const interned = slots.enums.get(state);
357
+ // One the boot function sets starts at 0, so nothing of the build's panel is left in the package.
358
+ const initial = state.bootInitial ? 0 : state.initial;
359
+ const slot = interned
360
+ ? Object.assign(arena.slot(ValueType.enum, 0), { aux: interned.set })
361
+ : state.slotKind === 'string'
362
+ ? arena.slot(ValueType.string, tables.string(String(initial)), listStringCapacity - 1)
363
+ : state.slotKind === 'i64'
364
+ ? arena.slot(ValueType.int64, tables.constant64(BigInt(Math.trunc(Number(initial)))))
365
+ : state.slotKind === 'float'
366
+ ? arena.slot(ValueType.float, floatBits(Number(initial)))
367
+ : arena.slot(state.isBoolean ? ValueType.bool : ValueType.int, Math.trunc(Number(initial)) | 0);
368
+ // A host value an effect's deps may read runs an update when it is set.
369
+ if (state.isWatched || (state.host && output.dependencyEffects.length)) {
370
+ arena.track(slot);
371
+ }
372
+ slots.states.set(state, slot);
373
+ }
374
+ // A list is a pool of rows, empty at load; the boot function appends its first items. Each row field is
375
+ // 4-aligned, and a string field holds its cap and a terminator.
376
+ const rows = [];
377
+ for (const state of app.state) {
378
+ if (state.kind !== 'list') {
379
+ continue;
380
+ }
381
+ if (!state.struct.fields.length) {
382
+ notYet(`list state "${state.name}", whose items have no fields`);
383
+ }
384
+ if (state.struct.fields.length > MAX_ROW_FIELDS) {
385
+ throw aotError(`AOT: list state "${state.name}" has ${state.struct.fields.length} fields, but a package row holds ${MAX_ROW_FIELDS}`, 'give the items fewer fields.');
386
+ }
387
+ let size = 0;
388
+ const fields = state.struct.fields.map(field => {
389
+ const capacity = field.kind === 'string' ? listStringCapacity - 1 : 0;
390
+ const entry = { type: ValueType[field.kind], cap: capacity, offset: size };
391
+ size += field.kind === 'string' ? (capacity + 1 + 3) & ~3 : 4;
392
+ return entry;
393
+ });
394
+ if (size > MAX_U16) {
395
+ throw aotError(`AOT: a row of list state "${state.name}" takes ${size} bytes, but a package row holds ${MAX_U16 - 3}`, 'lower ER_AOT_LIST_STR_CAP (the listStrCap option), or give the items fewer text fields.');
396
+ }
397
+ const slot = arena.list(rows.length, size, state.capacity);
398
+ rows.push({ size, fields });
399
+ if (state.isWatched) {
400
+ arena.track(slot);
401
+ }
402
+ // An appended item's text is built in a buffer of its own, then copied into the row.
403
+ const buffers = new Map(state.struct.fields
404
+ .filter(field => field.kind === 'string')
405
+ .map(field => [
406
+ field.key,
407
+ arena.slot(ValueType.string, undefined, listStringCapacity - 1),
408
+ ]));
409
+ slots.lists.set(state, { slot, buffers });
410
+ }
411
+ const fieldCount = rows.reduce((count, row) => count + row.fields.length, 0);
412
+ if (fieldCount > MAX_U16) {
413
+ 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.');
414
+ }
415
+ for (const ref of app.refs) {
416
+ if (ref.kind !== 'value') {
417
+ continue;
418
+ }
419
+ slots.refs.set(ref, ref.slotKind === 'i64'
420
+ ? arena.slot(ValueType.int64, tables.constant64(BigInt(Math.trunc(ref.initial))))
421
+ : ref.slotKind === 'float'
422
+ ? arena.slot(ValueType.float, floatBits(ref.initial))
423
+ : arena.slot(ValueType.int, Math.trunc(ref.initial) | 0));
424
+ }
425
+ // Boot values: a fraction is kept as a double.
426
+ for (const bootSlot of app.boot.slots) {
427
+ const slot = bootSlot.type.kind === 'float'
428
+ ? arena.slot(ValueType.double)
429
+ : bootSlot.type.kind === 'string'
430
+ ? arena.slot(ValueType.string, undefined, bootSlot.initializer.kind === 'expr'
431
+ ? longestLiteral(bootSlot.initializer.expression)
432
+ : 1)
433
+ : arena.slot(bootSlot.type.kind === 'bool' ? ValueType.bool : ValueType.int);
434
+ slot.flags |= SlotFlag.bootOnly;
435
+ slots.boot.set(bootSlot, slot);
436
+ }
437
+ // The effect locals a cleanup reads, and each effect's armed flag and copy of each dep.
438
+ for (const declaration of output.effectDeclarations) {
439
+ if (declaration.kind === 'local') {
440
+ slots.hoisted.set(declaration.name, declaration.slotKind === 'string'
441
+ ? arena.slot(ValueType.string, undefined, listStringCapacity - 1)
442
+ : arena.slot(declaration.slotKind === 'i64'
443
+ ? ValueType.int64
444
+ : declaration.slotKind === 'float'
445
+ ? ValueType.float
446
+ : ValueType.int));
447
+ }
448
+ else if (declaration.kind === 'armed') {
449
+ slots.armed.set(armedFlag(declaration.effect.id), arena.slot(ValueType.bool));
450
+ }
451
+ }
452
+ const copies = new Map();
453
+ for (const effect of output.dependencyEffects) {
454
+ copies.set(effect, effect.dependencies.map(dependency => {
455
+ const type = depType(dependency);
456
+ return {
457
+ type,
458
+ slot: type === 'string'
459
+ ? arena.slot(ValueType.string, undefined, listStringCapacity - 1)
460
+ : arena.slot(ValueType[type]),
461
+ };
462
+ }));
463
+ }
464
+ const locals = new Map();
465
+ for (const body of bodies(app)) {
466
+ stringLocals(body, locals);
467
+ }
468
+ for (const [name, capacity] of locals) {
469
+ if (!slots.hoisted.has(name)) {
470
+ slots.stringLocals.set(name, arena.slot(ValueType.string, undefined, capacity));
471
+ }
472
+ }
473
+ const nodes = nodesOf(app.root);
474
+ // A <TextInput>'s onChangeText reads the input's text, through its handle.
475
+ const handles = new Map();
476
+ const readsInput = (node) => node.wiring.some(wire => wire.kind === 'event' && wire.event === 'ER_EVENT_CHANGE_TEXT');
477
+ // An updateVector call draws on the node its ref holds: the last one built with it.
478
+ const calls = [];
479
+ for (const body of bodies(app)) {
480
+ updateVectors(body, calls);
481
+ }
482
+ const drawnRefs = new Set(calls.map(call => call.node));
483
+ const refNodes = new Map();
484
+ for (const node of nodes) {
485
+ for (const wire of node.wiring) {
486
+ if (wire.kind === 'ref' && drawnRefs.has(wire.slot)) {
487
+ refNodes.set(wire.slot, node);
488
+ }
489
+ }
490
+ }
491
+ const drawnOn = new Set(refNodes.values());
492
+ const reached = (node) => isStateDriven(node) ||
493
+ isSetOnce(node) ||
494
+ readsInput(node) ||
495
+ stateDrivenVectorOf(node) !== null;
496
+ // A row's node keeps its handle in an array by the row, one array for each place in the row that needs one.
497
+ const pools = [];
498
+ poolsOf(app.root, pools);
499
+ const rowHandles = new Map();
500
+ for (const pool of pools) {
501
+ const arrays = [];
502
+ pool.rows.forEach((rowElement, row) => nodesOf(rowElement).forEach((node, place) => {
503
+ if (readsInput(node)) {
504
+ notYetAt('onChangeText in a list row', node.location);
505
+ }
506
+ if (drawnOn.has(node)) {
507
+ notYetAt('updateVector on a node in a list row', node.location);
508
+ }
509
+ if (reached(node)) {
510
+ arrays[place] ??= arena.slot(ValueType.node, 0, pool.list.capacity);
511
+ rowHandles.set(node, { array: arrays[place], row });
512
+ }
513
+ }));
514
+ }
515
+ // The rows are built under their parent, before the node after them.
516
+ const builtUnder = new Set(pools.flatMap(pool => pool.anchor ? [pool.parent, pool.anchor] : [pool.parent]));
517
+ for (const node of nodes) {
518
+ if (!rowHandles.has(node) &&
519
+ (reached(node) || builtUnder.has(node) || drawnOn.has(node))) {
520
+ handles.set(node, arena.slot(ValueType.node));
521
+ }
522
+ }
523
+ for (const [ref, node] of refNodes) {
524
+ slots.vectors.refNodes.set(ref, handles.get(node));
525
+ }
526
+ const inputText = nodes.some(readsInput)
527
+ ? arena.slot(ValueType.string, undefined, ENGINE_STRING_MAX.ER_TEXT_MAX)
528
+ : null;
529
+ // Each PanResponder's gesture state.
530
+ for (const pan of output.panResponders) {
531
+ slots.gestures.set(pan.statePrefix, {
532
+ granted: arena.slot(ValueType.bool),
533
+ baseDeltaX: arena.slot(ValueType.int),
534
+ baseDeltaY: arena.slot(ValueType.int),
535
+ x0: arena.slot(ValueType.int),
536
+ y0: arena.slot(ValueType.int),
537
+ });
538
+ }
539
+ const requestsUpdate = output.handlers.some(handler => handler.kind === 'callback'
540
+ ? handler.callback.updatesState
541
+ : handler.kind === 'panEvent' && !!handler.event.callback?.updatesState) ||
542
+ output.timerFunctions.some(timer => timer.callback.updatesState) ||
543
+ output.mountEffects.some(mountUpdates) ||
544
+ completionsOf(app).some(completion => completion.updatesState);
545
+ const requested = requestsUpdate
546
+ ? arena.track(arena.slot(ValueType.bool))
547
+ : null;
548
+ const hasEffects = output.dependencyEffects.length > 0 || output.mountEffects.length > 0;
549
+ const once = hasEffects ||
550
+ pools.length ||
551
+ nodes.some(node => isStateDriven(node) || isSetOnce(node) || stateDrivenVectorOf(node))
552
+ ? arena.track(arena.slot(ValueType.bool))
553
+ : null;
554
+ // A state an effect sets that a node reads waits for the next update in a pending flag.
555
+ const effectWrites = new Set();
556
+ for (const effect of output.dependencyEffects) {
557
+ statesSet(effect.body, effectWrites);
558
+ statesSet(effect.cleanup ?? [], effectWrites);
559
+ }
560
+ const pending = new Map();
561
+ for (const state of effectWrites) {
562
+ const slot = stateSlotOf(state, slots);
563
+ if (slot.flags & SlotFlag.tracked) {
564
+ pending.set(slot, arena.slot(ValueType.bool));
565
+ }
566
+ }
567
+ const realBits = [requested, once].filter(slot => slot !== null);
568
+ for (const [state, slot] of slots.states) {
569
+ if (state.host && slot.flags & SlotFlag.tracked) {
570
+ realBits.push(slot);
571
+ }
572
+ }
573
+ // The first mount effect is queued by the first pass.
574
+ const mountNext = output.mountEffects.length
575
+ ? arena.slot(ValueType.int, 1)
576
+ : null;
577
+ if (output.timerFunctions.length) {
578
+ arena.timerTable(caps.maxTimers);
579
+ }
580
+ // A pass queues each dep-driven effect and the next mount effect, and a mount effect the one after it.
581
+ if (hasEffects) {
582
+ arena.eventQueue(output.dependencyEffects.length + 1);
583
+ }
584
+ arena.layOut();
585
+ return {
586
+ slots,
587
+ handles,
588
+ rowHandles,
589
+ rows,
590
+ pools,
591
+ inputText,
592
+ requested,
593
+ once,
594
+ effects: { copies, pending, realBits, mountNext },
595
+ };
596
+ }
597
+ /*----------------------------------------------------------------------------------------------------------------------
598
+ - Templates
599
+ ---------------------------------------------------------------------------------------------------------------------*/
600
+ /**
601
+ * A node's constant props as a prop set: its style, then a placeholder,
602
+ * text, and image known at compile time.
603
+ *
604
+ * @param node The node.
605
+ * @param lowering The program being lowered.
606
+ *
607
+ * @returns The set's entries.
608
+ */
609
+ function constantProps(node, lowering) {
610
+ const { tables } = lowering.slots;
611
+ const entries = node.constantProps.map(prop => constantPropEntry(prop.field, prop.value));
612
+ if (node.placeholder != null) {
613
+ entries.push(stringPropEntry('placeholder', tables.string(node.placeholder)));
614
+ }
615
+ const text = node.text ? constantText(node.text) : null;
616
+ if (text !== null) {
617
+ entries.push(stringPropEntry('text', tables.string(text)));
618
+ }
619
+ // The runtime only loads a package whose images are all in its own asset pack.
620
+ if (node.image?.kind === 'static') {
621
+ if (!lowering.images.has(node.image.name)) {
622
+ throw aotError(`AOT: the package has no image named "${node.image.name}"`, 'import the image file, so the build bakes it into the package.');
623
+ }
624
+ entries.push(stringPropEntry('image_name', tables.string(node.image.name)));
625
+ }
626
+ return entries;
627
+ }
628
+ /**
629
+ * The handler function an event on a node runs, made the first time. A handler bound to two events is one
630
+ * function per event, since a function's kind is the event it is entered with, and an onChangeText one per
631
+ * input, since it reads its own. Each row has its own handler; rows whose handlers have the same
632
+ * code share one function, so they can share a template.
633
+ *
634
+ * @param name The handler.
635
+ * @param eventName The event, an ER_EVENT_* name.
636
+ * @param node The node it is bound to.
637
+ * @param lowering The program being lowered.
638
+ * @param inRow Whether the node is in a list row.
639
+ *
640
+ * @returns The function's index.
641
+ */
642
+ function handlerFunction(name, eventName, node, lowering, inRow) {
643
+ // A PanResponder's handlers are wired as a responder, not by name.
644
+ const handler = lowering.app.output.handlers.find(candidate => candidate.kind !== 'panEvent' && candidate.name === name);
645
+ if (!handler || handler.kind === 'panEvent') {
646
+ throw new Error(`AOT internal: no handler "${name}"`);
647
+ }
648
+ // A press fade runs the app's own handler for the event after it, when it has one.
649
+ const then = handler.kind === 'pressFade'
650
+ ? handler.then
651
+ ? lowering.app.output.handlers.find(candidate => candidate.kind === 'callback' && candidate.name === handler.then)
652
+ : null
653
+ : handler;
654
+ if (then === undefined || (then && then.kind !== 'callback')) {
655
+ throw new Error(`AOT internal: no handler for "${name}"`);
656
+ }
657
+ const readsInput = eventName === 'ER_EVENT_CHANGE_TEXT';
658
+ const made = {
659
+ callback: then?.callback ?? { body: [], updatesState: false },
660
+ fade: handler.kind === 'pressFade' ? handler.fade : null,
661
+ event: ENGINE_VALUES.get(eventName),
662
+ name,
663
+ input: readsInput
664
+ ? { node: lowering.handles.get(node), text: lowering.inputText }
665
+ : undefined,
666
+ inRow,
667
+ };
668
+ // Compared by code alone, so where each handler is in the source doesn't keep two apart.
669
+ const key = inRow
670
+ ? `row ${JSON.stringify({ ...handlerBody({ ...made, index: NONE }, lowering), debug: undefined })}`
671
+ : `${name} ${eventName}${readsInput ? ` ${node.id}` : ''}`;
672
+ const existing = lowering.handlers.get(key);
673
+ if (existing) {
674
+ return existing.index;
675
+ }
676
+ const index = lowering.handlers.size;
677
+ lowering.handlers.set(key, { ...made, index });
678
+ return index;
679
+ }
680
+ /**
681
+ * A PanResponder's bindings: a handler for each of its events, then a query function for each predicate.
682
+ * Each function is made once, however many nodes spread the responder.
683
+ *
684
+ * @param pan The responder.
685
+ * @param lowering The program being lowered.
686
+ *
687
+ * @returns The bindings.
688
+ */
689
+ function responderBindings(pan, lowering) {
690
+ const made = (key, entry) => {
691
+ const existing = lowering.handlers.get(key);
692
+ if (existing) {
693
+ return existing.index;
694
+ }
695
+ const index = lowering.handlers.size;
696
+ lowering.handlers.set(key, { ...entry, index });
697
+ return index;
698
+ };
699
+ const common = { fade: null, input: undefined, inRow: false };
700
+ return [
701
+ ...pan.events.map(event => {
702
+ const kind = ENGINE_VALUES.get(event.event);
703
+ return {
704
+ kind: BindingKind.event,
705
+ event: kind,
706
+ target: made(`pan ${pan.functionPrefix} ${event.role}`, {
707
+ ...common,
708
+ callback: event.callback ?? { body: [], updatesState: false },
709
+ event: kind,
710
+ name: `${pan.name} ${event.role}`,
711
+ gesture: { statePrefix: pan.statePrefix, role: event.role },
712
+ }),
713
+ };
714
+ }),
715
+ ...pan.queries.map(query => {
716
+ const kind = ENGINE_VALUES.get(query.query);
717
+ return {
718
+ kind: BindingKind.query,
719
+ event: kind,
720
+ target: made(`pan ${pan.functionPrefix} query ${kind}`, {
721
+ ...common,
722
+ callback: { body: [], updatesState: false },
723
+ event: FunctionKind.query + kind,
724
+ name: `${pan.name} query`,
725
+ test: query.test,
726
+ }),
727
+ };
728
+ }),
729
+ ];
730
+ }
731
+ /**
732
+ * An element and everything under it as template nodes, each before its children. A conditional's branches
733
+ * are all built, and the update shows the chosen one. A list's rows are row templates of their own. What a node
734
+ * needs that a package can't lower yet is refused at the node's element.
735
+ *
736
+ * @param element The element.
737
+ * @param lowering The program being lowered.
738
+ * @param nodes Collects the template nodes.
739
+ * @param inRow Whether the element is a list row's.
740
+ */
741
+ function templateNodes(element, lowering, nodes, inRow = false) {
742
+ if (element.kind === 'component') {
743
+ templateNodes(element.root, lowering, nodes, inRow);
744
+ return;
745
+ }
746
+ const { node } = element;
747
+ let children;
748
+ try {
749
+ const bindings = [];
750
+ for (const wire of node.wiring) {
751
+ if (wire.kind === 'bind') {
752
+ bindings.push(lowering.slots.animations.binding(wire.bind));
753
+ }
754
+ else if (wire.kind === 'event') {
755
+ bindings.push({
756
+ kind: BindingKind.event,
757
+ event: ENGINE_VALUES.get(wire.event),
758
+ target: handlerFunction(wire.handler, wire.event, node, lowering, inRow),
759
+ });
760
+ }
761
+ else if (wire.kind === 'responder') {
762
+ bindings.push(...responderBindings(wire.pan, lowering));
763
+ }
764
+ else if (wire.kind === 'vectorTables') {
765
+ // A drawing state drives is committed by the update instead, and a ref needs nothing itself.
766
+ const tape = lowering.slots.vectors.tableTape(wire.tables);
767
+ if (tape !== null) {
768
+ bindings.push({ kind: BindingKind.tape, event: 0, target: tape });
769
+ }
770
+ }
771
+ }
772
+ children = node.children.flatMap(child => child.kind === 'element'
773
+ ? [child.element]
774
+ : child.kind === 'conditional'
775
+ ? branchElements(child)
776
+ : []);
777
+ // A node the update sets starts with no props.
778
+ const handle = inRow
779
+ ? lowering.rowHandles.get(node)?.array
780
+ : lowering.handles.get(node);
781
+ nodes.push({
782
+ type: ENGINE_VALUES.get(node.type),
783
+ children: children.length,
784
+ props: isStateDriven(node) || isSetOnce(node)
785
+ ? NONE
786
+ : lowering.slots.tables.propSet(constantProps(node, lowering)),
787
+ handle: handle?.index ?? NONE,
788
+ bindings: bindings.length ? lowering.bindings.length : 0,
789
+ bindingCount: bindings.length,
790
+ });
791
+ lowering.bindings.push(...bindings);
792
+ }
793
+ catch (error) {
794
+ locateError(error, node.location);
795
+ throw error;
796
+ }
797
+ for (const child of children) {
798
+ templateNodes(child, lowering, nodes, inRow);
799
+ }
800
+ }
801
+ /**
802
+ * Each list row's template. Rows whose nodes and bindings are the same share one.
803
+ *
804
+ * @param lowering The program being lowered.
805
+ */
806
+ function rowTemplates(lowering) {
807
+ const made = new Map();
808
+ for (const pool of lowering.pools) {
809
+ pool.templates = pool.rows.map(row => {
810
+ const first = lowering.bindings.length;
811
+ const nodes = [];
812
+ templateNodes(row, lowering, nodes, true);
813
+ const key = JSON.stringify({
814
+ nodes: nodes.map(node => ({
815
+ ...node,
816
+ bindings: node.bindingCount ? node.bindings - first : 0,
817
+ })),
818
+ bindings: lowering.bindings.slice(first),
819
+ });
820
+ const existing = made.get(key);
821
+ if (existing !== undefined) {
822
+ lowering.bindings.length = first;
823
+ return existing;
824
+ }
825
+ // The root template is first, so a row template's index is its place after it.
826
+ const index = lowering.templates.push({ kind: TemplateKind.row, nodes });
827
+ made.set(key, index);
828
+ return index;
829
+ });
830
+ }
831
+ }
832
+ /*----------------------------------------------------------------------------------------------------------------------
833
+ - Functions
834
+ ---------------------------------------------------------------------------------------------------------------------*/
835
+ /**
836
+ * Sets a node's props again: its constant set, what state drives, its image and its text, then spans when it
837
+ * has them and the update sets it once.
838
+ *
839
+ * @param codegen The update function's codegen.
840
+ * @param node The node.
841
+ * @param lowering The program being lowered.
842
+ */
843
+ function setNode(codegen, node, lowering) {
844
+ const { builder } = codegen;
845
+ const { tables } = lowering.slots;
846
+ const spans = isSetOnce(node) ? node.spans : null;
847
+ if (spans && spans.length > MAX_SPANS) {
848
+ notYet(`more than ${MAX_SPANS} nested <Text> spans`);
849
+ }
850
+ // Span styles are props too.
851
+ const entries = constantProps(node, lowering);
852
+ spans?.forEach((span, index) => SPAN_FIELDS.forEach(field => entries.push(constantPropEntry(`spans[${index}].${field}`, span[field]))));
853
+ builder.abx('PROPS', 0, tables.propSet(entries));
854
+ for (const { field, value } of node.stateProps) {
855
+ codegen.setProp(field, value);
856
+ }
857
+ if (node.image?.kind === 'value') {
858
+ const image = node.image.value;
859
+ codegen.scoped(() => builder.abx('PSETS', codegen.valueAs(image, 'string').index, abiProp('image_name').id));
860
+ }
861
+ if (node.text && constantText(node.text) === null) {
862
+ const { parts } = node.text;
863
+ codegen.scoped(() => {
864
+ codegen.text(parts);
865
+ builder.abc('FMTTEXT');
866
+ });
867
+ }
868
+ spans?.forEach((span, index) => {
869
+ builder.abx('FMTK', 0, tables.string(span.text));
870
+ builder.abc('FMTSPAN', index);
871
+ });
872
+ if (spans) {
873
+ builder.abc('SPANS', spans.length);
874
+ }
875
+ codegen.scoped(() => builder.abc('COMMIT', nodeHandle(codegen, node, lowering).index));
876
+ }
877
+ /**
878
+ * A node's handle: from its slot, or a list row's from its handle array.
879
+ *
880
+ * @param codegen The function's codegen.
881
+ * @param node The node.
882
+ * @param lowering The program being lowered.
883
+ *
884
+ * @returns A node register.
885
+ */
886
+ function nodeHandle(codegen, node, lowering) {
887
+ const { builder } = codegen;
888
+ const handle = builder.register('node');
889
+ const inRow = lowering.rowHandles.get(node);
890
+ if (inRow) {
891
+ builder.abc('GETNI', handle.index, codegen.load('int', inRow.row).index, 0, inRow.array.index);
892
+ }
893
+ else {
894
+ builder.abx('GET64', handle.index, lowering.handles.get(node).index);
895
+ }
896
+ return handle;
897
+ }
898
+ /**
899
+ * Builds every list row, in order, under its parent and before the node after it.
900
+ *
901
+ * @param codegen The update function's codegen.
902
+ * @param lowering The program being lowered.
903
+ */
904
+ function buildRows(codegen, lowering) {
905
+ const { builder } = codegen;
906
+ for (const pool of lowering.pools) {
907
+ codegen.scoped(() => {
908
+ const parent = nodeHandle(codegen, pool.parent, lowering);
909
+ // BUILD before the parent itself puts the row last.
910
+ const before = pool.anchor
911
+ ? nodeHandle(codegen, pool.anchor, lowering)
912
+ : parent;
913
+ pool.templates.forEach((template, row) => codegen.scoped(() => builder.abc('BUILD', builder.register('node').index, parent.index, before.index, template | (codegen.load('int', row).index << 16))));
914
+ });
915
+ }
916
+ }
917
+ /**
918
+ * The dirty bits of a set of slots, as a mask per dirty word.
919
+ *
920
+ * @param slots The slots.
921
+ *
922
+ * @returns Each word's mask.
923
+ */
924
+ function dirtyMasks(slots) {
925
+ const words = new Map();
926
+ for (const slot of slots) {
927
+ const word = slot.dirtyBit >> 5;
928
+ words.set(word, ((words.get(word) ?? 0) | (1 << (slot.dirtyBit & 31))) >>> 0);
929
+ }
930
+ return words;
931
+ }
932
+ /**
933
+ * Runs `body` only when one of a set of dirty bits is set in this update pass, or one of a set of pending flags.
934
+ *
935
+ * @param builder The update function.
936
+ * @param slots The slots whose bits guard it.
937
+ * @param body Emits what it guards.
938
+ * @param pending The pending flags that guard it too.
939
+ */
940
+ function whenDirty(builder, slots, body, pending = []) {
941
+ const run = builder.label();
942
+ const skip = builder.label();
943
+ for (const [word, mask] of dirtyMasks(slots)) {
944
+ builder.branchIfDirty(word, mask, run);
945
+ }
946
+ for (const flag of pending) {
947
+ const checkpoint = builder.checkpoint();
948
+ const set = builder.register('bool');
949
+ builder.abx('GET32', set.index, flag.index);
950
+ builder.branch('JT', run, set);
951
+ builder.release(checkpoint);
952
+ }
953
+ builder.branch('JMP', skip);
954
+ builder.place(run);
955
+ body();
956
+ builder.place(skip);
957
+ }
958
+ /**
959
+ * Writes a constant to a 4-byte slot.
960
+ *
961
+ * @param codegen The function's codegen.
962
+ * @param slot The slot.
963
+ * @param value The value.
964
+ */
965
+ function setConstant(codegen, slot, value) {
966
+ codegen.scoped(() => codegen.builder.abx('SET32', codegen.load(slot.type === ValueType.bool ? 'bool' : 'int', value).index, slot.index));
967
+ }
968
+ /**
969
+ * The update function: what a state change sets again, each node when a state it reads changed, and the nodes set
970
+ * once in the first pass; then the effects it runs, queued.
971
+ *
972
+ * @param lowering The program being lowered.
973
+ *
974
+ * @returns The function, or null when nothing needs it.
975
+ */
976
+ function updateFunction(lowering) {
977
+ const { output } = lowering.app;
978
+ const nodes = nodesOf(lowering.app.root);
979
+ const updated = nodes.filter(isStateDriven);
980
+ const setOnce = nodes.filter(isSetOnce);
981
+ const drawings = nodes.flatMap(node => {
982
+ const vector = stateDrivenVectorOf(node);
983
+ return vector ? [{ node, vector }] : [];
984
+ });
985
+ if (!updated.length &&
986
+ !setOnce.length &&
987
+ !drawings.length &&
988
+ !output.dependencyEffects.length &&
989
+ !output.mountEffects.length) {
990
+ return null;
991
+ }
992
+ const builder = new FunctionBuilder(FunctionKind.update, 'the update');
993
+ const codegen = new Codegen(builder, lowering.slots);
994
+ const { pending, realBits, mountNext } = lowering.effects;
995
+ const located = (node, lower) => {
996
+ builder.at(node.location);
997
+ try {
998
+ lower();
999
+ }
1000
+ catch (error) {
1001
+ locateError(error, node.location);
1002
+ throw error;
1003
+ }
1004
+ };
1005
+ const draw = (node, vector) => located(node, () => commitDrawing(codegen, vector, lowering.slots.vectors, () => nodeHandle(codegen, node, lowering)));
1006
+ // Set again when a state it reads changed; what reads something no state write flags (a ref, the clock) is
1007
+ // set on every pass.
1008
+ const whenRead = (reads, lower) => {
1009
+ const bits = reads
1010
+ ? [...reads].map(state => stateSlotOf(state, lowering.slots))
1011
+ : [];
1012
+ if (bits.length && bits.every(slot => slot.flags & SlotFlag.tracked)) {
1013
+ whenDirty(builder, bits, lower, bits.flatMap(slot => pending.get(slot) ?? []));
1014
+ }
1015
+ else {
1016
+ lower();
1017
+ }
1018
+ };
1019
+ // A pass only an effect's writes started keeps what they changed for the next one.
1020
+ const end = builder.label();
1021
+ if (pending.size) {
1022
+ const real = builder.label();
1023
+ for (const [word, mask] of dirtyMasks(realBits)) {
1024
+ builder.branchIfDirty(word, mask, real);
1025
+ }
1026
+ for (const [state, flag] of pending) {
1027
+ whenDirty(builder, [state], () => setConstant(codegen, flag, 1));
1028
+ }
1029
+ builder.branch('JMP', end);
1030
+ builder.place(real);
1031
+ }
1032
+ // The rows, the props that read only boot values, and the drawings that do, built once.
1033
+ const builtOnce = drawings.filter(({ node }) => !updatedVectorOf(node));
1034
+ if (setOnce.length || lowering.pools.length || builtOnce.length) {
1035
+ whenDirty(builder, [lowering.once], () => {
1036
+ buildRows(codegen, lowering);
1037
+ setOnce.forEach(node => located(node, () => setNode(codegen, node, lowering)));
1038
+ builtOnce.forEach(({ node, vector }) => draw(node, vector));
1039
+ });
1040
+ }
1041
+ // The nodes, then the drawings.
1042
+ for (const node of updated) {
1043
+ located(node, () => whenRead(nodeReads(node), () => setNode(codegen, node, lowering)));
1044
+ }
1045
+ for (const { node, vector } of drawings) {
1046
+ if (updatedVectorOf(node)) {
1047
+ whenRead(vectorReads(vector), () => draw(node, vector));
1048
+ }
1049
+ }
1050
+ for (const flag of pending.values()) {
1051
+ setConstant(codegen, flag, 0);
1052
+ }
1053
+ // Each dep-driven effect checks its deps when it runs, each in turn.
1054
+ for (const check of lowering.effectFunctions.checks) {
1055
+ builder.abx('EFFECT', 0, check);
1056
+ }
1057
+ // The first mount effect, then each one after a mount effect that set state.
1058
+ if (mountNext) {
1059
+ const { mounts } = lowering.effectFunctions;
1060
+ const queued = output.mountEffects.flatMap((_, index) => index === 0 || mountUpdates(output.mountEffects[index - 1])
1061
+ ? [index]
1062
+ : []);
1063
+ for (const index of queued) {
1064
+ codegen.scoped(() => {
1065
+ const skip = builder.label();
1066
+ const next = builder.register('int');
1067
+ const isNext = builder.register('bool');
1068
+ builder.abx('GET32', next.index, mountNext.index);
1069
+ builder.abc('EQ', isNext.index, next.index, codegen.load('int', index + 1).index);
1070
+ builder.branch('JF', skip, isNext);
1071
+ builder.abx('EFFECT', 0, mounts[index]);
1072
+ builder.place(skip);
1073
+ });
1074
+ }
1075
+ setConstant(codegen, mountNext, 0);
1076
+ }
1077
+ builder.place(end);
1078
+ return builder.finish();
1079
+ }
1080
+ /**
1081
+ * Toggles the request bit, so the update runs after a function that set state, even when no value changed.
1082
+ *
1083
+ * @param codegen The function's codegen.
1084
+ * @param lowering The program being lowered.
1085
+ */
1086
+ function requestUpdate(codegen, lowering) {
1087
+ const { requested } = lowering;
1088
+ if (!requested) {
1089
+ return;
1090
+ }
1091
+ const { builder } = codegen;
1092
+ codegen.scoped(() => {
1093
+ const flag = builder.register('bool');
1094
+ builder.abx('GET32', flag.index, requested.index);
1095
+ builder.abc('NOT', flag.index, flag.index);
1096
+ builder.abx('SET32', flag.index, requested.index);
1097
+ });
1098
+ }
1099
+ /**
1100
+ * A handler's function.
1101
+ *
1102
+ * @param handler The handler.
1103
+ * @param lowering The program being lowered.
1104
+ *
1105
+ * @returns The function.
1106
+ */
1107
+ function handlerBody(handler, lowering) {
1108
+ const builder = new FunctionBuilder(handler.event, `handler ${handler.name}`);
1109
+ // A row's handler is entered with its row, in its first register.
1110
+ const row = handler.inRow ? builder.reserved('int') : undefined;
1111
+ const codegen = new Codegen(builder, lowering.slots, {
1112
+ input: handler.input,
1113
+ row,
1114
+ });
1115
+ if (handler.test) {
1116
+ return builder.finish(0, codegen.condition(handler.test));
1117
+ }
1118
+ if (handler.fade) {
1119
+ startPressFade(codegen, handler.fade, lowering.slots.animations);
1120
+ }
1121
+ const end = builder.label();
1122
+ if (handler.gesture) {
1123
+ keepGesture(codegen, handler.gesture, 'before', end, lowering);
1124
+ }
1125
+ codegen.statements(handler.callback.body);
1126
+ if (handler.callback.updatesState) {
1127
+ requestUpdate(codegen, lowering);
1128
+ }
1129
+ if (handler.gesture) {
1130
+ keepGesture(codegen, handler.gesture, 'after', end, lowering);
1131
+ }
1132
+ builder.place(end);
1133
+ return builder.finish(row ? 1 : 0);
1134
+ }
1135
+ /**
1136
+ * What a PanResponder event's handler keeps of the gesture around the app's callback: the grant
1137
+ * anchors it, unless it is already granted; release and terminate clear it after the callback; those and move
1138
+ * do nothing unless it is granted.
1139
+ *
1140
+ * @param codegen The handler's codegen.
1141
+ * @param gesture The responder's gesture state, and the handler's role.
1142
+ * @param when Before the callback, or after it.
1143
+ * @param end The end of the handler, where it returns.
1144
+ * @param lowering The program being lowered.
1145
+ */
1146
+ function keepGesture(codegen, gesture, when, end, lowering) {
1147
+ const { builder } = codegen;
1148
+ const slots = lowering.slots.gestures.get(gesture.statePrefix);
1149
+ const { role } = gesture;
1150
+ codegen.scoped(() => {
1151
+ if (when === 'before' && role !== 'reject') {
1152
+ const granted = codegen.get(slots.granted);
1153
+ builder.branch(role === 'grant' ? 'JT' : 'JF', end, granted);
1154
+ }
1155
+ if (when === 'before' && role === 'grant') {
1156
+ codegen.set(slots.granted, codegen.load('bool', 1));
1157
+ const fields = [
1158
+ [slots.baseDeltaX, EventField.dx],
1159
+ [slots.baseDeltaY, EventField.dy],
1160
+ [slots.x0, EventField.x],
1161
+ [slots.y0, EventField.y],
1162
+ ];
1163
+ for (const [slot, field] of fields) {
1164
+ const value = builder.register('int');
1165
+ builder.abc('EVT', value.index, field);
1166
+ codegen.set(slot, value);
1167
+ }
1168
+ }
1169
+ if (when === 'after' && (role === 'release' || role === 'terminate')) {
1170
+ codegen.set(slots.granted, codegen.load('bool', 0));
1171
+ const zero = codegen.load('int', 0);
1172
+ codegen.set(slots.baseDeltaX, zero);
1173
+ codegen.set(slots.baseDeltaY, zero);
1174
+ }
1175
+ });
1176
+ }
1177
+ /**
1178
+ * A setTimeout or setInterval callback's function.
1179
+ *
1180
+ * @param name The callback's name.
1181
+ * @param callback The callback.
1182
+ * @param lowering The program being lowered.
1183
+ *
1184
+ * @returns The function.
1185
+ */
1186
+ function timerBody(name, callback, lowering) {
1187
+ const builder = new FunctionBuilder(FunctionKind.timer, `timer ${name}`);
1188
+ const codegen = new Codegen(builder, lowering.slots);
1189
+ codegen.statements(callback.body);
1190
+ if (callback.updatesState) {
1191
+ requestUpdate(codegen, lowering);
1192
+ }
1193
+ return builder.finish();
1194
+ }
1195
+ /**
1196
+ * An animation completion's helper: entered with what it was passed, which the body reads as `finished`.
1197
+ *
1198
+ * @param completion The completion.
1199
+ * @param lowering The program being lowered.
1200
+ *
1201
+ * @returns The function.
1202
+ */
1203
+ function completionBody(completion, lowering) {
1204
+ const builder = new FunctionBuilder(FunctionKind.helper, `completion ${completion.name}`);
1205
+ const finished = builder.reserved('bool');
1206
+ const codegen = new Codegen(builder, lowering.slots, { finished });
1207
+ codegen.statements(completion.body);
1208
+ if (completion.updatesState) {
1209
+ requestUpdate(codegen, lowering);
1210
+ }
1211
+ return builder.finish(1);
1212
+ }
1213
+ /**
1214
+ * The register-stack cells each function's deepest call path takes, its own frame included, as the runtime's
1215
+ * verifier works it out. A function only calls later ones.
1216
+ *
1217
+ * @param functions The functions.
1218
+ *
1219
+ * @returns The deepest.
1220
+ */
1221
+ function stackCells(functions) {
1222
+ const depths = [];
1223
+ for (let index = functions.length - 1; index >= 0; index--) {
1224
+ const { code, types } = functions[index];
1225
+ let deepest = 0;
1226
+ for (let at = 0; at < code.length; at += wordsOf(code[at])) {
1227
+ if ((code[at] & 0xff) === OP.CALL.code) {
1228
+ deepest = Math.max(deepest, depths[code[at] >>> 16]);
1229
+ }
1230
+ }
1231
+ depths[index] = FRAME_CELLS + types.length + deepest;
1232
+ }
1233
+ return Math.max(0, ...depths);
1234
+ }
1235
+ /**
1236
+ * How many of some instructions a function has.
1237
+ *
1238
+ * @param programFunction The function.
1239
+ * @param names The opcodes.
1240
+ *
1241
+ * @returns The count.
1242
+ */
1243
+ function countOps(programFunction, names) {
1244
+ const codes = new Set(names.map(name => OP[name].code));
1245
+ let count = 0;
1246
+ for (let at = 0; at < programFunction.code.length; at += wordsOf(programFunction.code[at])) {
1247
+ count += codes.has(programFunction.code[at] & 0xff) ? 1 : 0;
1248
+ }
1249
+ return count;
1250
+ }
1251
+ /**
1252
+ * An instruction's length, from its first word.
1253
+ *
1254
+ * @param word The word.
1255
+ *
1256
+ * @returns Its length in words.
1257
+ */
1258
+ const wordsOf = (word) => Object.values(OP).find(opcode => opcode.code === (word & 0xff)).words;
1259
+ /**
1260
+ * A dep-driven effect's run: the last run's cleanup, if that run reached it, then the body.
1261
+ *
1262
+ * @param effect The effect.
1263
+ * @param codegen The function's codegen.
1264
+ * @param lowering The program being lowered.
1265
+ */
1266
+ function runEffect(effect, codegen, lowering) {
1267
+ const { builder } = codegen;
1268
+ if (effect.hasCleanup) {
1269
+ const armed = lowering.slots.armed.get(armedFlag(effect.id));
1270
+ const skip = builder.label();
1271
+ codegen.scoped(() => {
1272
+ const flag = builder.register('bool');
1273
+ builder.abx('GET32', flag.index, armed.index);
1274
+ builder.branch('JF', skip, flag);
1275
+ });
1276
+ setConstant(codegen, armed, 0);
1277
+ codegen.statements(effect.cleanup ?? []);
1278
+ builder.place(skip);
1279
+ }
1280
+ codegen.statements(effect.body);
1281
+ }
1282
+ /**
1283
+ * The function a dep-driven effect runs in after an update pass: it copies each dep that changed,
1284
+ * and runs the effect if one did.
1285
+ *
1286
+ * @param effect The effect.
1287
+ * @param lowering The program being lowered.
1288
+ *
1289
+ * @returns The function.
1290
+ */
1291
+ function checkedEffect(effect, lowering) {
1292
+ const builder = new FunctionBuilder(FunctionKind.effect, `effect ${effect.id}`);
1293
+ const end = builder.label();
1294
+ const codegen = new Codegen(builder, lowering.slots, { onReturn: end });
1295
+ const copies = lowering.effects.copies.get(effect);
1296
+ const changed = builder.register('bool');
1297
+ builder.abx('LOADI', changed.index, 0);
1298
+ effect.dependencies.forEach((dependency, index) => {
1299
+ const { slot, type } = copies[index];
1300
+ codegen.scoped(() => {
1301
+ const value = codegen.valueAs(dependency, type);
1302
+ const same = builder.label();
1303
+ builder.branch('JT', same, codegen.same(value, codegen.get(slot)));
1304
+ codegen.set(slot, value);
1305
+ builder.abx('LOADI', changed.index, 1);
1306
+ builder.place(same);
1307
+ });
1308
+ });
1309
+ builder.branch('JF', end, changed);
1310
+ runEffect(effect, codegen, lowering);
1311
+ builder.place(end);
1312
+ return builder.finish();
1313
+ }
1314
+ /**
1315
+ * The function a mount effect runs in, after the first update. One that set
1316
+ * state has the next pass queue the mount effect after it; any other queues it itself.
1317
+ *
1318
+ * @param index The mount effect's place in the order.
1319
+ * @param lowering The program being lowered.
1320
+ *
1321
+ * @returns The function.
1322
+ */
1323
+ function mountEffect(index, lowering) {
1324
+ const { output } = lowering.app;
1325
+ const mount = output.mountEffects[index];
1326
+ const builder = new FunctionBuilder(FunctionKind.effect, `mount effect ${index}`);
1327
+ const end = builder.label();
1328
+ const codegen = new Codegen(builder, lowering.slots, { onReturn: end });
1329
+ switch (mount.kind) {
1330
+ case 'inline':
1331
+ codegen.statements(mount.callback.body);
1332
+ break;
1333
+ case 'call': {
1334
+ const called = output.effectFunctions.find(effectFunction => effectFunction.kind === 'mount' && effectFunction.name === mount.name);
1335
+ codegen.statements(called?.kind === 'mount' ? called.body : []);
1336
+ break;
1337
+ }
1338
+ case 'depEffect':
1339
+ runEffect(mount.effect, codegen, lowering);
1340
+ break;
1341
+ }
1342
+ builder.place(end);
1343
+ // A dep-driven effect keeps a copy of each dep, taken after it ran.
1344
+ if (mount.kind === 'depEffect') {
1345
+ const copies = lowering.effects.copies.get(mount.effect);
1346
+ mount.effect.dependencies.forEach((dependency, dependencyIndex) => codegen.scoped(() => codegen.set(copies[dependencyIndex].slot, codegen.valueAs(dependency, copies[dependencyIndex].type))));
1347
+ }
1348
+ const hasNext = index + 1 < output.mountEffects.length;
1349
+ if (mountUpdates(mount)) {
1350
+ requestUpdate(codegen, lowering);
1351
+ if (hasNext) {
1352
+ setConstant(codegen, lowering.effects.mountNext, index + 2);
1353
+ }
1354
+ }
1355
+ else if (hasNext) {
1356
+ builder.abx('EFFECT', 0, lowering.effectFunctions.mounts[index + 1]);
1357
+ }
1358
+ return builder.finish();
1359
+ }
1360
+ /**
1361
+ * Appends a list's first items: a missing field is 0 or "", and a whole
1362
+ * number field is the value rounded.
1363
+ *
1364
+ * @param list The list.
1365
+ * @param codegen The boot function's codegen.
1366
+ * @param lowering The program being lowered.
1367
+ */
1368
+ function appendInitialItems(list, codegen, lowering) {
1369
+ const { builder } = codegen;
1370
+ const { fields } = list.struct;
1371
+ for (const item of list.items) {
1372
+ codegen.scoped(() => {
1373
+ const row = builder.consecutive(fields.map(field => (field.kind === 'string' ? 'string' : field.kind)));
1374
+ fields.forEach((field, index) => {
1375
+ const value = item[field.key];
1376
+ if (field.kind === 'string') {
1377
+ builder.abx('LOADS', row[index].index, lowering.slots.tables.string(String(value ?? '')));
1378
+ return;
1379
+ }
1380
+ const number = Number(value) || 0;
1381
+ codegen.scoped(() => builder.abc('MOVE', row[index].index, codegen.load(field.kind, field.kind === 'float' ? number : Math.round(number)).index));
1382
+ });
1383
+ builder.abx('APPEND', row[0].index, lowering.slots.lists.get(list).slot.index);
1384
+ });
1385
+ }
1386
+ }
1387
+ /**
1388
+ * The boot function: the values worked out from the panel size, in double precision, and
1389
+ * each list's first items.
1390
+ *
1391
+ * @param bootSlots The values.
1392
+ * @param lowering The program being lowered.
1393
+ *
1394
+ * @returns The function, or null when the app has none.
1395
+ */
1396
+ function bootFunction(bootSlots, lowering) {
1397
+ const lists = lowering.app.state.filter((state) => state.kind === 'list' && state.items.length > 0);
1398
+ // A slot read only by a state's start is among bootSlots.
1399
+ if (!bootSlots.length && !lists.length) {
1400
+ return null;
1401
+ }
1402
+ const builder = new FunctionBuilder(FunctionKind.boot, 'the boot values');
1403
+ const codegen = new Codegen(builder, lowering.slots, { inDoubles: true });
1404
+ for (const list of lists) {
1405
+ appendInitialItems(list, codegen, lowering);
1406
+ }
1407
+ for (const bootSlot of bootSlots) {
1408
+ const slot = lowering.slots.boot.get(bootSlot);
1409
+ const { initializer } = bootSlot;
1410
+ codegen.scoped(() => {
1411
+ if (initializer.kind === 'screen') {
1412
+ const size = builder.register('int');
1413
+ builder.abx('SCREEN', size.index, initializer.dimension === 'width' ? 0 : 1);
1414
+ codegen.set(slot, size);
1415
+ }
1416
+ else {
1417
+ codegen.set(slot, codegen.value(initializer.expression));
1418
+ }
1419
+ });
1420
+ }
1421
+ // A state that starts at a value worked out at boot, after every value it can read.
1422
+ for (const state of lowering.app.state) {
1423
+ if (state.kind !== 'scalar' || !state.bootInitial)
1424
+ continue;
1425
+ const { bootInitial } = state;
1426
+ codegen.scoped(() => codegen.set(lowering.slots.states.get(state), codegen.value({
1427
+ kind: 'boot',
1428
+ slot: bootInitial,
1429
+ type: bootInitial.type,
1430
+ })));
1431
+ }
1432
+ return builder.finish();
1433
+ }
1434
+ /**
1435
+ * The keyboard table: setKeyboardConfig's look and layout, each size and key field cut to the bytes the engine's
1436
+ * ERKeyboardConfig keeps it in.
1437
+ *
1438
+ * @param keyboard The keyboard.
1439
+ * @param tables The program's tables.
1440
+ *
1441
+ * @returns The table.
1442
+ */
1443
+ function keyboardTable(keyboard, tables) {
1444
+ const byte = (value) => (value ?? 0) & 0xff;
1445
+ const string = (text) => text == null ? NONE : tables.string(text);
1446
+ return {
1447
+ layers: (keyboard.layers ?? []).map(layer => layer.map(row => row.map(key => ({
1448
+ label: string(key.label),
1449
+ text: string(key.text),
1450
+ type: ENGINE_VALUES.get(KEY_TYPES[key.kind]),
1451
+ layer: byte(key.layer),
1452
+ span: byte(key.span),
1453
+ highlight: byte(key.highlightLayer ?? NEVER_HIGHLIGHTED),
1454
+ })))),
1455
+ rowHeight: (keyboard.rowHeight ?? 0) & 0xffff,
1456
+ gridColumns: byte(keyboard.gridColumns),
1457
+ keyGap: byte(keyboard.keyGap),
1458
+ keyRadius: byte(keyboard.keyRadius),
1459
+ fontSize: byte(keyboard.fontSize),
1460
+ panelColor: keyboard.panelColor ?? 0,
1461
+ keyColor: keyboard.keyColor ?? 0,
1462
+ keyActiveColor: keyboard.keyActiveColor ?? 0,
1463
+ labelColor: keyboard.labelColor ?? 0,
1464
+ };
1465
+ }
1466
+ /*----------------------------------------------------------------------------------------------------------------------
1467
+ - Program
1468
+ ---------------------------------------------------------------------------------------------------------------------*/
1469
+ /**
1470
+ * Lowers an app to a program for one panel.
1471
+ *
1472
+ * @param app The lowered app.
1473
+ * @param options The compile's options: the panel, and the string cap.
1474
+ *
1475
+ * @returns The program.
1476
+ */
1477
+ export function lowerPackage(app, options) {
1478
+ const { screen } = options;
1479
+ const tables = new ProgramTables();
1480
+ const lowering = {
1481
+ app,
1482
+ ...planSlots(app, tables, options.caps),
1483
+ images: new Set(app.images.map(image => image.name)),
1484
+ handlers: new Map(),
1485
+ bindings: [],
1486
+ templates: [],
1487
+ effectFunctions: { checks: [], mounts: [] },
1488
+ };
1489
+ const { output } = app;
1490
+ // A row's handlers are compared by their code before the functions are numbered, so each timer they start
1491
+ // stands in by its own place until then.
1492
+ output.timerFunctions.forEach((timer, index) => lowering.slots.timerFunctions.set(timer.name, index));
1493
+ // A root the app's tree fills. The runtime sizes it to the real panel.
1494
+ const nodes = [
1495
+ {
1496
+ type: ENGINE_VALUES.get('ER_NODE_VIEW'),
1497
+ children: 1,
1498
+ props: tables.propSet([]),
1499
+ handle: NONE,
1500
+ bindings: 0,
1501
+ bindingCount: 0,
1502
+ },
1503
+ ];
1504
+ templateNodes(app.root, lowering, nodes);
1505
+ rowTemplates(lowering);
1506
+ // Every row is built, whether the list holds it or not.
1507
+ const built = [
1508
+ ...nodes,
1509
+ ...lowering.pools.flatMap(pool => pool.templates.flatMap(template => lowering.templates[template - 1].nodes)),
1510
+ ];
1511
+ const nodeCount = built.length;
1512
+ const vectorType = ENGINE_VALUES.get('ER_NODE_VECTOR');
1513
+ const vectorNodes = built.filter(node => node.type === vectorType).length;
1514
+ if (nodeCount > MAX_U16) {
1515
+ 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.');
1516
+ }
1517
+ // Handlers first, as the bindings number them, then the timer callbacks, the effects, and the boot and
1518
+ // update functions. Each is numbered before any code is written, since code names them.
1519
+ let next = lowering.handlers.size;
1520
+ for (const timer of output.timerFunctions) {
1521
+ lowering.slots.timerFunctions.set(timer.name, next++);
1522
+ }
1523
+ lowering.effectFunctions = {
1524
+ checks: output.dependencyEffects.map(() => next++),
1525
+ mounts: output.mountEffects.map(() => next++),
1526
+ };
1527
+ // Then the animations' done functions, and the completions they and the rest call, after every caller.
1528
+ const { animations } = lowering.slots;
1529
+ animations.number(next, next + animations.doneFunctions.size);
1530
+ const functions = [
1531
+ ...[...lowering.handlers.values()].map(handler => handlerBody(handler, lowering)),
1532
+ ...output.timerFunctions.map(timer => timerBody(timer.name, timer.callback, lowering)),
1533
+ ...output.dependencyEffects.map(effect => checkedEffect(effect, lowering)),
1534
+ ...output.mountEffects.map((_, index) => mountEffect(index, lowering)),
1535
+ ...doneFunctions(animations, builder => new Codegen(builder, lowering.slots)),
1536
+ ...[...animations.completions.values()].map(completion => completionBody(completion, lowering)),
1537
+ ];
1538
+ const boot = bootFunction(app.boot.slots, lowering);
1539
+ const update = updateFunction(lowering);
1540
+ const bootIndex = boot ? functions.push(boot) - 1 : NONE;
1541
+ const updateIndex = update ? functions.push(update) - 1 : NONE;
1542
+ // A completion that arrives while a function runs waits in the queue: each running tree's, and each one a
1543
+ // single function's starts and stops can end at once.
1544
+ if (animations.entries) {
1545
+ const ends = Math.max(0, ...functions.map(programFunction => countOps(programFunction, ['ASTART', 'AVSET', 'ASTOP'])));
1546
+ lowering.slots.arena.eventQueue(animations.entries + 2 * ends);
1547
+ }
1548
+ const { regions, bytes } = lowering.slots.arena.regions(stackCells(functions));
1549
+ // Host values, by name, for erb_input_find().
1550
+ const inputs = app.state
1551
+ .filter((state) => state.kind === 'scalar' && state.host)
1552
+ .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)
1553
+ .map(state => ({
1554
+ name: tables.string(state.name),
1555
+ slot: lowering.slots.states.get(state).index,
1556
+ }));
1557
+ return {
1558
+ flags: FLAG_DEBUG,
1559
+ panels: [
1560
+ {
1561
+ width: screen.width,
1562
+ height: screen.height,
1563
+ check: lowerCheck(app.boot.assumptions, screen),
1564
+ arenaBytes: bytes,
1565
+ nodeCount,
1566
+ rootTemplate: 0,
1567
+ bootFunction: bootIndex,
1568
+ updateFunction: updateIndex,
1569
+ },
1570
+ ],
1571
+ needs: [
1572
+ ...(vectorNodes
1573
+ ? [{ resource: Resource.vectorNodes, amount: vectorNodes }]
1574
+ : []),
1575
+ // Each animated value runs one engine animation at a time.
1576
+ ...(animations.values.size
1577
+ ? [
1578
+ {
1579
+ resource: Resource.animationValues,
1580
+ amount: animations.values.size,
1581
+ },
1582
+ { resource: Resource.animations, amount: animations.values.size },
1583
+ ]
1584
+ : []),
1585
+ ...(app.images.length
1586
+ ? [{ resource: Resource.images, amount: app.images.length }]
1587
+ : []),
1588
+ ],
1589
+ strings: tables.strings,
1590
+ const32: tables.const32,
1591
+ const64: tables.const64,
1592
+ regions,
1593
+ slots: lowering.slots.arena.slots,
1594
+ enums: [...lowering.slots.enums.values()].map(({ values }) => values.map(value => tables.string(value))),
1595
+ rows: lowering.rows,
1596
+ propSets: tables.propSets,
1597
+ templates: [{ kind: TemplateKind.root, nodes }, ...lowering.templates],
1598
+ bindings: lowering.bindings,
1599
+ functions,
1600
+ animations: animations.animations,
1601
+ inputs,
1602
+ interpolations: animations.interpolations,
1603
+ tapes: lowering.slots.vectors.tapes,
1604
+ keyboard: app.keyboard ? keyboardTable(app.keyboard, tables) : null,
1605
+ };
1606
+ }