embedded-react 0.20.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 (74) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +1 -0
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +16 -46
  5. package/aot/compiler/animations.mjs +299 -57
  6. package/aot/compiler/boot.mjs +27 -2
  7. package/aot/compiler/check.mjs +61 -9
  8. package/aot/compiler/collect.mjs +516 -136
  9. package/aot/compiler/contexts.mjs +391 -0
  10. package/aot/compiler/control-flow.mjs +276 -117
  11. package/aot/compiler/custom-hooks.mjs +686 -0
  12. package/aot/compiler/elements/button.mjs +182 -0
  13. package/aot/compiler/elements/image-background.mjs +76 -0
  14. package/aot/compiler/elements/image.mjs +2 -1
  15. package/aot/compiler/elements/props.mjs +38 -3
  16. package/aot/compiler/elements/rewrite.mjs +118 -0
  17. package/aot/compiler/elements/section-list.mjs +370 -0
  18. package/aot/compiler/expressions.mjs +1351 -97
  19. package/aot/compiler/handlers.mjs +1761 -365
  20. package/aot/compiler/helper-values.mjs +312 -0
  21. package/aot/compiler/ir/nodes.mjs +40 -1
  22. package/aot/compiler/ir/reads.mjs +206 -5
  23. package/aot/compiler/ir/text.mjs +5 -1
  24. package/aot/compiler/ir/types.mjs +12 -0
  25. package/aot/compiler/kept-states.mjs +177 -0
  26. package/aot/compiler/list-items.mjs +226 -0
  27. package/aot/compiler/list-order.mjs +586 -0
  28. package/aot/compiler/list-split.mjs +259 -0
  29. package/aot/compiler/loops.mjs +582 -0
  30. package/aot/compiler/lower.mjs +191 -53
  31. package/aot/compiler/native-files.mjs +439 -0
  32. package/aot/compiler/native-header.mjs +335 -0
  33. package/aot/compiler/native-modules.mjs +1173 -0
  34. package/aot/compiler/nodes.mjs +28 -22
  35. package/aot/compiler/options.mjs +3 -2
  36. package/aot/compiler/out.mjs +14 -1
  37. package/aot/compiler/package/animations.mjs +133 -23
  38. package/aot/compiler/package/assemble.mjs +2 -4
  39. package/aot/compiler/package/bytecode.mjs +37 -8
  40. package/aot/compiler/package/checks.mjs +4 -0
  41. package/aot/compiler/package/codegen.mjs +870 -31
  42. package/aot/compiler/package/enums.mjs +10 -0
  43. package/aot/compiler/package/format.mjs +12 -1
  44. package/aot/compiler/package/lower.mjs +658 -161
  45. package/aot/compiler/package/string-caps.mjs +515 -0
  46. package/aot/compiler/package/tables.mjs +24 -0
  47. package/aot/compiler/package/writer.mjs +22 -0
  48. package/aot/compiler/parse.mjs +3 -1
  49. package/aot/compiler/record-shapes.mjs +246 -0
  50. package/aot/compiler/records.mjs +654 -0
  51. package/aot/compiler/reducers.mjs +272 -0
  52. package/aot/compiler/static-eval.mjs +315 -7
  53. package/aot/compiler/style-text.mjs +18 -3
  54. package/aot/compiler/svg.mjs +7 -4
  55. package/aot/compiler/switch-cases.mjs +198 -0
  56. package/aot/compiler/tagged-records.mjs +450 -0
  57. package/aot/compiler/typing.mjs +307 -0
  58. package/aot/compiler/updaters.mjs +320 -0
  59. package/aot/compiler/window-dimensions.mjs +94 -0
  60. package/aot/compiler/worked-values.mjs +319 -0
  61. package/aot/demo-file.mjs +30 -0
  62. package/aot/style-map.mjs +50 -2
  63. package/build.mjs +9 -1
  64. package/cli.mjs +44 -1
  65. package/hotreload/pack-split.mjs +29 -40
  66. package/pack-container.mjs +9 -1
  67. package/package.json +1 -1
  68. package/sim/embedded-react.wasm +0 -0
  69. package/sim-server.mjs +22 -22
  70. package/src/embedded-react/Dimensions.js +37 -0
  71. package/src/embedded-react/SectionList.js +1 -3
  72. package/src/embedded-react/index.d.ts +83 -3
  73. package/src/embedded-react/index.js +2 -0
  74. package/src/embedded-react/nativeModule.js +462 -0
