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
@@ -27,7 +27,8 @@ import { attrExpr, collectStyleAssigns, lowerNodeText, collectTextSpans, } from
27
27
  import { at, checkAttributes, checkNoChildren, elementSpec, EVENT_TYPES, withoutPlatformNoOps, } from './elements/props.mjs';
28
28
  import { lowerHandler } from './handlers.mjs';
29
29
  import { emitPanResponder, panSpreadTarget } from './pan-responder.mjs';
30
- import { emitComponent, emitChildren } from './control-flow.mjs';
30
+ import { emitComponent, emitChildren, emitProvider } from './control-flow.mjs';
31
+ import { providedContextOf } from './contexts.mjs';
31
32
  import { emitSvg } from './svg.mjs';
32
33
  import { emitDial } from './elements/dial.mjs';
33
34
  import { emitSwitch } from './elements/switch.mjs';
@@ -35,18 +36,13 @@ import { emitTextInput } from './elements/text-input.mjs';
35
36
  import { emitActivityIndicator } from './elements/activity-indicator.mjs';
36
37
  import { emitModal } from './elements/modal.mjs';
37
38
  import { emitFlatList } from './elements/flat-list.mjs';
39
+ import { emitButton } from './elements/button.mjs';
40
+ import { emitImageBackground } from './elements/image-background.mjs';
41
+ import { emitSectionList } from './elements/section-list.mjs';
38
42
  import { resolveImageAttrs } from './elements/image.mjs';
39
43
  /*----------------------------------------------------------------------------------------------------------------------
40
44
  - Constants
41
45
  ---------------------------------------------------------------------------------------------------------------------*/
42
- // JS-only wrappers with no lowering yet, mapped to the tree to write by hand; "unknown element" would mislead.
43
- const FLOW_A_ONLY_COMPONENTS = {
44
- Button: '<Pressable style={…} onPress={…}><Text style={…}>title</Text></Pressable>.',
45
- ImageBackground: "<View style={…}><Image source={…} style={{position: 'absolute', top: 0, left: 0, " +
46
- 'right: 0, bottom: 0}} />…children…</View>.',
47
- SectionList: '<ScrollView> with the header element and a data.map(…) per section (a section is not ' +
48
- 'one .map, which is why it has no lowering).',
49
- };
50
46
  // <TouchableOpacity> press feedback (see touchablePressFades).
51
47
  const TOUCHABLE_ACTIVE_OPACITY = 0.2; // RN's default
52
48
  const TOUCHABLE_RESTORE_MS = 250; // RN's fade-back; the dim itself lands with no ramp
@@ -372,8 +368,8 @@ export function lowerEventHandler(attribute, output, environment, state) {
372
368
  }
373
369
  /**
374
370
  * Lowers one JSX element to its engine node (see emitNode, the located entry point): dispatches the typed
375
- * elements (Svg, Switch, Dial, TextInput, ActivityIndicator, Modal, FlatList) and function components to
376
- * their emitters, and builds a generic host node (View / Text / Pressable / TouchableOpacity / Image /
371
+ * elements (Svg, Switch, Dial, TextInput, ActivityIndicator, Modal), the wrappers (FlatList, SectionList,
372
+ * Button, ImageBackground) and function components to their emitters, and builds a generic host node (View / Text / Pressable / TouchableOpacity / Image /
377
373
  * ScrollView) itself: style, text, events, refs, and children.
378
374
  *
379
375
  * @param element The element.
@@ -386,10 +382,17 @@ export function lowerEventHandler(attribute, output, environment, state) {
386
382
  * @returns What the element lowered to.
387
383
  */
