embedded-react 0.20.0 → 0.22.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 (140) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +3 -2
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +17 -47
  5. package/aot/compiler/alerts.mjs +604 -0
  6. package/aot/compiler/animations.mjs +299 -57
  7. package/aot/compiler/boot.mjs +27 -2
  8. package/aot/compiler/check.mjs +62 -10
  9. package/aot/compiler/collect.mjs +517 -137
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +276 -117
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/elements/button.mjs +182 -0
  14. package/aot/compiler/elements/image-background.mjs +76 -0
  15. package/aot/compiler/elements/image.mjs +2 -1
  16. package/aot/compiler/elements/props.mjs +47 -8
  17. package/aot/compiler/elements/rewrite.mjs +118 -0
  18. package/aot/compiler/elements/section-list.mjs +370 -0
  19. package/aot/compiler/expressions.mjs +1378 -97
  20. package/aot/compiler/handlers.mjs +1807 -354
  21. package/aot/compiler/helper-values.mjs +312 -0
  22. package/aot/compiler/ir/nodes.mjs +40 -1
  23. package/aot/compiler/ir/reads.mjs +206 -5
  24. package/aot/compiler/ir/text.mjs +5 -1
  25. package/aot/compiler/ir/types.mjs +12 -0
  26. package/aot/compiler/kept-states.mjs +177 -0
  27. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  28. package/aot/compiler/keyboard.mjs +1 -1
  29. package/aot/compiler/list-items.mjs +226 -0
  30. package/aot/compiler/list-order.mjs +586 -0
  31. package/aot/compiler/list-split.mjs +259 -0
  32. package/aot/compiler/loops.mjs +582 -0
  33. package/aot/compiler/lower.mjs +203 -53
  34. package/aot/compiler/native-files.mjs +439 -0
  35. package/aot/compiler/native-header.mjs +335 -0
  36. package/aot/compiler/native-modules.mjs +1173 -0
  37. package/aot/compiler/nodes.mjs +45 -31
  38. package/aot/compiler/options.mjs +3 -2
  39. package/aot/compiler/out.mjs +18 -1
  40. package/aot/compiler/package/animations.mjs +133 -23
  41. package/aot/compiler/package/assemble.mjs +2 -4
  42. package/aot/compiler/package/bytecode.mjs +37 -8
  43. package/aot/compiler/package/checks.mjs +4 -0
  44. package/aot/compiler/package/codegen.mjs +906 -33
  45. package/aot/compiler/package/enums.mjs +10 -0
  46. package/aot/compiler/package/format.mjs +16 -3
  47. package/aot/compiler/package/lower.mjs +707 -176
  48. package/aot/compiler/package/string-caps.mjs +515 -0
  49. package/aot/compiler/package/tables.mjs +24 -0
  50. package/aot/compiler/package/writer.mjs +22 -0
  51. package/aot/compiler/parse.mjs +3 -1
  52. package/aot/compiler/record-shapes.mjs +246 -0
  53. package/aot/compiler/records.mjs +654 -0
  54. package/aot/compiler/reducers.mjs +272 -0
  55. package/aot/compiler/scroll-to.mjs +112 -0
  56. package/aot/compiler/static-eval.mjs +315 -7
  57. package/aot/compiler/style-text.mjs +20 -5
  58. package/aot/compiler/svg.mjs +13 -7
  59. package/aot/compiler/switch-cases.mjs +198 -0
  60. package/aot/compiler/tagged-records.mjs +450 -0
  61. package/aot/compiler/typing.mjs +307 -0
  62. package/aot/compiler/updaters.mjs +321 -0
  63. package/aot/compiler/window-dimensions.mjs +94 -0
  64. package/aot/compiler/worked-values.mjs +319 -0
  65. package/aot/demo-file.mjs +30 -0
  66. package/aot/style-map.mjs +94 -3
  67. package/assets/bake-font.mjs +187 -244
  68. package/assets/bake-image.mjs +47 -71
  69. package/assets/bake-svg.mjs +465 -533
  70. package/assets/build-builtin-font.mjs +14 -27
  71. package/assets/emit-c.mjs +124 -204
  72. package/assets/emit-container.mjs +129 -197
  73. package/assets/emit-pack.mjs +92 -136
  74. package/assets/font-config.mjs +19 -27
  75. package/assets/font-sizes.mjs +432 -507
  76. package/assets/glyph-coverage.mjs +170 -214
  77. package/assets/index.mjs +52 -97
  78. package/assets/rasterize.mjs +173 -194
  79. package/assets/svg-loader.mjs +42 -48
  80. package/build.mjs +85 -94
  81. package/cli.mjs +490 -586
  82. package/compile-bin.mjs +24 -36
  83. package/flash.mjs +297 -401
  84. package/hotreload/dev-device.mjs +229 -270
  85. package/hotreload/pack-app.mjs +118 -159
  86. package/hotreload/pack-split.mjs +146 -213
  87. package/hotreload/package-transfer.mjs +128 -131
  88. package/hotreload/protocol.mjs +118 -118
  89. package/hotreload/uploader.mjs +132 -159
  90. package/hotreload/watch-tree.mjs +56 -65
  91. package/pack-container.mjs +94 -116
  92. package/package.json +19 -16
  93. package/persist-transform.mjs +89 -105
  94. package/qjsc-wasm.mjs +47 -72
  95. package/sim/embedded-react.wasm +0 -0
  96. package/sim/index.html +1 -1
  97. package/sim-server.mjs +260 -354
  98. package/src/embedded-react/Alert.mjs +112 -0
  99. package/src/embedded-react/Animated.mjs +412 -0
  100. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  101. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  102. package/src/embedded-react/Dimensions.mjs +32 -0
  103. package/src/embedded-react/Easing.mjs +34 -0
  104. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  105. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  106. package/src/embedded-react/Keyboard.mjs +82 -0
  107. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  108. package/src/embedded-react/PanResponder.mjs +256 -0
  109. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  110. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  111. package/src/embedded-react/SectionList.mjs +103 -0
  112. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  113. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  114. package/src/embedded-react/background-image.mjs +321 -0
  115. package/src/embedded-react/{components.js → components.mjs} +1 -3
  116. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  117. package/src/embedded-react/index.d.ts +238 -5
  118. package/src/embedded-react/index.js +26 -17
  119. package/src/embedded-react/layout-anim-config.mjs +85 -0
  120. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  121. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  122. package/src/embedded-react/nativeModule.mjs +371 -0
  123. package/src/embedded-react/split-style.mjs +57 -0
  124. package/src/embedded-react/svg-ops.mjs +1075 -0
  125. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  126. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  127. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  128. package/src/host-config.mjs +512 -0
  129. package/src/{native-ui.js → native-ui.mjs} +1 -8
  130. package/src/props.mjs +341 -0
  131. package/src/{renderer.js → renderer.mjs} +30 -44
  132. package/src/embedded-react/Animated.js +0 -440
  133. package/src/embedded-react/Easing.js +0 -39
  134. package/src/embedded-react/PanResponder.js +0 -330
  135. package/src/embedded-react/SectionList.js +0 -148
  136. package/src/embedded-react/layout-anim-config.js +0 -101
  137. package/src/embedded-react/split-style.js +0 -58
  138. package/src/embedded-react/svg-ops.js +0 -1295
  139. package/src/host-config.js +0 -548
  140. package/src/props.js +0 -306
@@ -28,6 +28,8 @@ import { animationStatement } from './animations.mjs';
28
28
  import { EventField, MathFn, ValueType } from './format.mjs';
29
29
  import { abiProp, constantNumber, floatBits } from './props.mjs';
30
30
  import { updateVector } from './vectors.mjs';