@@ -32,14 +32,17 @@
32
32
  * pass; a row shows while the list holds it. Rows whose nodes and handlers
33
33
  * are the same share a template, and a row handler reads its item through the row it was built for.
34
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
+ *
35
40
  * A PanResponder is a handler for each responder event and a query function for each should-set predicate,
36
41
  * bound on each node that spreads it. Its gesture state is slots, kept by its grant, release and terminate
37
42
  * handlers, and a callback reads the gesture through them and EVT.
38
43
  *
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,
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,
43
46
  * each in turn. The mount effects run one after another, after the first pass; one that set state has the
44
47
  * pass after it queue the next.
45
48
  */
@@ -48,23 +51,28 @@
48
51
  ---------------------------------------------------------------------------------------------------------------------*/
49
52
  import { aotError, constantText, ENGINE_STRING_MAX, locateError, } from '../diagnostics.mjs';
50
53
  import { hasRuntimeProps, isStateDriven, nodesOf, branchElements, stateDrivenVectorOf, updatedVectorOf, } from '../ir/nodes.mjs';
51
- import { nodeReads, vectorReads } from '../ir/reads.mjs';
54
+ import { expressionReads, listReads, nodeReads, vectorReads, workedReads, } from '../ir/reads.mjs';
52
55
  import { armedFlag } from '../ir/functions.mjs';
53
56
  import { AnimationPlan, doneFunctions, startPressFade } from './animations.mjs';
54
57
  import { Arena } from './arena.mjs';
55
58
  import { FunctionBuilder, OP } from './bytecode.mjs';
56
59
  import { internedStates } from './enums.mjs';
60
+ import { longestLiteral, stringCaps } from './string-caps.mjs';
57
61
  import { Codegen, notYet } from './codegen.mjs';
58
62
  import { BindingKind, ENGINE_VALUES, EventField, FLAG_DEBUG, FRAME_CELLS, FunctionKind, MAX_SPANS, NONE, Resource, SlotFlag, TemplateKind, ValueType, } from './format.mjs';
59
63
  import { abiProp, constantPropEntry, floatBits, stringPropEntry, } from './props.mjs';
60
64
  import { ProgramTables } from './tables.mjs';
65
+ import { itemValueAt, rowEntries } from '../list-items.mjs';
61
66
  import { commitDrawing, VectorPlan } from './vectors.mjs';
62
67
  import { lowerCheck } from './checks.mjs';
68
+ import { MAX_NATIVE_EVENTS } from '../native-modules.mjs';
63
69
  /*----------------------------------------------------------------------------------------------------------------------
64
70
  - Constants
65
71
  ---------------------------------------------------------------------------------------------------------------------*/
66
72
  /** The most a u16 count or size in the format holds: a row's bytes, a panel's nodes, the row fields. */
67
73
  const MAX_U16 = 0xffff;
74
+ /** BUILD's instance operand when the template is no list row's. */
75
+ const NO_REGISTER = 0xff;
68
76
  /** The most fields a row has: ROWGET names one in a byte. */
69
77
  const MAX_ROW_FIELDS = 255;
70
78
  /** Key kind → its ERKeyboardKey type. */