388
384
  function emitNodeImpl(element, scope, output, environment, state, options = {}) {
385
+ // A context's provider stands for the one element it wraps.
386
+ const context = providedContextOf(element, environment);
387
+ if (context) {
388
+ return emitProvider(element, context, scope, output, environment, state, options);
389
+ }
389
390
  // Refuse any prop the element does not declare, whatever its value, then drop the no-ops and the props that
390
391
  // fold to undefined before dispatch.
392
+ // A component in this file wins over a built-in that is no host node, as its binding would in JS.
391
393
  const tag = resolveTag(element.openingElement);
392
- const spec = elementSpec(tag);
394
+ const localComponent = !NODE_TYPES[tag] && output.components.has(tag);
395
+ const spec = localComponent ? undefined : elementSpec(tag);
393
396
  if (spec) {
394
397
  checkAttributes(spec, element.openingElement);
395
398
  if (spec.children === 'none') {
@@ -404,6 +407,9 @@ function emitNodeImpl(element, scope, output, environment, state, options = {})
404
407
  }
405
408
  return { kind: 'node', id: node.id, node };
406
409
  };
410
+ if (localComponent) {
411
+ return emitComponent(element, scope, output, environment, state, options);
412
+ }
407
413
  if (tag === 'Svg') {
408
414
  return typed(emitSvg(element, scope, output, environment, state, options));
409
415
  }
@@ -424,18 +430,18 @@ function emitNodeImpl(element, scope, output, environment, state, options = {})
424
430
  if (tag === 'FlatList') {
425
431
  return emitFlatList(element, scope, output, environment, state, options);
426
432
  }
427
- // Anything else must be a host node or a function component defined in this file.
433
+ if (tag === 'SectionList') {
434
+ return emitSectionList(element, scope, output, environment, state, options);
435
+ }
436
+ if (tag === 'Button') {
437
+ return emitButton(element, scope, output, environment, state, options);
438
+ }
439
+ if (tag === 'ImageBackground') {
440
+ return emitImageBackground(element, scope, output, environment, state, options);
441
+ }
442
+ // Anything else must be a host node.
428
443
  const nodeType = NODE_TYPES[tag];
429
444
  if (!nodeType) {
430
- if (output.components.has(tag)) {
431
- return emitComponent(element, scope, output, environment, state, options);
432
- }
433
- // A package export with no lowering yet gets its own error; "unknown element" would read like a typo.
434
- const replacement = FLOW_A_ONLY_COMPONENTS[tag];
435
- if (replacement) {
436
- throw aotError(`AOT: <${tag}> is not supported in Flow B yet`, `it renders in Flow A (the simulator and the QuickJS runtime) but the AOT has no ` +
437
- `lowering for it. Write it out by hand for the device build: ${replacement}`);
438
- }
439
445
  throw aotError(`AOT: unknown element <${tag}> (not a built-in or a component in this file)`, `<${tag}> must be a built-in (View / Text / Pressable / TouchableOpacity / Image / ` +
440
446
  `ScrollView / Svg + shapes / Animated.*) or a function component defined in THIS ` +
441
447
  `file. Check the import / spelling or define the component here.`);
@@ -21,7 +21,7 @@
21
21
  * nested <Text>'s segment count in the engine's uint8_t `span_count`.
22
22
  */
23
23
  const MAX_SCREEN = 32767;
24
- const MAX_LIST_CAPACITY = 32767;
24
+ export const MAX_LIST_CAPACITY = 32767;
25
25
  const MAX_LIST_STRING_CAPACITY = 32767;
26
26
  const MAX_TEXT_SPANS = 255;
27
27
  const MAX_TIMERS = 4096;
@@ -63,7 +63,8 @@ function wholeInRange(value, name, max, shown = String(value)) {
63
63
  * unless told a size, with both variables or the option.
64
64
  * listCap ER_AOT_LIST_CAP 16 Rows a list state holds. Each pooled row costs engine
65
65
  * nodes, so lower it on a tight-RAM MCU.
66
- * listStrCap ER_AOT_LIST_STR_CAP 48 Characters per string buffer (list field, string state).
66
+ * listStrCap ER_AOT_LIST_STR_CAP 48 Bytes for a string built from itself (`log + '.'`), with
67
+ * its terminator. Every other string is sized from its values.
67
68
  * maxTextSpans ER_AOT_MAX_TEXT_SPANS 4 Inline segments in a nested <Text>. Must match the
68
69
  * engine's ER_TEXT_MAX_SPANS.
69
70
  * maxTimers ER_AOT_MAX_TIMERS 8 Timers that run at once. Sizes the package's timer
@@ -34,12 +34,25 @@ export class Out {
34
34
  /** Numbers the next <Svg> (which names its tapes). */
35
35
  svgCount = 0;
36
36
  timerFunctions = [];
37
+ /** A release build, which leaves the console calls out. */
38
+ release = false;
39
+ /** The states a handler, effect or timer keeps a copy of, to read after setting them. */
40
+ keptStates = new Set();
41
+ /** useNativeEvent handlers, in the order they lower. */
42
+ nativeEventHandlers = [];
43
+ /** The optional native modules, by index, each with every method and event the package lists. */
44
+ optionalModules = [];
37
45
  /** What the build runs last: mount-once effects, and the first run of each dep-driven one. */
38
46
  mountEffects = [];
39
47
  /** Animations' on_complete callbacks: completions, completion waits, and chains. */
40
48
  animationCallbacks = [];
41
- /** The owner number of each composition that completion waits belong to, by composition; `isStarted` once a start waits. */
49
+ /**
50
+ * The owner number of each composition that completion waits belong to, by composition; `isStarted` once a
51
+ * start keeps a run under it, and `hasWaits` once one runs waits of their own.
52
+ */
42
53
  animationWaits = new Map();
54
+ /** Running-animation entries the groups of several animations take: each group's own, and all it runs. */
55
+ animationGroupEntries = 0;
43
56
  /** Numbers the next animation sequence. */
44
57
  sequenceCount = 0;
45
58
  /** Image assets the app reaches: asset name → source-relative import path. */
@@ -20,9 +20,10 @@
20
20
  * toValue in a register; its delay is the engine's own delay_ms. Each on_complete callback is an
21
21
  * animation-done function: a chain's steps start one another from them, and a completion wait is a delay leaf
22
22
  * started from one. A completion is a helper that takes `finished`, entered through a done function of its own
23
- * when an animation ends with it, or called directly. A run joined at run time (a spring beside a
24
- * longer delay) is a parallel group of a delay leaf and the animation. A composition with waits keeps the handle
25
- * of its last wait in a slot, so a stop can end it.
23
+ * when an animation ends with it, or called directly. A completion that waits on several animations, or on a
24
+ * spring beside a longer delay, is on a group of them (and a delay leaf); a parallel of several is a group with
25
+ * or without one, so they stop together. A composition with waits keeps the handle of its last wait in a slot,
26
+ * so a stop can end it.
26
27
  */
27
28
  /*----------------------------------------------------------------------------------------------------------------------
28
29
  - Imports
@@ -35,7 +36,7 @@ import { abiProp, floatBits } from './props.mjs';
35
36
  ---------------------------------------------------------------------------------------------------------------------*/
36
37
  /** Waits that run at once. */
37
38
  const MAX_WAITS = 8;
38
- /** Running-animation entries a wait takes: its delay leaf, and a joined run's group. */
39
+ /** Running-animation entries a wait takes: its delay leaf, and its group's. */
39
40
  const WAIT_ENTRIES = 2;
40
41
  /** A register operand that names no register (ASTART with no toValue in one). */
41
42
  const NO_REGISTER = 0xff;
@@ -64,6 +65,8 @@ export class AnimationPlan {
64
65
  /** The completions, in function order (callers first), by name. */
65
66
  completions = new Map();
66
67
  descriptors = new Map();
68
+ /** Each group's animations, in the order its tree lists them. */
69
+ groupLeaves = new Map();
67
70
  waits = new Map();
68
71
  interpolationIndex = new Map();
69
72
  /** The running-animation table's entries. */
@@ -138,10 +141,12 @@ export class AnimationPlan {
138
141
  this.completions.set(completion.name, completion);
139
142
  }
140
143
  // Each value runs one animation at a time, and one more while a start cancels it; each wait takes its own,
141
- // even in an app that only waits.
144
+ // even in an app that only waits. A group's block is counted twice, for the run a restart cancels.
142
145
  if (this.values.size || this.owners.size) {
143
- const waits = this.owners.size ? MAX_WAITS * WAIT_ENTRIES : 0;
144
- this.entries = this.values.size + 1 + waits;
146
+ const hasWaits = [...output.animationWaits.values()].some(record => record.hasWaits);
147
+ const waits = hasWaits ? MAX_WAITS * WAIT_ENTRIES : 0;
148
+ const groups = 2 * output.animationGroupEntries;
149
+ this.entries = this.values.size + 1 + waits + groups;
145
150
  arena.animTable(this.entries);
146
151
  }
147
152
  }
@@ -247,27 +252,51 @@ export class AnimationPlan {
247
252
  return index;
248
253
  }
249
254
  /**
250
- * A joined run: a parallel group of its delay and its one animation, done when both are and not finished as
251
- * soon as the animation stops.
255
+ * A group's tree: its wait's delay leaf, when it has one, then its animations, then its sequences, each group's
256
+ * children listed together after the groups before it. A parallel stops the rest when one stops; a stagger
257
+ * with no gap starts them together too, and lets the rest run on.
252
258
  *
253
259
  * @param start The start.
254
260
  *
255
261
  * @returns The group's index.
256
262
  */
257
- join(start) {
263
+ group(start) {
258
264
  let index = this.descriptors.get(start);
259
265
  if (index === undefined) {
260
- index = this.animations.length;
261
- this.animations.push({
262
- ...leafDefaults(),
263
- kind: AnimationKind.parallel,
264
- first: index + 1,
265
- count: 2,
266
- }, { ...leafDefaults(), amount: start.completionJoin.delayMs }, this.leafRecord(start.animations[0]));
266
+ const { stopsTogether, wait } = start.group;
267
+ const root = this.groupNode(stopsTogether, start.animations, start.sequences, wait?.delayMs ?? null);
268
+ index = this.animations.push(root.record) - 1;
269
+ const leaves = [];
270
+ const nodes = [root];
271
+ for (const node of nodes) {
272
+ if (node.animation) {
273
+ leaves.push(node.animation);
274
+ }
275
+ if (!node.children.length)
276
+ continue;
277
+ node.record.first = this.animations.length;
278
+ node.record.count = node.children.length;
279
+ for (const child of node.children) {
280
+ this.animations.push(child.record);
281
+ nodes.push(child);
282
+ }
283
+ }
267
284
  this.descriptors.set(start, index);
285
+ this.groupLeaves.set(start, leaves);
268
286
  }
269
287
  return index;
270
288
  }
289
+ /**
290
+ * A group's animations, in the order a start reads their toValues from registers: its tree's.
291
+ *
292
+ * @param start The start.
293
+ *
294
+ * @returns The animations.
295
+ */
296
+ groupAnimations(start) {
297
+ this.group(start);
298
+ return this.groupLeaves.get(start);
299
+ }
271
300
  /**
272
301
  * An animated value's bind as a binding: straight onto the prop, or through an interpolation.
273
302
  *
@@ -319,6 +348,41 @@ export class AnimationPlan {
319
348
  }
320
349
  return slot;
321
350
  }
351
+ groupNode(stopsTogether, animations, sequences, waitMs) {
352
+ const children = [
353
+ ...animations.map(animation => this.leafNode(animation)),
354
+ ...sequences.map(sequence => this.sequenceNode(sequence)),
355
+ ];
356
+ if (waitMs !== null) {
357
+ children.unshift(delayNode(waitMs));
358
+ }
359
+ return {
360
+ record: {
361
+ ...leafDefaults(),
362
+ kind: stopsTogether ? AnimationKind.parallel : AnimationKind.stagger,
363
+ },
364
+ animation: null,
365
+ children,
366
+ };
367
+ }
368
+ sequenceNode(sequence) {
369
+ return {
370
+ record: { ...leafDefaults(), kind: AnimationKind.sequence },
371
+ animation: null,
372
+ children: sequence.steps.map(step => {
373
+ if (step.kind === 'animation') {
374
+ return this.leafNode(step.animation);
375
+ }
376
+ if (step.kind === 'delay') {
377
+ return delayNode(step.delayMs);
378
+ }
379
+ return this.groupNode(step.stopsTogether, step.animations, step.sequences, step.waitMs);
380
+ }),
381
+ };
382
+ }
383
+ leafNode(animation) {
384
+ return { record: this.leafRecord(animation), animation, children: [] };
385
+ }
322
386
  leafRecord(animation) {
323
387
  const { curve } = animation;
324
388
  const record = {
@@ -386,6 +450,18 @@ const leafDefaults = () => ({
386
450
  to: 0,
387
451
  parameters: [0, 0, 0, 0],
388
452
  });
453
+ /**
454
+ * A delay leaf in a group's tree.
455
+ *
456
+ * @param delayMs The delay.
457
+ *
458
+ * @returns The node.
459
+ */
460
+ const delayNode = (delayMs) => ({
461
+ record: { ...leafDefaults(), amount: delayMs },
462
+ animation: null,
463
+ children: [],
464
+ });
389
465
  /**
390
466
  * The name of a chain's callback that starts step `index` (step 0's starts a repeat).
391
467
  *
@@ -451,6 +527,29 @@ function toValue(codegen, animation, plan) {
451
527
  codegen.builder.abx('AVGET', register.index, plan.value(animation.handle).index);
452
528
  return register;
453
529
  }
530
+ /**
531
+ * The toValues a group's animations take from registers, in consecutive registers in the animations' order.
532
+ *
533
+ * @param codegen The function's codegen.
534
+ * @param animations The animations.
535
+ * @param plan The program's animations.
536
+ *
537
+ * @returns The first register, or null when every descriptor holds its own.
538
+ */
539
+ function toValues(codegen, animations, plan) {
540
+ const fromRegisters = animations.filter(animation => animation.to?.kind !== 'number');
541
+ if (fromRegisters.length <= 1) {
542
+ return fromRegisters.length
543
+ ? toValue(codegen, fromRegisters[0], plan)
544
+ : null;
545
+ }
546
+ const run = codegen.builder.consecutive(fromRegisters.map(() => 'float'));
547
+ fromRegisters.forEach((animation, index) => {
548
+ const value = toValue(codegen, animation, plan);
549
+ codegen.builder.abc('MOVE', run[index].index, value.index);
550
+ });
551
+ return run[0];
552
+ }
454
553
  /**
455
554
  * Starts one animation.
456
555
  *
@@ -510,15 +609,26 @@ export function animationStatement(codegen, statement, plan) {
510
609
  const { builder } = codegen;
511
610
  switch (statement.kind) {
512
611
  case 'startAnimations': {
513
- const { animations, completion, completionJoin } = statement;
514
- if (!animations.length) {
612
+ const { animations, completion, group } = statement;
613
+ if (!animations.length && !statement.sequences.length) {
515
614
  return;
516
615
  }
517
- // A joined run is one tree, kept where a stop of its composition finds it.
518
- if (completionJoin && completion) {
616
+ // A group is one tree, kept where a stop of its composition finds it when it has a wait. One with
617
+ // sequences is kept too, and stops its last run first: steps that run on would pile up runs.
618
+ if (group) {
619
+ const owner = group.owner ?? group.wait?.owner ?? null;
620
+ if (group.owner !== null) {
621
+ codegen.scoped(() => {
622
+ const last = builder.register('animation');
623
+ builder.abx('GET32', last.index, plan.owner(group.owner).index);
624
+ builder.abc('ASTOP', last.index);
625
+ });
626
+ }
519
627
  codegen.scoped(() => {
520
- const handle = start(codegen, plan.join(statement), plan.done(completion.name), toValue(codegen, animations[0], plan));
521
- builder.abx('SET32', handle.index, plan.owner(completionJoin.owner).index);
628
+ const handle = start(codegen, plan.group(statement), completion ? plan.done(completion.name) : NONE, toValues(codegen, plan.groupAnimations(statement), plan));
629
+ if (owner !== null) {
630
+ builder.abx('SET32', handle.index, plan.owner(owner).index);
631
+ }
522
632
  });
523
633
  return;
524
634
  }
@@ -45,13 +45,11 @@ const WORDS_PER_LINE = 8;
45
45
  *
46
46
  * @param source The App.jsx/App.tsx source text.
47
47
  * @param options compilePackage's options, resolved (see resolveOptions), with the panel as the screen.
48
- * @param wide State/ref slots to declare 64-bit.
49
- * @param stores Collects every value stored into an int slot.
50
48
  *
51
49
  * @returns The panel's program, and its images.
52
50
  */
53
- export function compilePanel(source, options, wide, stores) {
54
- const app = lowerApp(source, options, wide, stores);
51
+ export function compilePanel(source, options) {
52
+ const app = lowerApp(source, options);
55
53
  return {
56
54
  program: lowerPackage(app, options),
57
55
  images: app.images,
@@ -31,6 +31,8 @@ export const OP = Object.fromEntries(OPCODES.map(([name, , words], index) => [na
31
31
  const MAX_REGISTERS = 255;
32
32
  /** The longest branch forward, in words: a branch keeps its offset in a signed 16 bits. */
33
33
  const MAX_BRANCH_OFFSET = 0x7fff;
34
+ /** The most loops in one function: the verifier's ERB_MAX_LOOPS. */
35
+ const MAX_LOOPS = 32;
34
36
  /** The register types that take two cells. */
35
37
  const WIDE = new Set(['int64', 'double', 'node']);
36
38
  /*----------------------------------------------------------------------------------------------------------------------
@@ -51,10 +53,14 @@ export class FunctionBuilder {
51
53
  runs = new Map();
52
54
  /** The types of each run, by its first cell. */
53
55
  runTypes = new Map();
56
+ /** Each run's registers, by its first. */
57
+ runIndices = new Map();
54
58
  /** Registers in use, in the order they were taken, for checkpoints. */
55
59
  taken = [];
56
60
  /** Where each run of the code starts in the source, for the debug table. */
57
61
  lines = [];
62
+ /** How many loops the function has so far. */
63
+ loops = 0;
58
64
  kind;
59
65
  what;
60
66
  /**
@@ -116,8 +122,9 @@ export class FunctionBuilder {
116
122
  return { index: this.newRegister(type), type };
117
123
  }
118
124
  /**
119
- * Registers of one-cell types in consecutive cells, as APPEND reads a row: a released run of the same types when
120
- * there is one, else new ones. A run is released whole, and only ever reused as a run.
125
+ * Registers in consecutive cells, as APPEND reads a row and CALLN its arguments: a released run of the same types
126
+ * when there is one, else new ones. A two-cell register starts on an even cell, so a gap may come before it. A run
127
+ * is released whole, and only ever reused as a run.
121
128
  *
122
129
  * @param types Their types.
123
130
  *
@@ -125,14 +132,15 @@ export class FunctionBuilder {
125
132
  */
126
133
  consecutive(types) {
127
134
  const key = types.join(' ');
128
- let first = this.runs.get(key)?.pop();
129
- if (first === undefined) {
130
- first = this.cellTypes.length;
131
- types.forEach(type => this.newRegister(type));
132
- this.runTypes.set(first, key);
135
+ const reused = this.runs.get(key)?.pop();
136
+ let indices = reused === undefined ? undefined : this.runIndices.get(reused);
137
+ if (!indices) {
138
+ indices = types.map(type => this.newRegister(type));
139
+ this.runTypes.set(indices[0], key);
140
+ this.runIndices.set(indices[0], indices);
133
141
  }
134
142
  const registers = types.map((type, index) => ({
135
- index: first + index,
143
+ index: indices[index],
136
144
  type,
137
145
  }));
138
146
  this.taken.push(registers[0]);
@@ -240,6 +248,27 @@ export class FunctionBuilder {
240
248
  label.branches.push(this.position);
241
249
  this.abx(name, test?.index ?? 0, 0);
242
250
  }
251
+ /**
252
+ * A counted loop: the body runs `bound` times, the counter going from `bound` down to 1. Only LOOPSET and LOOP
253
+ * may write the counter, so it is a register no release hands out.
254
+ *
255
+ * @param counter The counter.
256
+ * @param bound How many times.
257
+ * @param body Lowers the body.
258
+ */
259
+ loop(counter, bound, body) {
260
+ if (++this.loops > MAX_LOOPS) {
261
+ throw aotError(`AOT: ${this.what} has more than ${MAX_LOOPS} loops`, 'move some of them into another handler or effect, or combine loops over the same list.');
262
+ }
263
+ this.abx('LOOPSET', counter.index, bound);
264
+ const start = this.position;
265
+ body();
266
+ const offset = start - (this.position + 1);
267
+ if (-offset > MAX_BRANCH_OFFSET + 1) {
268
+ throw aotError(`AOT: ${this.what} has a loop too long for a package`, 'split it into smaller pieces.');
269
+ }
270
+ this.abx('LOOP', counter.index, offset);
271
+ }
243
272
  /**
244
273
  * A branch to a label when any of a dirty word's bits is set in this update pass.
245
274
  *
@@ -121,6 +121,10 @@ class CheckLowering {
121
121
  this.step(initializer.dimension === 'width' ? CheckOp.width : CheckOp.height, 0, 0, 1);
122
122
  return;
123
123
  }
124
+ // Whether a native module is there isn't known until the firmware loads the package.
125
+ if (initializer.kind === 'native') {
126
+ throw new NotCheckable();
127
+ }
124
128
  let local = this.locals.get(slot);
125
129
  if (local === undefined) {
126
130
  local = this.locals.size;