31
+ import { itemReadOf, rowEntries, rowIndexOf } from '../list-items.mjs';
32
+ import { BOOL } from '../ir/types.mjs';
31
33
  /*----------------------------------------------------------------------------------------------------------------------
32
34
  - Constants
33
35
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -77,7 +79,7 @@ const CONVERSIONS = {
77
79
  'int64>float': 'LTOF',
78
80
  'int64>double': 'LTOD',
79
81
  };
80
- /** The event field each touch field, and what a <Dial> passes, reads. */
82
+ /** The event field each touch or scroll field, and what a <Dial> passes, reads. */
81
83
  const EVENT_FIELDS = {
82
84
  x: EventField.x,
83
85
  y: EventField.y,
@@ -85,6 +87,8 @@ const EVENT_FIELDS = {
85
87
  dy: EventField.dy,
86
88
  vx: EventField.vx,
87
89
  vy: EventField.vy,
90
+ scrollX: EventField.scrollX,
91
+ scrollY: EventField.scrollY,
88
92
  value: EventField.value,
89
93
  value_start: EventField.valueStart,
90
94
  };
@@ -118,10 +122,24 @@ export class Codegen {
118
122
  inDoubles;
119
123
  input;
120
124
  onReturn;
125
+ /** The end of each block being lowered, innermost last, which a `return` in it goes to. */
126
+ blockEnds = [];
121
127
  row;
122
128
  locals = new Map();
123
129
  /** A string register nothing writes, so it stays the empty string. Reserved, so no release reuses it. */
124
130
  emptyString = null;
131
+ /** The counter of each depth of loops, which only LOOPSET and LOOP write. Reserved, for that. */
132
+ loopCounters = [];
133
+ /** How many loops are around the code being lowered. */
134
+ loopDepth = 0;
135
+ /** Where `break` and `continue` go in each loop being lowered, innermost last. */
136
+ loopLabels = [];
137
+ /** The row the update being lowered visits, which its setRows write. */
138
+ updatingRow;
139
+ /** The states the body being lowered keeps a copy of, which its reads use. */
140
+ keptStates = new Set();
141
+ /** The states the statement being lowered reads as they are now: an updater's own. */
142
+ readsLatest;
125
143
  /**
126
144
  * @param builder The function being built.
127
145
  * @param program The program's slots and tables.
@@ -130,6 +148,7 @@ export class Codegen {
130
148
  * onReturn: where an effect's early `return` goes.
131
149
  * row: the row a list row's handler was built for, which its item reads.
132
150
  * finished: what an animation completion was passed, which its `finished` reads.
151
+ * values: a native event handler's values, by the names its locals read them by.
133
152
  */
134
153
  constructor(builder, program, options = {}) {
135
154
  this.builder = builder;
@@ -141,6 +160,9 @@ export class Codegen {
141
160
  if (options.finished) {
142
161
  this.locals.set('finished', { register: options.finished });
143
162
  }
163
+ for (const [name, register] of options.values ?? []) {
164
+ this.locals.set(name, { register });
165
+ }
144
166
  }
145
167
  /*--------------------------------------------------------------------------------------------------------------------
146
168
  - Types
@@ -171,7 +193,7 @@ export class Codegen {
171
193
  // An interned state still reads as a string.
172
194
  return this.program.enums.has(expression.state)
173
195
  ? 'string'
174
- : slotType(this.stateSlot(expression.state));
196
+ : slotType(this.readSlot(expression));
175
197
  case 'boot':
176
198
  return slotType(this.bootSlot(expression.slot));
177
199
  case 'ref':
@@ -190,7 +212,7 @@ export class Codegen {
190
212
  case 'event':
191
213
  return expression.field === 'changed_text'
192
214
  ? 'string'
193
- : ['vx', 'vy', 'value', 'value_start'].includes(expression.field)
215
+ : expression.type.kind === 'float'
194
216
  ? 'float'
195
217
  : 'int';
196
218
  case 'gesture':
@@ -199,8 +221,12 @@ export class Codegen {
199
221
  : 'int';
200
222
  case 'clock':
201
223
  return 'int64';
224
+ case 'native':
225
+ return expression.call.import.result;
202
226
  case 'itemField':
203
227
  return expression.field.kind;
228
+ case 'itemPresent':
229
+ return 'bool';
204
230
  case 'pi':
205
231
  case 'toFloat':
206
232
  case 'floatDivide':
@@ -218,6 +244,7 @@ export class Codegen {
218
244
  return this.typeOf(expression.operand);
219
245
  case 'compare':
220
246
  case 'stringEquals':
247
+ case 'stringIncludes':
221
248
  case 'logical':
222
249
  return 'bool';
223
250
  case 'pick':
@@ -256,7 +283,7 @@ export class Codegen {
256
283
  if (this.program.enums.has(expression.state)) {
257
284
  throw new Error(`AOT internal: state "${expression.state.name}" is interned, but read as a string`);
258
285
  }
259
- return this.get(this.stateSlot(expression.state));
286
+ return this.get(this.readSlot(expression));
260
287
  case 'boot':
261
288
  return this.get(this.bootSlot(expression.slot));
262
289
  case 'ref':
@@ -269,7 +296,9 @@ export class Codegen {
269
296
  return register;
270
297
  }
271
298
  case 'itemField':
272
- return this.itemField(expression.item, expression.field.key, type);
299
+ return this.itemField(expression.item, expression.field, type);
300
+ case 'itemPresent':
301
+ return this.itemPresent(expression);
273
302
  case 'gesture':
274
303
  return this.gesture(expression);
275
304
  case 'event':
@@ -283,6 +312,8 @@ export class Codegen {
283
312
  builder.abc(expression.clock === 'Date' ? 'DATENOW' : 'NOW', register.index);
284
313
  return register;
285
314
  }
315
+ case 'native':
316
+ return this.callNative(expression.call);
286
317
  case 'pi':
287
318
  return this.load(type, Math.PI);
288
319
  case 'toFloat':
@@ -329,6 +360,16 @@ export class Codegen {
329
360
  }
330
361
  return register;
331
362
  }
363
+ case 'stringOrder': {
364
+ const register = builder.register('int');
365
+ builder.abc('SCMP', register.index, this.valueAs(expression.left, 'string').index, this.valueAs(expression.right, 'string').index);
366
+ return register;
367
+ }
368
+ case 'stringIncludes': {
369
+ const register = builder.register('bool');
370
+ builder.abc('SHAS', register.index, this.valueAs(expression.haystack, 'string').index, this.valueAs(expression.needle, 'string').index);
371
+ return register;
372
+ }
332
373
  case 'logical': {
333
374
  const register = builder.register('bool');
334
375
  const end = builder.label();
@@ -344,6 +385,50 @@ export class Codegen {
344
385
  return this.choose(this.condition(expression.test), () => this.valueAs(expression.consequent, type), () => this.valueAs(expression.alternate, type), type);
345
386
  }
346
387
  }
388
+ /**
389
+ * Calls a native method: its arguments in consecutive registers, and its result in the one after them (an int64
390
+ * on an even register, as the runtime lays them out).
391
+ *
392
+ * @param call The call.
393
+ * @param readsResult The caller reads the result.
394
+ *
395
+ * @returns A register holding the result, or null when the method returns nothing or it isn't read.
396
+ */
397
+ callNative(call, readsResult = true) {
398
+ const results = this.nativeCall(call);
399
+ if (!results.length || !readsResult) {
400
+ return null;
401
+ }
402
+ // A copy of its own, since a run is only ever released whole.
403
+ const register = this.builder.register(results[0].type);
404
+ this.builder.abc('MOVE', register.index, results[0].index);
405
+ return register;
406
+ }
407
+ /**
408
+ * Calls a native method: its arguments in consecutive registers, then its results, a record's values one by one.
409
+ *
410
+ * @param call The call.
411
+ *
412
+ * @returns The registers the results are in.
413
+ */
414
+ nativeCall(call) {
415
+ const { builder } = this;
416
+ const { params, results } = call.import;
417
+ const values = call.callArguments.map((argument, index) => this.valueAs(argument, params[index]));
418
+ const types = [...params, ...results];
419
+ const run = types.length ? builder.consecutive(types) : [];
420
+ values.forEach((value, index) => builder.abc('MOVE', run[index].index, value.index));
421
+ const importIndex = this.program.tables.nativeImport(call.import);
422
+ if (results.includes('string')) {
423
+ // A string result is copied into the call's own buffer: CALLNS names the first, one for each string.
424
+ const buffer = required(this.program.nativeStrings.get(call), `the buffer of ${call.import.name}`);
425
+ builder.abx('CALLNS', run[0].index, importIndex, buffer.index);
426
+ }
427
+ else {
428
+ builder.abx('CALLN', run[0]?.index ?? 0, importIndex);
429
+ }
430
+ return run.slice(params.length);
431
+ }
347
432
  /**
348
433
  * The set of an interned state an expression reads, or null when it reads none.
349
434
  *
@@ -378,7 +463,7 @@ export class Codegen {
378
463
  return this.load('bool', operator === '==' ? 0 : 1);
379
464
  }
380
465
  const register = this.builder.register('bool');
381
- this.builder.abc('EQ', register.index, this.get(this.stateSlot(read.state)).index, this.enumValue(set, index).index);
466
+ this.builder.abc('EQ', register.index, this.get(this.readSlot(read)).index, this.enumValue(set, index).index);
382
467
  if (operator === '!=') {
383
468
  this.builder.abc('NOT', register.index, register.index);
384
469
  }
@@ -618,29 +703,134 @@ export class Codegen {
618
703
  return this.get(this.input.text);
619
704
  }
620
705
  /**
621
- * A field of a list row's item. A row past the list's end, as a hidden row is, reads as zero or "".
706
+ * A field of a list row's item. A row past the list's end, as a hidden row is, reads as zero or "", and so does
707
+ * `list[i]?.field`; `list[i].field` past the end faults, as JS throws there.
622
708
  *
623
709
  * @param item The row's item.
624
- * @param key The field.
710
+ * @param field The field.
625
711
  * @param type Its type.
626
712
  *
627
713
  * @returns The register.
628
714
  */
629
- itemField(item, key, type) {
715
+ itemField(item, field, type) {
716
+ const list = required(item.list, `the list of "${item.name}"`);
717
+ return this.rowRead(item, rowIndexOf(list.struct, field), type, false);
718
+ }
719
+ /**
720
+ * Reads one field of an item's row, its value or its flag.
721
+ *
722
+ * @param item The row's item.
723
+ * @param index The field's index in the row.
724
+ * @param type Its type.
725
+ * @param checked Read zero past the list's end even for an unguarded index.
726
+ *
727
+ * @returns The register.
728
+ */
729
+ rowRead(item, index, type, checked) {
630
730
  const { builder } = this;
631
731
  const list = required(item.list, `the list of "${item.name}"`);
632
- const field = list.struct.fields.findIndex(entry => entry.key === key);
633
732
  const pool = this.listPool(list).slot;
634
- const row = this.row ?? this.load('int', required(item.row, item.name));
635
- const count = builder.register('int');
636
- const inUse = builder.register('bool');
637
- builder.abx('LEN', count.index, pool.index);
638
- builder.abc('LT', inUse.index, row.index, count.index);
639
- return this.choose(inUse, () => {
733
+ const row = item.index
734
+ ? this.valueAs(item.index, 'int')
735
+ : (this.row ?? this.load('int', required(item.row, item.name)));
736
+ const read = () => {
640
737
  const register = builder.register(type);
641
- builder.abc('ROWGET', register.index, row.index, 0, pool.index | (field << 16));
738
+ builder.abc('ROWGET', register.index, this.sourceRow(item, row).index, 0, pool.index | (index << 16));
642
739
  return register;
643
- }, () => this.zero(type), type);
740
+ };
741
+ if (item.index && !item.guarded && !checked) {
742
+ return read();
743
+ }
744
+ return this.choose(this.rowInRange(item, row), read, () => this.zero(type), type);
745
+ }
746
+ /**
747
+ * The row of its list an item is: the row itself, or for a row of a filtered or sorted list, the source row it
748
+ * holds.
749
+ *
750
+ * @param item The row's item.
751
+ * @param row Its row, in the list it counts in.
752
+ *
753
+ * @returns An int register.
754
+ */
755
+ sourceRow(item, row) {
756
+ if (!item.through)
757
+ return row;
758
+ const source = this.builder.register('int');
759
+ this.builder.abc('ROWGET', source.index, row.index, 0, this.listPool(item.through).slot.index);
760
+ return source;
761
+ }
762
+ /**
763
+ * Whether an item's row is in its list: below the count, and not negative for an index worked out at run time.
764
+ *
765
+ * @param item The row's item.
766
+ * @param row Its row.
767
+ *
768
+ * @returns A bool register.
769
+ */
770
+ rowInRange(item, row) {
771
+ const { builder } = this;
772
+ const pool = this.listPool(item.through ?? item.list).slot;
773
+ const count = builder.register('int');
774
+ const below = builder.register('bool');
775
+ builder.abx('LEN', count.index, pool.index);
776
+ builder.abc('LT', below.index, row.index, count.index);
777
+ if (!item.index) {
778
+ return below;
779
+ }
780
+ return this.choose(below, () => {
781
+ const nonNegative = builder.register('bool');
782
+ builder.abc('LE', nonNegative.index, this.load('int', 0).index, row.index);
783
+ return nonNegative;
784
+ }, () => this.load('bool', 0), 'bool');
785
+ }
786
+ /**
787
+ * Whether an item, or a field of it, is there. An item is there while its row is in the list; a field some item
788
+ * leaves out has a flag, and an object of fields is there when any of them is.
789
+ *
790
+ * @param expression The test.
791
+ *
792
+ * @returns A bool register.
793
+ */
794
+ itemPresent(expression) {
795
+ const { builder } = this;
796
+ const { item, fields } = expression;
797
+ const struct = required(item.list, `the list of "${item.name}"`).struct;
798
+ const flags = fields.filter(field => field.optional);
799
+ if (fields.length && flags.length < fields.length) {
800
+ // Some field every item has: there whenever the row is. Past the end of an unguarded index, reading the
801
+ // field faults, as JS throws there.
802
+ if (item.index && !item.guarded) {
803
+ this.rowRead(item, rowIndexOf(struct, fields[0]), fields[0].kind, false);
804
+ return this.load('bool', 1);
805
+ }
806
+ return this.rowPresent(item);
807
+ }
808
+ if (!fields.length) {
809
+ return this.rowPresent(item);
810
+ }
811
+ const result = builder.register('bool');
812
+ const end = builder.label();
813
+ flags.forEach((flag, index) => {
814
+ builder.abc('MOVE', result.index, this.rowRead(item, rowIndexOf(struct, flag, true), 'bool', false).index);
815
+ if (index < flags.length - 1) {
816
+ builder.branch('JT', end, result);
817
+ }
818
+ });
819
+ builder.place(end);
820
+ return result;
821
+ }
822
+ /**
823
+ * Whether an item's row is in its list.
824
+ *
825
+ * @param item The row's item.
826
+ *
827
+ * @returns A bool register.
828
+ */
829
+ rowPresent(item) {
830
+ const row = item.index
831
+ ? this.valueAs(item.index, 'int')
832
+ : (this.row ?? this.load('int', required(item.row, item.name)));
833
+ return this.rowInRange(item, row);
644
834
  }
645
835
  /** Zero, or the empty string, in a register of a type. */
646
836
  zero(type) {
@@ -764,17 +954,43 @@ export class Codegen {
764
954
  const { builder } = this;
765
955
  for (const part of parts) {
766
956
  const checkpoint = builder.checkpoint();
767
- if (part.kind === 'literal') {
957
+ const read = part.kind === 'literal' ? null : itemReadOf(part.value);
958
+ if (part.kind !== 'literal' &&
959
+ part.missing !== undefined &&
960
+ read &&
961
+ (read.field.optional || read.item.guarded)) {
962
+ // A field that isn't there prints as JS prints undefined.
963
+ const otherwise = builder.label();
964
+ const end = builder.label();
965
+ builder.branch('JF', otherwise, this.itemPresent({
966
+ kind: 'itemPresent',
967
+ item: read.item,
968
+ fields: [read.field],
969
+ type: BOOL,
970
+ }));
971
+ this.text([{ ...part, missing: undefined }]);
972
+ builder.branch('JMP', end);
973
+ builder.place(otherwise);
974
+ if (part.missing) {
975
+ builder.abx('FMTK', 0, this.program.tables.string(part.missing));
976
+ }
977
+ builder.place(end);
978
+ }
979
+ else if (part.kind === 'literal') {
768
980
  if (part.text) {
769
981
  builder.abx('FMTK', 0, this.program.tables.string(part.text));
770
982
  }
771
983
  }
772
984
  else if (part.kind === 'booleanWord') {
985
+ const positions = this.slicePositions(part.edits);
773
986
  builder.abc('FMTB', this.condition(part.value).index);
987
+ this.edits(part.edits, positions, 0);
774
988
  }
775
989
  else if (this.enumOf(part.value)) {
776
990
  const value = part.value;
777
- builder.abx('FMTE', this.get(this.stateSlot(value.state)).index, this.enumOf(value).set);
991
+ const positions = this.slicePositions(part.edits);
992
+ builder.abx('FMTE', this.get(this.readSlot(value)).index, this.enumOf(value).set);
993
+ this.edits(part.edits, positions, 0);
778
994
  }
779
995
  else {
780
996
  // The spec is by the value's IR type: a float is printed from a float, so a boot double is narrowed first.
@@ -786,11 +1002,65 @@ export class Codegen {
786
1002
  : type === 'int64'
787
1003
  ? ['FMTL', 'int64']
788
1004
  : ['FMTI', 'int'];
789
- builder.abc(opcode, this.valueAs(part.value, formatType).index);
1005
+ const register = this.valueAs(part.value, formatType).index;
1006
+ const positions = this.slicePositions(part.edits);
1007
+ if (part.digits !== undefined && formatType === 'float') {
1008
+ builder.abc('FMTFX', register, part.digits);
1009
+ this.edits(part.edits, positions, 0);
1010
+ }
1011
+ else if (part.digits) {
1012
+ // A whole number's decimals are all zeros, so pad the number to leave room for them.
1013
+ builder.abc(opcode, register);
1014
+ this.edits(part.edits, positions, part.digits + 1);
1015
+ builder.abx('FMTK', 0, this.program.tables.string(`.${'0'.repeat(part.digits)}`));
1016
+ }
1017
+ else {
1018
+ builder.abc(opcode, register);
1019
+ this.edits(part.edits, positions, 0);
1020
+ }
790
1021
  }
791
1022
  builder.release(checkpoint);
792
1023
  }
793
1024
  }
1025
+ /**
1026
+ * The registers each slice of a piece cuts at, worked out before the piece is printed.
1027
+ *
1028
+ * @param edits The piece's string helpers.
1029
+ *
1030
+ * @returns The start and end registers of each slice, in order.
1031
+ */
1032
+ slicePositions(edits) {
1033
+ return (edits ?? [])
1034
+ .filter(edit => edit.kind === 'slice')
1035
+ .map(edit => [
1036
+ this.valueAs(edit.start, 'int'),
1037
+ this.valueAs(edit.end, 'int'),
1038
+ ]);
1039
+ }
1040
+ /**
1041
+ * Applies the string helpers to the piece just printed, in order.
1042
+ *
1043
+ * @param edits The padStart, slice and toUpperCase calls, in order.
1044
+ * @param positions Each slice's registers, from slicePositions.
1045
+ * @param suffix How many bytes are still to be printed after the piece, which each padStart width leaves room for.
1046
+ */
1047
+ edits(edits, positions, suffix) {
1048
+ const slices = positions[Symbol.iterator]();
1049
+ for (const edit of edits ?? []) {
1050
+ if (edit.kind === 'pad') {
1051
+ if (edit.width > suffix) {
1052
+ this.builder.abc('FMTPAD', edit.width - suffix, edit.fill.charCodeAt(0));
1053
+ }
1054
+ }
1055
+ else if (edit.kind === 'upper') {
1056
+ this.builder.abc('FMTUPPER', 0);
1057
+ }
1058
+ else {
1059
+ const [start, end] = slices.next().value;
1060
+ this.builder.abc('FMTSLICE', start.index, end.index);
1061
+ }
1062
+ }
1063
+ }
794
1064
  /*--------------------------------------------------------------------------------------------------------------------
795
1065
  - Statements
796
1066
  -------------------------------------------------------------------------------------------------------------------*/
@@ -804,10 +1074,45 @@ export class Codegen {
804
1074
  this.statement(statement);
805
1075
  }
806
1076
  }
1077
+ /**
1078
+ * Lowers a body that shares its function with another, an effect's cleanup before its body: the copies it keeps
1079
+ * are its own.
1080
+ *
1081
+ * @param statements The body's statements.
1082
+ */
1083
+ body(statements) {
1084
+ this.keptStates.clear();
1085
+ this.statements(statements);
1086
+ this.keptStates.clear();
1087
+ }
807
1088
  statement(statement) {
1089
+ const outer = this.readsLatest;
1090
+ this.readsLatest = statement.readsLatest ?? outer;
1091
+ try {
1092
+ this.lowerStatement(statement);
1093
+ }
1094
+ finally {
1095
+ this.readsLatest = outer;
1096
+ }
1097
+ }
1098
+ /** Whether a statement lowers to code: all but a field kept as it is, which the body didn't set before. */
1099
+ doesSomething(statement) {
1100
+ if (statement.kind !== 'keepField')
1101
+ return true;
1102
+ const latest = statement.readsLatest ?? this.readsLatest;
1103
+ return (this.keptStates.has(statement.state) && !latest?.has(statement.state));
1104
+ }
1105
+ lowerStatement(statement) {
808
1106
  const { builder } = this;
809
1107
  builder.at(statement.location);
810
1108
  switch (statement.kind) {
1109
+ case 'keepStates':
1110
+ for (const state of statement.states) {
1111
+ const copy = required(this.program.kept.get(state), `the copy of state "${state.name}"`);
1112
+ this.scoped(() => this.set(copy, this.get(this.stateSlot(state))));
1113
+ this.keptStates.add(state);
1114
+ }
1115
+ return;
811
1116
  case 'declareLocal': {
812
1117
  const hoisted = this.program.hoisted.get(statement.name);
813
1118
  if (statement.isHoisted && !hoisted) {
@@ -822,13 +1127,15 @@ export class Codegen {
822
1127
  // A string local is a copy of its own, so a later write to the state it was read from can't change it.
823
1128
  const slot = hoisted ?? this.program.stringLocals.get(statement.name);
824
1129
  const checkpoint = builder.checkpoint();
825
- this.text([{ kind: 'value', value: statement.initializer }]);
1130
+ this.text(statement.text?.parts ?? [
1131
+ { kind: 'value', value: statement.initializer },
1132
+ ]);
826
1133
  builder.abx('FMTSET', 0, slot.index);
827
1134
  builder.release(checkpoint);
828
1135
  this.locals.set(statement.name, { slot });
829
1136
  return;
830
1137
  }
831
- const type = declaredType(statement.initializer);
1138
+ const type = statement.widenedTo ?? declaredType(statement.initializer);
832
1139
  const register = builder.register(type);
833
1140
  const checkpoint = builder.checkpoint();
834
1141
  builder.abc('MOVE', register.index, this.valueAs(statement.initializer, type).index);
@@ -865,12 +1172,19 @@ export class Codegen {
865
1172
  });
866
1173
  return;
867
1174
  case 'if': {
1175
+ // Branches that only keep fields as they are do nothing, so the test isn't worked out either.
1176
+ const inner = [...statement.consequent, ...(statement.alternate ?? [])];
1177
+ if (inner.some(kept => kept.kind === 'keepField') &&
1178
+ !inner.some(kept => this.doesSomething(kept))) {
1179
+ return;
1180
+ }
868
1181
  const otherwise = builder.label();
869
1182
  const checkpoint = builder.checkpoint();
870
1183
  builder.branch('JF', otherwise, this.condition(statement.test));
871
1184
  builder.release(checkpoint);
872
1185
  this.statements(statement.consequent);
873
- if (statement.alternate) {
1186
+ // An else of fields kept as they are does nothing.
1187
+ if (statement.alternate?.some(inner => this.doesSomething(inner))) {
874
1188
  const end = builder.label();
875
1189
  builder.branch('JMP', end);
876
1190
  builder.place(otherwise);
@@ -888,6 +1202,29 @@ export class Codegen {
888
1202
  case 'clearTimer':
889
1203
  this.scoped(() => builder.abc('TCLEAR', this.valueAs(statement.id, 'int').index));
890
1204
  return;
1205
+ case 'callNative': {
1206
+ if (!statement.results) {
1207
+ this.scoped(() => this.callNative(statement.call, false));
1208
+ return;
1209
+ }
1210
+ // A record's values are kept, each in a register of its own, for the locals that read them.
1211
+ const kept = statement.call.import.results.map(type => builder.register(type));
1212
+ this.scoped(() => this.nativeCall(statement.call).forEach((result, index) => builder.abc('MOVE', kept[index].index, result.index)));
1213
+ statement.results.forEach((name, index) => this.locals.set(name, { register: kept[index] }));
1214
+ return;
1215
+ }
1216
+ case 'keepField':
1217
+ if (this.doesSomething(statement)) {
1218
+ const { state } = statement;
1219
+ this.scoped(() => this.set(this.stateSlot(state), this.get(this.program.kept.get(state))));
1220
+ }
1221
+ return;
1222
+ case 'log':
1223
+ this.scoped(() => {
1224
+ this.text(statement.text.parts);
1225
+ builder.abc('FMTLOG', 0);
1226
+ });
1227
+ return;
891
1228
  case 'clearList':
892
1229
  builder.abx('CLEAR', 0, this.listPool(statement.list).slot.index);
893
1230
  return;
@@ -904,24 +1241,188 @@ export class Codegen {
904
1241
  // slice(0, end), as SLICE counts it.
905
1242
  this.scoped(() => builder.abc('SLICE', this.load('int', 0).index, this.valueAs(statement.end, 'int').index, 0, this.listPool(statement.list).slot.index));
906
1243
  return;
1244
+ case 'removeItem':
1245
+ this.scoped(() => this.removeItem(statement));
1246
+ return;
1247
+ case 'updateItems':
1248
+ this.scoped(() => this.updateItems(statement));
1249
+ return;
1250
+ case 'setRow':
1251
+ this.scoped(() => this.setRow(statement));
1252
+ return;
1253
+ case 'filterItems':
1254
+ this.scoped(() => this.filterItems(statement));
1255
+ return;
1256
+ case 'sortItems':
1257
+ this.scoped(() => this.sortItems(statement));
1258
+ return;
1259
+ case 'fillOrder':
1260
+ this.scoped(() => this.fillOrder(statement));
1261
+ return;
1262
+ case 'splitItems':
1263
+ this.scoped(() => this.splitItems(statement));
1264
+ return;
907
1265
  case 'stopAnimations':
908
1266
  case 'startAnimations':
909
1267
  case 'startChain':
910
1268
  case 'completeAfter':
911
1269
  animationStatement(this, statement, this.program.animations);
912
1270
  return;
913
- case 'return':
914
- if (!this.onReturn) {
915
- throw new Error('AOT internal: a `return` outside an effect');
1271
+ case 'block': {
1272
+ const end = builder.label();
1273
+ this.blockEnds.push(end);
1274
+ this.statements(statement.body);
1275
+ this.blockEnds.pop();
1276
+ builder.place(end);
1277
+ return;
1278
+ }
1279
+ case 'assignLocal':
1280
+ this.scoped(() => this.assignLocal(statement));
1281
+ return;
1282
+ case 'loop':
1283
+ this.loop(statement);
1284
+ return;
1285
+ case 'break':
1286
+ case 'continue': {
1287
+ const labels = this.loopLabels.at(-1);
1288
+ if (!labels) {
1289
+ throw new Error(`AOT internal: a \`${statement.kind}\` outside a loop`);
916
1290
  }
917
- builder.branch('JMP', this.onReturn);
1291
+ builder.branch('JMP', statement.kind === 'break' ? labels.done : labels.next);
918
1292
  return;
1293
+ }
1294
+ case 'return': {
1295
+ const end = this.blockEnds.at(-1) ?? this.onReturn;
1296
+ if (!end) {
1297
+ throw new Error('AOT internal: a `return` outside a block or effect');
1298
+ }
1299
+ builder.branch('JMP', end);
1300
+ return;
1301
+ }
919
1302
  case 'armCleanup':
920
1303
  this.scoped(() => this.set(required(this.program.armed.get(statement.flag), statement.flag), this.load('bool', 1)));
921
1304
  return;
922
1305
  case 'updateVector':
923
1306
  updateVector(this, statement, this.program.vectors);
1307
+ return;
1308
+ case 'scrollTo':
1309
+ this.scrollTo(statement);
1310
+ return;
1311
+ case 'dismissKeyboard':
1312
+ builder.abc('BLUR', 0);
1313
+ }
1314
+ }
1315
+ /**
1316
+ * Scrolls the ScrollView a ref is on, then keeps where it landed for the locals that read it.
1317
+ *
1318
+ * @param statement The call.
1319
+ */
1320
+ scrollTo(statement) {
1321
+ const { builder } = this;
1322
+ const handle = required(this.program.vectors.refNodes.get(statement.node), 'the node a scrollTo scrolls');
1323
+ const kept = statement.results?.map(() => builder.register('float'));
1324
+ this.scoped(() => {
1325
+ const node = builder.register('node');
1326
+ builder.abx('GET64', node.index, handle.index);
1327
+ if (statement.x || statement.y) {
1328
+ // An axis left out is NaN, which the engine keeps where it is.
1329
+ const axis = (value) => value ? this.valueAs(value, 'float') : this.load('float', NaN);
1330
+ const x = axis(statement.x);
1331
+ builder.abc('SCROLL', node.index, x.index, axis(statement.y).index);
1332
+ }
1333
+ if (kept) {
1334
+ const position = builder.consecutive(kept.map(() => 'float'));
1335
+ builder.abc('SCROLLAT', node.index, position[0].index);
1336
+ position.forEach((value, index) => builder.abc('MOVE', kept[index].index, value.index));
1337
+ }
1338
+ });
1339
+ statement.results?.forEach((name, index) => this.locals.set(name, { register: kept[index] }));
1340
+ }
1341
+ /**
1342
+ * A counted loop, its counter the one for its depth, so a loop inside it counts with another.
1343
+ *
1344
+ * @param bound How many times the body runs.
1345
+ * @param body Lowers the body, given the counter, which goes from `bound` down to 1.
1346
+ */
1347
+ counted(bound, body) {
1348
+ const counter = this.counterAt(this.loopDepth);
1349
+ this.loopDepth++;
1350
+ try {
1351
+ this.builder.loop(counter, bound, () => body(counter));
1352
+ }
1353
+ finally {
1354
+ this.loopDepth--;
1355
+ }
1356
+ }
1357
+ /**
1358
+ * The counter of a depth of loops, taken the first time it is needed.
1359
+ *
1360
+ * @param depth How many loops are around the loop.
1361
+ *
1362
+ * @returns The counter.
1363
+ */
1364
+ counterAt(depth) {
1365
+ return (this.loopCounters[depth] ??= this.builder.reserved('int'));
1366
+ }
1367
+ /**
1368
+ * A `for` or `for…of` loop. A `break` goes past its end, and a `continue` to its step. The body's locals are its
1369
+ * own, so a name it declares again reads the outer local after it.
1370
+ *
1371
+ * @param statement The loop.
1372
+ */
1373
+ loop(statement) {
1374
+ const { builder } = this;
1375
+ if (statement.bound === 0)
1376
+ return;
1377
+ const done = builder.label();
1378
+ const next = builder.label();
1379
+ const outer = new Map(this.locals);
1380
+ this.loopLabels.push({ done, next });
1381
+ this.counted(statement.bound, counter => this.scoped(() => {
1382
+ // The counter runs from the bound down to 1, so bound - counter is the visit's number from 0.
1383
+ if (statement.visit) {
1384
+ const visit = builder.register('int');
1385
+ builder.abc('SUB', visit.index, this.load('int', statement.bound).index, counter.index);
1386
+ this.locals.set(required(statement.visit.name, 'the visit'), {
1387
+ register: visit,
1388
+ });
1389
+ }
1390
+ if (statement.test) {
1391
+ const checkpoint = builder.checkpoint();
1392
+ builder.branch('JF', done, this.condition(statement.test));
1393
+ builder.release(checkpoint);
1394
+ }
1395
+ this.statements(statement.body);
1396
+ builder.place(next);
1397
+ this.statements(statement.step);
1398
+ }));
1399
+ this.loopLabels.pop();
1400
+ this.locals.clear();
1401
+ outer.forEach((binding, name) => this.locals.set(name, binding));
1402
+ builder.place(done);
1403
+ }
1404
+ /**
1405
+ * Sets a `let` local declared before: its register, or its slot when it is kept in one.
1406
+ *
1407
+ * @param statement The assignment.
1408
+ */
1409
+ assignLocal(statement) {
1410
+ const { builder } = this;
1411
+ const binding = this.binding(statement.name);
1412
+ if (!binding) {
1413
+ throw new Error(`AOT internal: no local "${statement.name}"`);
1414
+ }
1415
+ if ('register' in binding) {
1416
+ const { register } = binding;
1417
+ builder.abc('MOVE', register.index, this.valueAs(statement.value, register.type).index);
1418
+ return;
1419
+ }
1420
+ if (slotType(binding.slot) === 'string') {
1421
+ this.text(statement.text?.parts ?? [{ kind: 'value', value: statement.value }]);
1422
+ builder.abx('FMTSET', 0, binding.slot.index);
1423
+ return;
924
1424
  }
1425
+ this.set(binding.slot, this.value(statement.value));
925
1426
  }
926
1427
  /**
927
1428
  * Appends an item, its fields worked out in order into consecutive registers. A full list drops it.
@@ -932,20 +1433,384 @@ export class Codegen {
932
1433
  appendItem(statement) {
933
1434
  const { builder } = this;
934
1435
  const pool = this.listPool(statement.list);
935
- const row = builder.consecutive(statement.values.map(({ field }) => field.kind === 'string' ? 'string' : field.kind));
936
- statement.values.forEach((itemValue, index) => this.scoped(() => {
937
- if ('text' in itemValue) {
938
- const buffer = required(pool.buffers.get(itemValue.field.key), `field "${itemValue.field.key}"`);
1436
+ const entries = rowEntries(statement.list.struct);
1437
+ const given = new Map(statement.values.map(value => [value.field, value]));
1438
+ const row = builder.consecutive(entries.map(({ field, presence }) => presence ? 'bool' : field.kind === 'string' ? 'string' : field.kind));
1439
+ entries.forEach(({ field, presence }, index) => this.scoped(() => {
1440
+ const itemValue = given.get(field);
1441
+ if (presence || !itemValue) {
1442
+ // A field the item leaves out is 0 or "", and its flag says so.
1443
+ builder.abc('MOVE', row[index].index, presence
1444
+ ? this.load('bool', itemValue ? 1 : 0).index
1445
+ : this.zero(field.kind).index);
1446
+ }
1447
+ else if ('text' in itemValue) {
1448
+ const buffer = required(pool.buffers.get(field.key), `field "${field.key}"`);
939
1449
  this.text(itemValue.text.parts);
940
1450
  builder.abx('FMTSET', 0, buffer.index);
941
1451
  builder.abx('GETS', row[index].index, buffer.index);
942
1452
  }
943
1453
  else {
944
- builder.abc('MOVE', row[index].index, this.valueAs(itemValue.value, itemValue.field.kind).index);
1454
+ builder.abc('MOVE', row[index].index, this.valueAs(itemValue.value, field.kind).index);
945
1455
  }
946
1456
  }));
947
1457
  builder.abx('APPEND', row[0].index, pool.slot.index);
948
1458
  }
1459
+ /**
1460
+ * Drops a row, moving the rest up. Past either end, nothing is removed.
1461
+ *
1462
+ * @param statement The removal.
1463
+ */
1464
+ removeItem(statement) {
1465
+ const { builder } = this;
1466
+ const pool = this.listPool(statement.list).slot;
1467
+ let index = this.valueAs(statement.index, 'int');
1468
+ if (statement.negative === 'sliced') {
1469
+ // [...items.slice(0, -1), ...items.slice(0)] repeats the list, which a list can't hold.
1470
+ const list = statement.list.name;
1471
+ this.trapWhen('EQ', index, -1, `[...${list}.slice(0, -1), ...${list}.slice(0)] repeats the list`);
1472
+ }
1473
+ if (statement.negative !== 'none') {
1474
+ index = this.countedBack(index, pool, statement.negative === 'spliced');
1475
+ }
1476
+ builder.abx('REMOVE', index.index, pool.index);
1477
+ }
1478
+ /**
1479
+ * Stops the app with a message when a whole number compares to a constant: is equal to it, or below it.
1480
+ *
1481
+ * @param compare EQ or LT.
1482
+ * @param value The number.
1483
+ * @param constant The constant.
1484
+ * @param message Why it stops.
1485
+ */
1486
+ trapWhen(compare, value, constant, message) {
1487
+ const { builder } = this;
1488
+ const stops = builder.register('bool');
1489
+ builder.abc(compare, stops.index, value.index, this.load('int', constant).index);
1490
+ const goesOn = builder.label();
1491
+ builder.branch('JF', goesOn, stops);
1492
+ builder.abx('TRAP', 0, this.program.tables.string(message));
1493
+ builder.place(goesOn);
1494
+ }
1495
+ /**
1496
+ * A row index with a negative one counted back from the end, as `toSpliced`, `with` and a pair of slices count it.
1497
+ *
1498
+ * @param index The index.
1499
+ * @param pool The list's pool.
1500
+ * @param floor One still negative after counting back is 0, as `toSpliced` makes it.
1501
+ *
1502
+ * @returns The row.
1503
+ */
1504
+ countedBack(index, pool, floor) {
1505
+ const { builder } = this;
1506
+ const negative = builder.register('bool');
1507
+ builder.abc('LT', negative.index, index.index, this.load('int', 0).index);
1508
+ return this.choose(negative, () => {
1509
+ const count = builder.register('int');
1510
+ builder.abx('LEN', count.index, pool.index);
1511
+ const back = builder.register('int');
1512
+ builder.abc('ADD', back.index, index.index, count.index);
1513
+ if (floor) {
1514
+ builder.abc('MAX', back.index, back.index, this.load('int', 0).index);
1515
+ }
1516
+ return back;
1517
+ }, () => index, 'int');
1518
+ }
1519
+ /**
1520
+ * Runs an update's body on its rows: every row, in a loop as long as the list's cap that stops at its count, or
1521
+ * the one row `with` names, which must be in the list.
1522
+ *
1523
+ * @param statement The update.
1524
+ */
1525
+ updateItems(statement) {
1526
+ const { builder } = this;
1527
+ const pool = this.listPool(statement.list).slot;
1528
+ const name = required(statement.row.name, 'the update row');
1529
+ const visit = (row) => {
1530
+ this.locals.set(name, { register: row });
1531
+ this.updatingRow = row;
1532
+ this.statements(statement.body);
1533
+ this.updatingRow = undefined;
1534
+ this.locals.delete(name);
1535
+ };
1536
+ if (statement.index) {
1537
+ const index = this.valueAs(statement.index, 'int');
1538
+ if (statement.negativeKeeps) {
1539
+ const list = statement.list.name;
1540
+ this.trapWhen('LT', index, 0, `${list}.with(n, …) keeps fields of ${list}[n], which is undefined for a negative n`);
1541
+ }
1542
+ const row = this.countedBack(index, pool, false);
1543
+ // A read of the row faults past the end, as with() throws there.
1544
+ const [first] = rowEntries(statement.list.struct);
1545
+ builder.abc('ROWGET', builder.register(first.field.kind).index, row.index, 0, pool.index);
1546
+ visit(row);
1547
+ return;
1548
+ }
1549
+ const count = builder.register('int');
1550
+ builder.abx('LEN', count.index, pool.index);
1551
+ const capacity = this.load('int', statement.list.capacity);
1552
+ const done = builder.label();
1553
+ this.counted(statement.list.capacity, counter => this.scoped(() => {
1554
+ const row = builder.register('int');
1555
+ builder.abc('SUB', row.index, capacity.index, counter.index);
1556
+ const inList = builder.register('bool');
1557
+ builder.abc('LT', inList.index, row.index, count.index);
1558
+ builder.branch('JF', done, inList);
1559
+ visit(row);
1560
+ }));
1561
+ builder.place(done);
1562
+ }
1563
+ /**
1564
+ * Visits a list's rows in a loop as long as its cap that stops at its count: first to last, or last to first.
1565
+ *
1566
+ * @param list The list.
1567
+ * @param backwards Visit the last row first.
1568
+ * @param visit Lowers the body, given the row.
1569
+ */
1570
+ eachRow(list, backwards, visit) {
1571
+ const { builder } = this;
1572
+ const pool = this.listPool(list).slot;
1573
+ const count = builder.register('int');
1574
+ builder.abx('LEN', count.index, pool.index);
1575
+ const capacity = this.load('int', list.capacity);
1576
+ const done = builder.label();
1577
+ this.counted(list.capacity, counter => this.scoped(() => {
1578
+ // The counter runs from the cap down to 1, so cap - counter is the visit's number from 0.
1579
+ const row = builder.register('int');
1580
+ builder.abc('SUB', row.index, capacity.index, counter.index);
1581
+ const inList = builder.register('bool');
1582
+ if (backwards) {
1583
+ builder.abc('SUB', row.index, count.index, row.index);
1584
+ builder.abc('SUB', row.index, row.index, this.load('int', 1).index);
1585
+ builder.abc('LE', inList.index, this.load('int', 0).index, row.index);
1586
+ }
1587
+ else {
1588
+ builder.abc('LT', inList.index, row.index, count.index);
1589
+ }
1590
+ builder.branch('JF', done, inList);
1591
+ visit(row);
1592
+ }));
1593
+ builder.place(done);
1594
+ }
1595
+ /**
1596
+ * Drops the rows a filter doesn't keep, last to first, so the rows still to test stay where they are.
1597
+ *
1598
+ * @param statement The filter.
1599
+ */
1600
+ filterItems(statement) {
1601
+ const { builder } = this;
1602
+ const pool = this.listPool(statement.list).slot;
1603
+ const name = required(statement.position.name, 'the filtered row');
1604
+ this.eachRow(statement.list, true, row => {
1605
+ this.locals.set(name, { register: row });
1606
+ const kept = builder.label();
1607
+ builder.branch('JT', kept, this.condition(statement.keep));
1608
+ builder.abx('REMOVE', row.index, pool.index);
1609
+ builder.place(kept);
1610
+ this.locals.delete(name);
1611
+ });
1612
+ }
1613
+ /**
1614
+ * Fills a list of strings with a string's pieces. Without a limit it keeps every piece the list holds; without a
1615
+ * separator, the whole string.
1616
+ *
1617
+ * @param statement The split.
1618
+ */
1619
+ splitItems(statement) {
1620
+ const { builder } = this;
1621
+ const pool = this.listPool(statement.list).slot;
1622
+ if (!statement.separator) {
1623
+ // The string is read before the clear, which only resets the count, so a row of this list still reads.
1624
+ const text = this.valueAs(statement.text, 'string');
1625
+ builder.abx('CLEAR', 0, pool.index);
1626
+ builder.abx('APPEND', text.index, pool.index);
1627
+ return;
1628
+ }
1629
+ builder.abc('SPLIT', this.valueAs(statement.text, 'string').index, this.valueAs(statement.separator, 'string').index, (statement.limit
1630
+ ? this.valueAs(statement.limit, 'int')
1631
+ : this.load('int', -1)).index, pool.index);
1632
+ }
1633
+ /**
1634
+ * Fills a filtered or sorted list with the source rows its first filter keeps, or all of them.
1635
+ *
1636
+ * @param statement The fill.
1637
+ */
1638
+ fillOrder(statement) {
1639
+ const { builder } = this;
1640
+ const pool = this.listPool(statement.list).slot;
1641
+ const source = required(statement.list.derived?.source, 'a filtered or sorted list');
1642
+ const name = required(statement.row.name, 'the visited row');
1643
+ builder.abx('CLEAR', 0, pool.index);
1644
+ this.eachRow(source, false, row => {
1645
+ const skip = builder.label();
1646
+ if (statement.keep) {
1647
+ this.locals.set(name, { register: row });
1648
+ builder.branch('JF', skip, this.condition(statement.keep));
1649
+ this.locals.delete(name);
1650
+ }
1651
+ builder.abx('APPEND', row.index, pool.index);
1652
+ builder.place(skip);
1653
+ });
1654
+ }
1655
+ /**
1656
+ * Sorts a list's rows in place by insertion: each row moves back past the rows before it that go after it, so
1657
+ * equal rows keep their order, as JS's sort does.
1658
+ *
1659
+ * @param statement The sort.
1660
+ */
1661
+ sortItems(statement) {
1662
+ const { builder } = this;
1663
+ const { list } = statement;
1664
+ const pool = this.listPool(list).slot;
1665
+ const firstName = required(statement.first.name, 'the first row');
1666
+ const secondName = required(statement.second.name, 'the second row');
1667
+ const count = builder.register('int');
1668
+ builder.abx('LEN', count.index, pool.index);
1669
+ const capacity = this.load('int', list.capacity);
1670
+ const one = this.load('int', 1);
1671
+ // Both counters are taken before the loops, ahead of the registers the loops work in.
1672
+ this.counterAt(this.loopDepth);
1673
+ this.counterAt(this.loopDepth + 1);
1674
+ const sorted = builder.label();
1675
+ this.counted(list.capacity, outer => this.scoped(() => {
1676
+ // Row cap - counter + 1 moves back next, from row 1 on.
1677
+ const moving = builder.register('int');
1678
+ builder.abc('SUB', moving.index, capacity.index, outer.index);
1679
+ builder.abc('ADD', moving.index, moving.index, one.index);
1680
+ const inList = builder.register('bool');
1681
+ builder.abc('LT', inList.index, moving.index, count.index);
1682
+ builder.branch('JF', sorted, inList);
1683
+ const placed = builder.label();
1684
+ this.counted(list.capacity, inner => this.scoped(() => {
1685
+ // It is at row moving - (cap - counter) now; it stops at row 0.
1686
+ const second = builder.register('int');
1687
+ builder.abc('SUB', second.index, capacity.index, inner.index);
1688
+ builder.abc('SUB', second.index, moving.index, second.index);
1689
+ const above = builder.register('bool');
1690
+ builder.abc('LT', above.index, this.load('int', 0).index, second.index);
1691
+ builder.branch('JF', placed, above);
1692
+ const first = builder.register('int');
1693
+ builder.abc('SUB', first.index, second.index, one.index);
1694
+ this.locals.set(firstName, { register: first });
1695
+ this.locals.set(secondName, { register: second });
1696
+ builder.branch('JF', placed, this.after(statement.order));
1697
+ this.locals.delete(firstName);
1698
+ this.locals.delete(secondName);
1699
+ this.swapRows(list, first, second);
1700
+ }));
1701
+ builder.place(placed);
1702
+ }));
1703
+ builder.place(sorted);
1704
+ }
1705
+ /**
1706
+ * Whether a compare function's result puts the first row after the second: it is above zero.
1707
+ *
1708
+ * @param order The result.
1709
+ *
1710
+ * @returns A bool register.
1711
+ */
1712
+ after(order) {
1713
+ const { builder } = this;
1714
+ const value = this.value(order);
1715
+ const type = value.type;
1716
+ const result = builder.register('bool');
1717
+ if (type === 'bool') {
1718
+ // true is 1, which puts the first row after the second.
1719
+ builder.abc('MOVE', result.index, value.index);
1720
+ }
1721
+ else if (type === 'float' || type === 'double') {
1722
+ builder.abc(type === 'float' ? 'FLT' : 'DLT', result.index, this.load(type, 0).index, value.index);
1723
+ }
1724
+ else if (type === 'int64') {
1725
+ builder.abc('LLT', result.index, this.load('int64', 0).index, value.index);
1726
+ }
1727
+ else {
1728
+ builder.abc('LT', result.index, this.load('int', 0).index, value.index);
1729
+ }
1730
+ return result;
1731
+ }
1732
+ /**
1733
+ * Swaps two rows of a list, field by field. A string goes through its field's own buffer.
1734
+ *
1735
+ * @param list The list.
1736
+ * @param first One row.
1737
+ * @param second The other.
1738
+ */
1739
+ swapRows(list, first, second) {
1740
+ const { builder } = this;
1741
+ const pool = this.listPool(list);
1742
+ rowEntries(list.struct).forEach(({ field, presence }, index) => this.scoped(() => {
1743
+ const extension = pool.slot.index | (index << 16);
1744
+ const read = (row, type) => {
1745
+ const register = builder.register(type);
1746
+ builder.abc('ROWGET', register.index, row.index, 0, extension);
1747
+ return register;
1748
+ };
1749
+ const write = (value, row) => builder.abc('ROWSET', value.index, row.index, 0, extension);
1750
+ if (!presence && field.kind === 'string') {
1751
+ const buffer = required(pool.buffers.get(field.key), `field "${field.key}"`);
1752
+ builder.abx('SETS', read(first, 'string').index, buffer.index);
1753
+ write(read(second, 'string'), first);
1754
+ const kept = builder.register('string');
1755
+ builder.abx('GETS', kept.index, buffer.index);
1756
+ write(kept, second);
1757
+ return;
1758
+ }
1759
+ const type = presence ? 'bool' : field.kind;
1760
+ const firstValue = read(first, type);
1761
+ const secondValue = read(second, type);
1762
+ write(secondValue, first);
1763
+ write(firstValue, second);
1764
+ }));
1765
+ }
1766
+ /**
1767
+ * Sets fields of the row an update visits. Every value is worked out before any is stored, text in its field's
1768
+ * own buffer, so a value that reads another field of the row reads it as it was.
1769
+ *
1770
+ * @param statement The fields.
1771
+ */
1772
+ setRow(statement) {
1773
+ const { builder } = this;
1774
+ const { struct } = statement.list;
1775
+ const pool = this.listPool(statement.list);
1776
+ const row = required(this.updatingRow, 'the row an update visits');
1777
+ const writes = [];
1778
+ for (const itemValue of statement.values) {
1779
+ const { field } = itemValue;
1780
+ let value;
1781
+ if ('text' in itemValue) {
1782
+ const buffer = required(pool.buffers.get(field.key), `field "${field.key}"`);
1783
+ this.text(itemValue.text.parts);
1784
+ builder.abx('FMTSET', 0, buffer.index);
1785
+ value = builder.register('string');
1786
+ builder.abx('GETS', value.index, buffer.index);
1787
+ }
1788
+ else {
1789
+ value = this.valueAs(itemValue.value, field.kind);
1790
+ }
1791
+ writes.push({ index: rowIndexOf(struct, field), value });
1792
+ if (field.optional) {
1793
+ writes.push({
1794
+ index: rowIndexOf(struct, field, true),
1795
+ value: this.load('bool', 1),
1796
+ });
1797
+ }
1798
+ }
1799
+ // A field set to undefined is 0 or "", and its flag says it isn't there.
1800
+ for (const field of statement.cleared) {
1801
+ writes.push({
1802
+ index: rowIndexOf(struct, field),
1803
+ value: this.zero(field.kind),
1804
+ });
1805
+ writes.push({
1806
+ index: rowIndexOf(struct, field, true),
1807
+ value: this.load('bool', 0),
1808
+ });
1809
+ }
1810
+ for (const { index, value } of writes) {
1811
+ builder.abc('ROWSET', value.index, row.index, 0, pool.slot.index | (index << 16));
1812
+ }
1813
+ }
949
1814
  /**
950
1815
  * Starts a timer, keeping its id in a local when the app names it.
951
1816
  *
@@ -1216,6 +2081,14 @@ export class Codegen {
1216
2081
  stateSlot(state) {
1217
2082
  return required(this.program.states.get(state), `state "${state.name}"`);
1218
2083
  }
2084
+ /** The slot a read of a state takes: the copy its body keeps, unless an updater reads it. */
2085
+ readSlot({ state, latest }) {
2086
+ return this.keptStates.has(state) &&
2087
+ !latest &&
2088
+ !this.readsLatest?.has(state)
2089
+ ? this.program.kept.get(state)
2090
+ : this.stateSlot(state);
2091
+ }
1219
2092
  listPool(list) {
1220
2093
  return required(this.program.lists.get(list), `list "${list.name}"`);
1221
2094
  }