@@ -109,44 +117,57 @@ const isSetOnce = (node) => !isStateDriven(node) && (hasRuntimeProps(node) || no
109
117
  - Slots
110
118
  ---------------------------------------------------------------------------------------------------------------------*/
111
119
  /**
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.
120
+ * Every string local a statement list declares.
136
121
  *
137
122
  * @param statements The statements.
138
- * @param found Collects each local's name and cap.
123
+ * @param found Collects each local's name.
139
124
  */
140
125
  function stringLocals(statements, found) {
141
126
  for (const statement of statements) {
142
127
  if (statement.kind === 'declareLocal' &&
143
128
  statement.initializer.type.kind === 'string') {
144
- found.set(statement.name, Math.max(found.get(statement.name) ?? 0, statement.stringCapacity - 1));
129
+ found.add(statement.name);
145
130
  }
146
131
  else if (statement.kind === 'if') {
147
132
  stringLocals(statement.consequent, found);
148
133
  stringLocals(statement.alternate ?? [], found);
149
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
+ }
150
171
  }
151
172
  }
152
173
  /**
@@ -164,6 +185,13 @@ function updateVectors(statements, found) {
164
185
  updateVectors(statement.consequent, found);
165
186
  updateVectors(statement.alternate ?? [], found);
166
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
+ }
167
195
  }
168
196
  }
169
197
  /**
@@ -184,6 +212,13 @@ function statesSet(statements, found) {
184
212
  statesSet(statement.consequent, found);
185
213
  statesSet(statement.alternate ?? [], found);
186
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
+ }
187
222
  }
188
223
  }
189
224
  /**
@@ -204,6 +239,19 @@ function depType(dependency) {
204
239
  return 'int';
205
240
  }
206
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
+ };
207
255
  /**
208
256
  * Whether a mount effect sets state, so an update runs after it.
209
257
  *
@@ -230,6 +278,7 @@ function bodies(app) {
230
278
  ? [handler.event.callback.body]
231
279
  : []),
232
280
  ...output.timerFunctions.map(timer => timer.callback.body),
281
+ ...output.nativeEventHandlers.map(handler => handler.callback.body),
233
282
  ...output.effectFunctions.map(effectFunction => effectFunction.kind === 'mount'
234
283
  ? effectFunction.body
235
284
  : effectFunction.kind === 'cleanup'
@@ -267,24 +316,49 @@ const stateSlotOf = (state, slots) => state.kind === 'list'
267
316
  */
268
317
  const firstNode = (element) => element.kind === 'component' ? firstNode(element.root) : element.node;
269
318
  /**
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.
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.
272
321
  *
273
322
  * @param element The element.
274
- * @param found Collects the pools.
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.
275
326
  */
276
- function poolsOf(element, found) {
327
+ function planTree(element, within, plan, arena) {
277
328
  if (element.kind === 'component') {
278
- poolsOf(element.root, found);
329
+ planTree(element.root, within, plan, arena);
279
330
  return;
280
331
  }
281
332
  const { node } = element;
333
+ if (within) {
334
+ plan.places.set(node, within);
335
+ }
282
336
  node.children.forEach((child, index) => {
337
+ const after = node.children.slice(index + 1);
283
338
  if (child.kind === 'element') {
284
- poolsOf(child.element, found);
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));
285
343
  }
286
344
  else if (child.kind === 'conditional') {
287
- branchElements(child).forEach(branch => poolsOf(branch, found));
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));
288
362
  }
289
363
  else {
290
364
  for (const row of child.rows) {
@@ -292,25 +366,54 @@ function poolsOf(element, found) {
292
366
  if (nested) {
293
367
  notYetAt('a list inside a list row', nested.location);
294
368
  }
369
+ if (within) {
370
+ nodesOf(row).forEach(rowNode => plan.places.set(rowNode, within));
371
+ }
295
372
  }
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({
373
+ plan.pools.push({
305
374
  list: child.list,
306
375
  rows: child.rows,
307
376
  parent: node,
308
- anchor: after.length ? firstNode(after[0]) : null,
377
+ after,
378
+ anchors: [],
379
+ within,
309
380
  templates: [],
310
381
  });
311
382
  }
312
383
  });
313
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
+ }
314
417
  /**
315
418
  * Plans every slot the program uses, then lays the arena out.
316
419
  *
@@ -321,7 +424,6 @@ function poolsOf(element, found) {
321
424
  * @returns The slots, the node handles, and the bookkeeping bits.
322
425
  */
323
426
  function planSlots(app, tables, caps) {
324
- const { listStrCap: listStringCapacity } = caps;
325
427
  const { output } = app;
326
428
  const arena = new Arena();
327
429
  const animations = new AnimationPlan(app, arena);
@@ -333,7 +435,9 @@ function planSlots(app, tables, caps) {
333
435
  refs: new Map(),
334
436
  boot: new Map(),
335
437
  stringLocals: new Map(),
438
+ nativeStrings: new Map(),
336
439
  enums: new Map(),
440
+ kept: new Map(),
337
441
  hoisted: new Map(),
338
442
  armed: new Map(),
339
443
  timerFunctions: new Map(),
@@ -348,6 +452,8 @@ function planSlots(app, tables, caps) {
348
452
  values,
349
453
  });
350
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);
351
457
  // State, each with a dirty bit when a node reads it.
352
458
  for (const state of app.state) {
353
459
  if (state.kind === 'list') {
@@ -359,7 +465,7 @@ function planSlots(app, tables, caps) {
359
465
  const slot = interned
360
466
  ? Object.assign(arena.slot(ValueType.enum, 0), { aux: interned.set })
361
467
  : state.slotKind === 'string'
362
- ? arena.slot(ValueType.string, tables.string(String(initial)), listStringCapacity - 1)
468
+ ? arena.slot(ValueType.string, tables.string(String(initial)), stringCap.state(state))
363
469
  : state.slotKind === 'i64'
364
470
  ? arena.slot(ValueType.int64, tables.constant64(BigInt(Math.trunc(Number(initial)))))
365
471
  : state.slotKind === 'float'
@@ -371,6 +477,19 @@ function planSlots(app, tables, caps) {
371
477
  }
372
478
  slots.states.set(state, slot);
373
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
+ }
374
493
  // A list is a pool of rows, empty at load; the boot function appends its first items. Each row field is
375
494
  // 4-aligned, and a string field holds its cap and a terminator.
376
495
  const rows = [];
@@ -381,18 +500,24 @@ function planSlots(app, tables, caps) {
381
500
  if (!state.struct.fields.length) {
382
501
  notYet(`list state "${state.name}", whose items have no fields`);
383
502
  }
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.');
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).');
386
506
  }
387
507
  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;
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;
392
517
  return entry;
393
518
  });
394
519
  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.');
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.');
396
521
  }
397
522
  const slot = arena.list(rows.length, size, state.capacity);
398
523
  rows.push({ size, fields });
@@ -404,7 +529,7 @@ function planSlots(app, tables, caps) {
404
529
  .filter(field => field.kind === 'string')
405
530
  .map(field => [
406
531
  field.key,
407
- arena.slot(ValueType.string, undefined, listStringCapacity - 1),
532
+ arena.slot(ValueType.string, undefined, stringCap.field(state, field.key)),
408
533
  ]));
409
534
  slots.lists.set(state, { slot, buffers });
410
535
  }
@@ -438,7 +563,7 @@ function planSlots(app, tables, caps) {
438
563
  for (const declaration of output.effectDeclarations) {
439
564
  if (declaration.kind === 'local') {
440
565
  slots.hoisted.set(declaration.name, declaration.slotKind === 'string'
441
- ? arena.slot(ValueType.string, undefined, listStringCapacity - 1)
566
+ ? arena.slot(ValueType.string, undefined, stringCap.local(declaration.name))
442
567
  : arena.slot(declaration.slotKind === 'i64'
443
568
  ? ValueType.int64
444
569
  : declaration.slotKind === 'float'
@@ -456,20 +581,35 @@ function planSlots(app, tables, caps) {
456
581
  return {
457
582
  type,
458
583
  slot: type === 'string'
459
- ? arena.slot(ValueType.string, undefined, listStringCapacity - 1)
584
+ ? arena.slot(ValueType.string, undefined, stringCap.value(dependency))
460
585
  : arena.slot(ValueType[type]),
461
586
  };
462
587
  }));
463
588
  }
464
- const locals = new Map();
589
+ const locals = new Set();
465
590
  for (const body of bodies(app)) {
466
591
  stringLocals(body, locals);
467
592
  }
468
- for (const [name, capacity] of locals) {
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) {
469
599
  if (!slots.hoisted.has(name)) {
470
- slots.stringLocals.set(name, arena.slot(ValueType.string, undefined, capacity));
600
+ slots.stringLocals.set(name, arena.slot(ValueType.string, undefined, stringCap.local(name)));
471
601
  }
472
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
+ }
473
613
  const nodes = nodesOf(app.root);
474
614
  // A <TextInput>'s onChangeText reads the input's text, through its handle.
475
615
  const handles = new Map();
@@ -493,12 +633,25 @@ function planSlots(app, tables, caps) {
493
633
  isSetOnce(node) ||
494
634
  readsInput(node) ||
495
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
+ ]));
496
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.
497
- const pools = [];
498
- poolsOf(app.root, pools);
499
651
  const rowHandles = new Map();
500
652
  for (const pool of pools) {
501
653
  const arrays = [];
654
+ const anchoring = pool.rows.length > 0 && builtUnder.has(firstNode(pool.rows[0]));
502
655
  pool.rows.forEach((rowElement, row) => nodesOf(rowElement).forEach((node, place) => {
503
656
  if (readsInput(node)) {
504
657
  notYetAt('onChangeText in a list row', node.location);
@@ -506,16 +659,27 @@ function planSlots(app, tables, caps) {
506
659
  if (drawnOn.has(node)) {
507
660
  notYetAt('updateVector on a node in a list row', node.location);
508
661
  }
509
- if (reached(node)) {
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)) {
510
664
  arrays[place] ??= arena.slot(ValueType.node, 0, pool.list.capacity);
511
665
  rowHandles.set(node, { array: arrays[place], row });
512
666
  }
513
667
  }));
514
668
  }
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]));
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
+ }
517
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
+ }
518
681
  if (!rowHandles.has(node) &&
682
+ !handles.has(node) &&
519
683
  (reached(node) || builtUnder.has(node) || drawnOn.has(node))) {
520
684
  handles.set(node, arena.slot(ValueType.node));
521
685
  }
@@ -540,7 +704,9 @@ function planSlots(app, tables, caps) {
540
704
  ? handler.callback.updatesState
541
705
  : handler.kind === 'panEvent' && !!handler.event.callback?.updatesState) ||
542
706
  output.timerFunctions.some(timer => timer.callback.updatesState) ||
707
+ output.nativeEventHandlers.some(handler => handler.callback.updatesState) ||
543
708
  output.mountEffects.some(mountUpdates) ||
709
+ output.dependencyEffects.some(setsState) ||
544
710
  completionsOf(app).some(completion => completion.updatesState);
545
711
  const requested = requestsUpdate
546
712
  ? arena.track(arena.slot(ValueType.bool))
@@ -551,25 +717,10 @@ function planSlots(app, tables, caps) {
551
717
  nodes.some(node => isStateDriven(node) || isSetOnce(node) || stateDrivenVectorOf(node))
552
718
  ? arena.track(arena.slot(ValueType.bool))
553
719
  : 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
- }
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;
573
724
  // The first mount effect is queued by the first pass.
574
725
  const mountNext = output.mountEffects.length
575
726
  ? arena.slot(ValueType.int, 1)
@@ -577,9 +728,10 @@ function planSlots(app, tables, caps) {
577
728
  if (output.timerFunctions.length) {
578
729
  arena.timerTable(caps.maxTimers);
579
730
  }
580
- // A pass queues each dep-driven effect and the next mount effect, and a mount effect the one after it.
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.
581
733
  if (hasEffects) {
582
- arena.eventQueue(output.dependencyEffects.length + 1);
734
+ arena.eventQueue(2 * output.dependencyEffects.length + 1);
583
735
  }
584
736
  arena.layOut();
585
737
  return {
@@ -588,10 +740,12 @@ function planSlots(app, tables, caps) {
588
740
  rowHandles,
589
741
  rows,
590
742
  pools,
743
+ branchings,
744
+ places,
591
745
  inputText,
592
746
  requested,
593
747
  once,
594
- effects: { copies, pending, realBits, mountNext },
748
+ effects: { copies, checksQueued, mountNext },
595
749
  };
596
750
  }
597
751
  /*----------------------------------------------------------------------------------------------------------------------
@@ -729,9 +883,10 @@ function responderBindings(pan, lowering) {
729
883
  ];
730
884
  }
731
885
  /**
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.
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.
735
890
  *
736
891
  * @param element The element.
737
892
  * @param lowering The program being lowered.
@@ -771,7 +926,7 @@ function templateNodes(element, lowering, nodes, inRow = false) {
771
926
  }
772
927
  children = node.children.flatMap(child => child.kind === 'element'
773
928
  ? [child.element]
774
- : child.kind === 'conditional'
929
+ : child.kind === 'conditional' && child.toggle
775
930
  ? branchElements(child)
776
931
  : []);
777
932
  // A node the update sets starts with no props.
@@ -829,6 +984,52 @@ function rowTemplates(lowering) {
829
984
  });
830
985
  }
831
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
+ }
832
1033
  /*----------------------------------------------------------------------------------------------------------------------
833
1034
  - Functions
834
1035
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -896,23 +1097,132 @@ function nodeHandle(codegen, node, lowering) {
896
1097
  return handle;
897
1098
  }
898
1099
  /**
899
- * Builds every list row, in order, under its parent and before the node after it.
1100
+ * Builds under a parent, before the first anchor that is built: emits the BUILD for each node it may go before.
900
1101
  *
901
1102
  * @param codegen The update function's codegen.
1103
+ * @param parent The parent's handle.
1104
+ * @param anchors What it goes before.
902
1105
  * @param lowering The program being lowered.
1106
+ * @param build Emits the BUILD, before a node.
903
1107
  */
904
- function buildRows(codegen, lowering) {
1108
+ function buildBefore(codegen, parent, anchors, lowering, build) {
905
1109
  const { builder } = codegen;
906
- for (const pool of lowering.pools) {
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();
907
1118
  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))));
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);
914
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));
915
1224
  }
1225
+ return reads;
916
1226
  }
917
1227
  /**
918
1228
  * The dirty bits of a set of slots, as a mask per dirty word.
@@ -930,26 +1240,18 @@ function dirtyMasks(slots) {
930
1240
  return words;
931
1241
  }
932
1242
  /**
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.
1243
+ * Runs `body` only when one of a set of dirty bits is set in this update pass.
934
1244
  *
935
1245
  * @param builder The update function.
936
1246
  * @param slots The slots whose bits guard it.
937
1247
  * @param body Emits what it guards.
938
- * @param pending The pending flags that guard it too.
939
1248
  */
940
- function whenDirty(builder, slots, body, pending = []) {
1249
+ function whenDirty(builder, slots, body) {
941
1250
  const run = builder.label();
942
1251
  const skip = builder.label();
943
1252
  for (const [word, mask] of dirtyMasks(slots)) {
944
1253
  builder.branchIfDirty(word, mask, run);
945
1254
  }
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
1255
  builder.branch('JMP', skip);
954
1256
  builder.place(run);
955
1257
  body();
@@ -966,8 +1268,9 @@ function setConstant(codegen, slot, value) {
966
1268
  codegen.scoped(() => codegen.builder.abx('SET32', codegen.load(slot.type === ValueType.bool ? 'bool' : 'int', value).index, slot.index));
967
1269
  }
968
1270
  /**
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.
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.
971
1274
  *
972
1275
  * @param lowering The program being lowered.
973
1276
  *
@@ -982,16 +1285,21 @@ function updateFunction(lowering) {
982
1285
  const vector = stateDrivenVectorOf(node);
983
1286
  return vector ? [{ node, vector }] : [];
984
1287
  });
985
- if (!updated.length &&
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 &&
986
1293
  !setOnce.length &&
987
1294
  !drawings.length &&
1295
+ !lowering.branchings.length &&
988
1296
  !output.dependencyEffects.length &&
989
1297
  !output.mountEffects.length) {
990
1298
  return null;
991
1299
  }
992
1300
  const builder = new FunctionBuilder(FunctionKind.update, 'the update');
993
1301
  const codegen = new Codegen(builder, lowering.slots);
994
- const { pending, realBits, mountNext } = lowering.effects;
1302
+ const { mountNext } = lowering.effects;
995
1303
  const located = (node, lower) => {
996
1304
  builder.at(node.location);
997
1305
  try {
@@ -1010,49 +1318,121 @@ function updateFunction(lowering) {
1010
1318
  ? [...reads].map(state => stateSlotOf(state, lowering.slots))
1011
1319
  : [];
1012
1320
  if (bits.length && bits.every(slot => slot.flags & SlotFlag.tracked)) {
1013
- whenDirty(builder, bits, lower, bits.flatMap(slot => pending.get(slot) ?? []));
1321
+ whenDirty(builder, bits, lower);
1014
1322
  }
1015
1323
  else {
1016
1324
  lower();
1017
1325
  }
1018
1326
  };
1019
- // A pass only an effect's writes started keeps what they changed for the next one.
1020
1327
  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);
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
+ });
1031
1365
  }
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) {
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) {
1035
1372
  whenDirty(builder, [lowering.once], () => {
1036
- buildRows(codegen, lowering);
1037
- setOnce.forEach(node => located(node, () => setNode(codegen, node, lowering)));
1373
+ rootPools.forEach(pool => buildPool(codegen, pool, lowering));
1374
+ rootSetOnce.forEach(node => located(node, () => setNode(codegen, node, lowering)));
1038
1375
  builtOnce.forEach(({ node, vector }) => draw(node, vector));
1039
1376
  });
1040
1377
  }
1041
- // The nodes, then the drawings.
1378
+ // The nodes, then the drawings, each only while its branch is built.
1042
1379
  for (const node of updated) {
1043
- located(node, () => whenRead(nodeReads(node), () => setNode(codegen, node, lowering)));
1380
+ located(node, () => whenRead(nodeReads(node), () => whileBuilt(codegen, places.get(node), () => setNode(codegen, node, lowering))));
1044
1381
  }
1045
1382
  for (const { node, vector } of drawings) {
1046
1383
  if (updatedVectorOf(node)) {
1047
- whenRead(vectorReads(vector), () => draw(node, vector));
1384
+ whenRead(vectorReads(vector), () => whileBuilt(codegen, places.get(node), () => draw(node, vector)));
1048
1385
  }
1049
1386
  }
1050
- for (const flag of pending.values()) {
1051
- setConstant(codegen, flag, 0);
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);
1052
1420
  }
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);
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
+ });
1056
1436
  }
1057
1437
  // The first mount effect, then each one after a mount effect that set state.
1058
1438
  if (mountNext) {
@@ -1192,6 +1572,66 @@ function timerBody(name, callback, lowering) {
1192
1572
  }
1193
1573
  return builder.finish();
1194
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
+ }
1195
1635
  /**
1196
1636
  * An animation completion's helper: entered with what it was passed, which the body reads as `finished`.
1197
1637
  *
@@ -1274,10 +1714,10 @@ function runEffect(effect, codegen, lowering) {
1274
1714
  builder.branch('JF', skip, flag);
1275
1715
  });
1276
1716
  setConstant(codegen, armed, 0);
1277
- codegen.statements(effect.cleanup ?? []);
1717
+ codegen.body(effect.cleanup ?? []);
1278
1718
  builder.place(skip);
1279
1719
  }
1280
- codegen.statements(effect.body);
1720
+ codegen.body(effect.body);
1281
1721
  }
1282
1722
  /**
1283
1723
  * The function a dep-driven effect runs in after an update pass: it copies each dep that changed,
@@ -1291,8 +1731,14 @@ function runEffect(effect, codegen, lowering) {
1291
1731
  function checkedEffect(effect, lowering) {
1292
1732
  const builder = new FunctionBuilder(FunctionKind.effect, `effect ${effect.id}`);
1293
1733
  const end = builder.label();
1294
- const codegen = new Codegen(builder, lowering.slots, { onReturn: end });
1734
+ // An early `return` still ends at the request.
1735
+ const ran = builder.label();
1736
+ const codegen = new Codegen(builder, lowering.slots, { onReturn: ran });
1295
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
+ }
1296
1742
  const changed = builder.register('bool');
1297
1743
  builder.abx('LOADI', changed.index, 0);
1298
1744
  effect.dependencies.forEach((dependency, index) => {
@@ -1308,6 +1754,10 @@ function checkedEffect(effect, lowering) {
1308
1754
  });
1309
1755
  builder.branch('JF', end, changed);
1310
1756
  runEffect(effect, codegen, lowering);
1757
+ builder.place(ran);
1758
+ if (setsState(effect)) {
1759
+ requestUpdate(codegen, lowering);
1760
+ }
1311
1761
  builder.place(end);
1312
1762
  return builder.finish();
1313
1763
  }
@@ -1355,6 +1805,12 @@ function mountEffect(index, lowering) {
1355
1805
  else if (hasNext) {
1356
1806
  builder.abx('EFFECT', 0, lowering.effectFunctions.mounts[index + 1]);
1357
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
+ }
1358
1814
  return builder.finish();
1359
1815
  }
1360
1816
  /**
@@ -1367,18 +1823,24 @@ function mountEffect(index, lowering) {
1367
1823
  */
1368
1824
  function appendInitialItems(list, codegen, lowering) {
1369
1825
  const { builder } = codegen;
1370
- const { fields } = list.struct;
1826
+ const entries = rowEntries(list.struct);
1371
1827
  for (const item of list.items) {
1372
1828
  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 ?? '')));
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) : ''));
1378
1834
  return;
1379
1835
  }
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));
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));
1382
1844
  });
1383
1845
  builder.abx('APPEND', row[0].index, lowering.slots.lists.get(list).slot.index);
1384
1846
  });
@@ -1413,6 +1875,11 @@ function bootFunction(bootSlots, lowering) {
1413
1875
  builder.abx('SCREEN', size.index, initializer.dimension === 'width' ? 0 : 1);
1414
1876
  codegen.set(slot, size);
1415
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
+ }
1416
1883
  else {
1417
1884
  codegen.set(slot, codegen.value(initializer.expression));
1418
1885
  }
@@ -1502,15 +1969,12 @@ export function lowerPackage(app, options) {
1502
1969
  },
1503
1970
  ];
1504
1971
  templateNodes(app.root, lowering, nodes);
1972
+ branchTemplates(lowering);
1505
1973
  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;
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);
1514
1978
  if (nodeCount > MAX_U16) {
1515
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.');
1516
1980
  }
@@ -1520,6 +1984,36 @@ export function lowerPackage(app, options) {
1520
1984
  for (const timer of output.timerFunctions) {
1521
1985
  lowering.slots.timerFunctions.set(timer.name, next++);
1522
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
+ }
1523
2017
  lowering.effectFunctions = {
1524
2018
  checks: output.dependencyEffects.map(() => next++),
1525
2019
  mounts: output.mountEffects.map(() => next++),
@@ -1530,6 +2024,7 @@ export function lowerPackage(app, options) {
1530
2024
  const functions = [
1531
2025
  ...[...lowering.handlers.values()].map(handler => handlerBody(handler, lowering)),
1532
2026
  ...output.timerFunctions.map(timer => timerBody(timer.name, timer.callback, lowering)),
2027
+ ...subscribed.map(handlers => nativeEventBody(handlers, lowering)),
1533
2028
  ...output.dependencyEffects.map(effect => checkedEffect(effect, lowering)),
1534
2029
  ...output.mountEffects.map((_, index) => mountEffect(index, lowering)),
1535
2030
  ...doneFunctions(animations, builder => new Codegen(builder, lowering.slots)),
@@ -1598,6 +2093,8 @@ export function lowerPackage(app, options) {
1598
2093
  bindings: lowering.bindings,
1599
2094
  functions,
1600
2095
  animations: animations.animations,
2096
+ imports: tables.imports,
2097
+ nativeEvents,
1601
2098
  inputs,
1602
2099
  interpolations: animations.interpolations,
1603
2100
  tapes: lowering.slots.vectors.tapes,