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
@@ -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
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -118,10 +120,24 @@ export class Codegen {
118
120
  inDoubles;
119
121
  input;
120
122
  onReturn;
123
+ /** The end of each block being lowered, innermost last, which a `return` in it goes to. */
124
+ blockEnds = [];
121
125
  row;
122
126
  locals = new Map();
123
127
  /** A string register nothing writes, so it stays the empty string. Reserved, so no release reuses it. */
124
128
  emptyString = null;
129
+ /** The counter of each depth of loops, which only LOOPSET and LOOP write. Reserved, for that. */
130
+ loopCounters = [];
131
+ /** How many loops are around the code being lowered. */
132
+ loopDepth = 0;
133
+ /** Where `break` and `continue` go in each loop being lowered, innermost last. */
134
+ loopLabels = [];
135
+ /** The row the update being lowered visits, which its setRows write. */
136
+ updatingRow;
137
+ /** The states the body being lowered keeps a copy of, which its reads use. */
138
+ keptStates = new Set();
139
+ /** The states the statement being lowered reads as they are now: an updater's own. */
140
+ readsLatest;
125
141
  /**
126
142
  * @param builder The function being built.
127
143
  * @param program The program's slots and tables.
@@ -130,6 +146,7 @@ export class Codegen {
130
146
  * onReturn: where an effect's early `return` goes.
131
147
  * row: the row a list row's handler was built for, which its item reads.
132
148
  * finished: what an animation completion was passed, which its `finished` reads.
149
+ * values: a native event handler's values, by the names its locals read them by.
133
150
  */
134
151
  constructor(builder, program, options = {}) {
135
152
  this.builder = builder;
@@ -141,6 +158,9 @@ export class Codegen {
141
158
  if (options.finished) {
142
159
  this.locals.set('finished', { register: options.finished });
143
160
  }
161
+ for (const [name, register] of options.values ?? []) {
162
+ this.locals.set(name, { register });
163
+ }
144
164
  }
145
165
  /*--------------------------------------------------------------------------------------------------------------------
146
166
  - Types
@@ -171,7 +191,7 @@ export class Codegen {
171
191
  // An interned state still reads as a string.
172
192
  return this.program.enums.has(expression.state)
173
193
  ? 'string'
174
- : slotType(this.stateSlot(expression.state));
194
+ : slotType(this.readSlot(expression));
175
195
  case 'boot':
176
196
  return slotType(this.bootSlot(expression.slot));
177
197
  case 'ref':
@@ -199,8 +219,12 @@ export class Codegen {
199
219
  : 'int';
200
220
  case 'clock':
201
221
  return 'int64';
222
+ case 'native':
223
+ return expression.call.import.result;
202
224
  case 'itemField':
203
225
  return expression.field.kind;
226
+ case 'itemPresent':
227
+ return 'bool';
204
228
  case 'pi':
205
229
  case 'toFloat':
206
230
  case 'floatDivide':
@@ -218,6 +242,7 @@ export class Codegen {
218
242
  return this.typeOf(expression.operand);
219
243
  case 'compare':
220
244
  case 'stringEquals':
245
+ case 'stringIncludes':
221
246
  case 'logical':
222
247
  return 'bool';
223
248
  case 'pick':
@@ -256,7 +281,7 @@ export class Codegen {
256
281
  if (this.program.enums.has(expression.state)) {
257
282
  throw new Error(`AOT internal: state "${expression.state.name}" is interned, but read as a string`);
258
283
  }
259
- return this.get(this.stateSlot(expression.state));
284
+ return this.get(this.readSlot(expression));
260
285
  case 'boot':
261
286
  return this.get(this.bootSlot(expression.slot));
262
287
  case 'ref':
@@ -269,7 +294,9 @@ export class Codegen {
269
294
  return register;
270
295
  }
271
296
  case 'itemField':
272
- return this.itemField(expression.item, expression.field.key, type);
297
+ return this.itemField(expression.item, expression.field, type);
298
+ case 'itemPresent':
299
+ return this.itemPresent(expression);
273
300
  case 'gesture':
274
301
  return this.gesture(expression);
275
302
  case 'event':
@@ -283,6 +310,8 @@ export class Codegen {
283
310
  builder.abc(expression.clock === 'Date' ? 'DATENOW' : 'NOW', register.index);
284
311
  return register;
285
312
  }
313
+ case 'native':
314
+ return this.callNative(expression.call);
286
315
  case 'pi':
287
316
  return this.load(type, Math.PI);
288
317
  case 'toFloat':
@@ -329,6 +358,16 @@ export class Codegen {
329
358
  }
330
359
  return register;
331
360
  }
361
+ case 'stringOrder': {
362
+ const register = builder.register('int');
363
+ builder.abc('SCMP', register.index, this.valueAs(expression.left, 'string').index, this.valueAs(expression.right, 'string').index);
364
+ return register;
365
+ }
366
+ case 'stringIncludes': {
367
+ const register = builder.register('bool');
368
+ builder.abc('SHAS', register.index, this.valueAs(expression.haystack, 'string').index, this.valueAs(expression.needle, 'string').index);
369
+ return register;
370
+ }
332
371
  case 'logical': {
333
372
  const register = builder.register('bool');
334
373
  const end = builder.label();
@@ -344,6 +383,50 @@ export class Codegen {
344
383
  return this.choose(this.condition(expression.test), () => this.valueAs(expression.consequent, type), () => this.valueAs(expression.alternate, type), type);
345
384
  }
346
385
  }
386
+ /**
387
+ * Calls a native method: its arguments in consecutive registers, and its result in the one after them (an int64
388
+ * on an even register, as the runtime lays them out).
389
+ *
390
+ * @param call The call.
391
+ * @param readsResult The caller reads the result.
392
+ *
393
+ * @returns A register holding the result, or null when the method returns nothing or it isn't read.
394
+ */
395
+ callNative(call, readsResult = true) {
396
+ const results = this.nativeCall(call);
397
+ if (!results.length || !readsResult) {
398
+ return null;
399
+ }
400
+ // A copy of its own, since a run is only ever released whole.
401
+ const register = this.builder.register(results[0].type);
402
+ this.builder.abc('MOVE', register.index, results[0].index);
403
+ return register;
404
+ }
405
+ /**
406
+ * Calls a native method: its arguments in consecutive registers, then its results, a record's values one by one.
407
+ *
408
+ * @param call The call.
409
+ *
410
+ * @returns The registers the results are in.
411
+ */
412
+ nativeCall(call) {
413
+ const { builder } = this;
414
+ const { params, results } = call.import;
415
+ const values = call.callArguments.map((argument, index) => this.valueAs(argument, params[index]));
416
+ const types = [...params, ...results];
417
+ const run = types.length ? builder.consecutive(types) : [];
418
+ values.forEach((value, index) => builder.abc('MOVE', run[index].index, value.index));
419
+ const importIndex = this.program.tables.nativeImport(call.import);
420
+ if (results.includes('string')) {
421
+ // A string result is copied into the call's own buffer: CALLNS names the first, one for each string.
422
+ const buffer = required(this.program.nativeStrings.get(call), `the buffer of ${call.import.name}`);
423
+ builder.abx('CALLNS', run[0].index, importIndex, buffer.index);
424
+ }
425
+ else {
426
+ builder.abx('CALLN', run[0]?.index ?? 0, importIndex);
427
+ }
428
+ return run.slice(params.length);
429
+ }
347
430
  /**
348
431
  * The set of an interned state an expression reads, or null when it reads none.
349
432
  *
@@ -378,7 +461,7 @@ export class Codegen {
378
461
  return this.load('bool', operator === '==' ? 0 : 1);
379
462
  }
380
463
  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);
464
+ this.builder.abc('EQ', register.index, this.get(this.readSlot(read)).index, this.enumValue(set, index).index);
382
465
  if (operator === '!=') {
383
466
  this.builder.abc('NOT', register.index, register.index);
384
467
  }
@@ -618,29 +701,134 @@ export class Codegen {
618
701
  return this.get(this.input.text);
619
702
  }
620
703
  /**
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 "".
704
+ * 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
705
+ * `list[i]?.field`; `list[i].field` past the end faults, as JS throws there.
706
+ *
707
+ * @param item The row's item.
708
+ * @param field The field.
709
+ * @param type Its type.
710
+ *
711
+ * @returns The register.
712
+ */
713
+ itemField(item, field, type) {
714
+ const list = required(item.list, `the list of "${item.name}"`);
715
+ return this.rowRead(item, rowIndexOf(list.struct, field), type, false);
716
+ }
717
+ /**
718
+ * Reads one field of an item's row, its value or its flag.
622
719
  *
623
720
  * @param item The row's item.
624
- * @param key The field.
721
+ * @param index The field's index in the row.
625
722
  * @param type Its type.
723
+ * @param checked Read zero past the list's end even for an unguarded index.
626
724
  *
627
725
  * @returns The register.
628
726
  */
629
- itemField(item, key, type) {
727
+ rowRead(item, index, type, checked) {
630
728
  const { builder } = this;
631
729
  const list = required(item.list, `the list of "${item.name}"`);
632
- const field = list.struct.fields.findIndex(entry => entry.key === key);
633
730
  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, () => {
731
+ const row = item.index
732
+ ? this.valueAs(item.index, 'int')
733
+ : (this.row ?? this.load('int', required(item.row, item.name)));
734
+ const read = () => {
640
735
  const register = builder.register(type);
641
- builder.abc('ROWGET', register.index, row.index, 0, pool.index | (field << 16));
736
+ builder.abc('ROWGET', register.index, this.sourceRow(item, row).index, 0, pool.index | (index << 16));
642
737
  return register;
643
- }, () => this.zero(type), type);
738
+ };
739
+ if (item.index && !item.guarded && !checked) {
740
+ return read();
741
+ }
742
+ return this.choose(this.rowInRange(item, row), read, () => this.zero(type), type);
743
+ }
744
+ /**
745
+ * 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
746
+ * holds.
747
+ *
748
+ * @param item The row's item.
749
+ * @param row Its row, in the list it counts in.
750
+ *
751
+ * @returns An int register.
752
+ */
753
+ sourceRow(item, row) {
754
+ if (!item.through)
755
+ return row;
756
+ const source = this.builder.register('int');
757
+ this.builder.abc('ROWGET', source.index, row.index, 0, this.listPool(item.through).slot.index);
758
+ return source;
759
+ }
760
+ /**
761
+ * Whether an item's row is in its list: below the count, and not negative for an index worked out at run time.
762
+ *
763
+ * @param item The row's item.
764
+ * @param row Its row.
765
+ *
766
+ * @returns A bool register.
767
+ */
768
+ rowInRange(item, row) {
769
+ const { builder } = this;
770
+ const pool = this.listPool(item.through ?? item.list).slot;
771
+ const count = builder.register('int');
772
+ const below = builder.register('bool');
773
+ builder.abx('LEN', count.index, pool.index);
774
+ builder.abc('LT', below.index, row.index, count.index);
775
+ if (!item.index) {
776
+ return below;
777
+ }
778
+ return this.choose(below, () => {
779
+ const nonNegative = builder.register('bool');
780
+ builder.abc('LE', nonNegative.index, this.load('int', 0).index, row.index);
781
+ return nonNegative;
782
+ }, () => this.load('bool', 0), 'bool');
783
+ }
784
+ /**
785
+ * 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
786
+ * leaves out has a flag, and an object of fields is there when any of them is.
787
+ *
788
+ * @param expression The test.
789
+ *
790
+ * @returns A bool register.
791
+ */
792
+ itemPresent(expression) {
793
+ const { builder } = this;
794
+ const { item, fields } = expression;
795
+ const struct = required(item.list, `the list of "${item.name}"`).struct;
796
+ const flags = fields.filter(field => field.optional);
797
+ if (fields.length && flags.length < fields.length) {
798
+ // Some field every item has: there whenever the row is. Past the end of an unguarded index, reading the
799
+ // field faults, as JS throws there.
800
+ if (item.index && !item.guarded) {
801
+ this.rowRead(item, rowIndexOf(struct, fields[0]), fields[0].kind, false);
802
+ return this.load('bool', 1);
803
+ }
804
+ return this.rowPresent(item);
805
+ }
806
+ if (!fields.length) {
807
+ return this.rowPresent(item);
808
+ }
809
+ const result = builder.register('bool');
810
+ const end = builder.label();
811
+ flags.forEach((flag, index) => {
812
+ builder.abc('MOVE', result.index, this.rowRead(item, rowIndexOf(struct, flag, true), 'bool', false).index);
813
+ if (index < flags.length - 1) {
814
+ builder.branch('JT', end, result);
815
+ }
816
+ });
817
+ builder.place(end);
818
+ return result;
819
+ }
820
+ /**
821
+ * Whether an item's row is in its list.
822
+ *
823
+ * @param item The row's item.
824
+ *
825
+ * @returns A bool register.
826
+ */
827
+ rowPresent(item) {
828
+ const row = item.index
829
+ ? this.valueAs(item.index, 'int')
830
+ : (this.row ?? this.load('int', required(item.row, item.name)));
831
+ return this.rowInRange(item, row);
644
832
  }
645
833
  /** Zero, or the empty string, in a register of a type. */
646
834
  zero(type) {
@@ -764,17 +952,43 @@ export class Codegen {
764
952
  const { builder } = this;
765
953
  for (const part of parts) {
766
954
  const checkpoint = builder.checkpoint();
767
- if (part.kind === 'literal') {
955
+ const read = part.kind === 'literal' ? null : itemReadOf(part.value);
956
+ if (part.kind !== 'literal' &&
957
+ part.missing !== undefined &&
958
+ read &&
959
+ (read.field.optional || read.item.guarded)) {
960
+ // A field that isn't there prints as JS prints undefined.
961
+ const otherwise = builder.label();
962
+ const end = builder.label();
963
+ builder.branch('JF', otherwise, this.itemPresent({
964
+ kind: 'itemPresent',
965
+ item: read.item,
966
+ fields: [read.field],
967
+ type: BOOL,
968
+ }));
969
+ this.text([{ ...part, missing: undefined }]);
970
+ builder.branch('JMP', end);
971
+ builder.place(otherwise);
972
+ if (part.missing) {
973
+ builder.abx('FMTK', 0, this.program.tables.string(part.missing));
974
+ }
975
+ builder.place(end);
976
+ }
977
+ else if (part.kind === 'literal') {
768
978
  if (part.text) {
769
979
  builder.abx('FMTK', 0, this.program.tables.string(part.text));
770
980
  }
771
981
  }
772
982
  else if (part.kind === 'booleanWord') {
983
+ const positions = this.slicePositions(part.edits);
773
984
  builder.abc('FMTB', this.condition(part.value).index);
985
+ this.edits(part.edits, positions, 0);
774
986
  }
775
987
  else if (this.enumOf(part.value)) {
776
988
  const value = part.value;
777
- builder.abx('FMTE', this.get(this.stateSlot(value.state)).index, this.enumOf(value).set);
989
+ const positions = this.slicePositions(part.edits);
990
+ builder.abx('FMTE', this.get(this.readSlot(value)).index, this.enumOf(value).set);
991
+ this.edits(part.edits, positions, 0);
778
992
  }
779
993
  else {
780
994
  // 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 +1000,65 @@ export class Codegen {
786
1000
  : type === 'int64'
787
1001
  ? ['FMTL', 'int64']
788
1002
  : ['FMTI', 'int'];
789
- builder.abc(opcode, this.valueAs(part.value, formatType).index);
1003
+ const register = this.valueAs(part.value, formatType).index;
1004
+ const positions = this.slicePositions(part.edits);
1005
+ if (part.digits !== undefined && formatType === 'float') {
1006
+ builder.abc('FMTFX', register, part.digits);
1007
+ this.edits(part.edits, positions, 0);
1008
+ }
1009
+ else if (part.digits) {
1010
+ // A whole number's decimals are all zeros, so pad the number to leave room for them.
1011
+ builder.abc(opcode, register);
1012
+ this.edits(part.edits, positions, part.digits + 1);
1013
+ builder.abx('FMTK', 0, this.program.tables.string(`.${'0'.repeat(part.digits)}`));
1014
+ }
1015
+ else {
1016
+ builder.abc(opcode, register);
1017
+ this.edits(part.edits, positions, 0);
1018
+ }
790
1019
  }
791
1020
  builder.release(checkpoint);
792
1021
  }
793
1022
  }
1023
+ /**
1024
+ * The registers each slice of a piece cuts at, worked out before the piece is printed.
1025
+ *
1026
+ * @param edits The piece's string helpers.
1027
+ *
1028
+ * @returns The start and end registers of each slice, in order.
1029
+ */
1030
+ slicePositions(edits) {
1031
+ return (edits ?? [])
1032
+ .filter(edit => edit.kind === 'slice')
1033
+ .map(edit => [
1034
+ this.valueAs(edit.start, 'int'),
1035
+ this.valueAs(edit.end, 'int'),
1036
+ ]);
1037
+ }
1038
+ /**
1039
+ * Applies the string helpers to the piece just printed, in order.
1040
+ *
1041
+ * @param edits The padStart, slice and toUpperCase calls, in order.
1042
+ * @param positions Each slice's registers, from slicePositions.
1043
+ * @param suffix How many bytes are still to be printed after the piece, which each padStart width leaves room for.
1044
+ */
1045
+ edits(edits, positions, suffix) {
1046
+ const slices = positions[Symbol.iterator]();
1047
+ for (const edit of edits ?? []) {
1048
+ if (edit.kind === 'pad') {
1049
+ if (edit.width > suffix) {
1050
+ this.builder.abc('FMTPAD', edit.width - suffix, edit.fill.charCodeAt(0));
1051
+ }
1052
+ }
1053
+ else if (edit.kind === 'upper') {
1054
+ this.builder.abc('FMTUPPER', 0);
1055
+ }
1056
+ else {
1057
+ const [start, end] = slices.next().value;
1058
+ this.builder.abc('FMTSLICE', start.index, end.index);
1059
+ }
1060
+ }
1061
+ }
794
1062
  /*--------------------------------------------------------------------------------------------------------------------
795
1063
  - Statements
796
1064
  -------------------------------------------------------------------------------------------------------------------*/
@@ -804,10 +1072,45 @@ export class Codegen {
804
1072
  this.statement(statement);
805
1073
  }
806
1074
  }
1075
+ /**
1076
+ * Lowers a body that shares its function with another, an effect's cleanup before its body: the copies it keeps
1077
+ * are its own.
1078
+ *
1079
+ * @param statements The body's statements.
1080
+ */
1081
+ body(statements) {
1082
+ this.keptStates.clear();
1083
+ this.statements(statements);
1084
+ this.keptStates.clear();
1085
+ }
807
1086
  statement(statement) {
1087
+ const outer = this.readsLatest;
1088
+ this.readsLatest = statement.readsLatest ?? outer;
1089
+ try {
1090
+ this.lowerStatement(statement);
1091
+ }
1092
+ finally {
1093
+ this.readsLatest = outer;
1094
+ }
1095
+ }
1096
+ /** Whether a statement lowers to code: all but a field kept as it is, which the body didn't set before. */
1097
+ doesSomething(statement) {
1098
+ if (statement.kind !== 'keepField')
1099
+ return true;
1100
+ const latest = statement.readsLatest ?? this.readsLatest;
1101
+ return (this.keptStates.has(statement.state) && !latest?.has(statement.state));
1102
+ }
1103
+ lowerStatement(statement) {
808
1104
  const { builder } = this;
809
1105
  builder.at(statement.location);
810
1106
  switch (statement.kind) {
1107
+ case 'keepStates':
1108
+ for (const state of statement.states) {
1109
+ const copy = required(this.program.kept.get(state), `the copy of state "${state.name}"`);
1110
+ this.scoped(() => this.set(copy, this.get(this.stateSlot(state))));
1111
+ this.keptStates.add(state);
1112
+ }
1113
+ return;
811
1114
  case 'declareLocal': {
812
1115
  const hoisted = this.program.hoisted.get(statement.name);
813
1116
  if (statement.isHoisted && !hoisted) {
@@ -822,13 +1125,15 @@ export class Codegen {
822
1125
  // 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
1126
  const slot = hoisted ?? this.program.stringLocals.get(statement.name);
824
1127
  const checkpoint = builder.checkpoint();
825
- this.text([{ kind: 'value', value: statement.initializer }]);
1128
+ this.text(statement.text?.parts ?? [
1129
+ { kind: 'value', value: statement.initializer },
1130
+ ]);
826
1131
  builder.abx('FMTSET', 0, slot.index);
827
1132
  builder.release(checkpoint);
828
1133
  this.locals.set(statement.name, { slot });
829
1134
  return;
830
1135
  }
831
- const type = declaredType(statement.initializer);
1136
+ const type = statement.widenedTo ?? declaredType(statement.initializer);
832
1137
  const register = builder.register(type);
833
1138
  const checkpoint = builder.checkpoint();
834
1139
  builder.abc('MOVE', register.index, this.valueAs(statement.initializer, type).index);
@@ -865,12 +1170,19 @@ export class Codegen {
865
1170
  });
866
1171
  return;
867
1172
  case 'if': {
1173
+ // Branches that only keep fields as they are do nothing, so the test isn't worked out either.
1174
+ const inner = [...statement.consequent, ...(statement.alternate ?? [])];
1175
+ if (inner.some(kept => kept.kind === 'keepField') &&
1176
+ !inner.some(kept => this.doesSomething(kept))) {
1177
+ return;
1178
+ }
868
1179
  const otherwise = builder.label();
869
1180
  const checkpoint = builder.checkpoint();
870
1181
  builder.branch('JF', otherwise, this.condition(statement.test));
871
1182
  builder.release(checkpoint);
872
1183
  this.statements(statement.consequent);
873
- if (statement.alternate) {
1184
+ // An else of fields kept as they are does nothing.
1185
+ if (statement.alternate?.some(inner => this.doesSomething(inner))) {
874
1186
  const end = builder.label();
875
1187
  builder.branch('JMP', end);
876
1188
  builder.place(otherwise);
@@ -888,6 +1200,29 @@ export class Codegen {
888
1200
  case 'clearTimer':
889
1201
  this.scoped(() => builder.abc('TCLEAR', this.valueAs(statement.id, 'int').index));
890
1202
  return;
1203
+ case 'callNative': {
1204
+ if (!statement.results) {
1205
+ this.scoped(() => this.callNative(statement.call, false));
1206
+ return;
1207
+ }
1208
+ // A record's values are kept, each in a register of its own, for the locals that read them.
1209
+ const kept = statement.call.import.results.map(type => builder.register(type));
1210
+ this.scoped(() => this.nativeCall(statement.call).forEach((result, index) => builder.abc('MOVE', kept[index].index, result.index)));
1211
+ statement.results.forEach((name, index) => this.locals.set(name, { register: kept[index] }));
1212
+ return;
1213
+ }
1214
+ case 'keepField':
1215
+ if (this.doesSomething(statement)) {
1216
+ const { state } = statement;
1217
+ this.scoped(() => this.set(this.stateSlot(state), this.get(this.program.kept.get(state))));
1218
+ }
1219
+ return;
1220
+ case 'log':
1221
+ this.scoped(() => {
1222
+ this.text(statement.text.parts);
1223
+ builder.abc('FMTLOG', 0);
1224
+ });
1225
+ return;
891
1226
  case 'clearList':
892
1227
  builder.abx('CLEAR', 0, this.listPool(statement.list).slot.index);
893
1228
  return;
@@ -904,18 +1239,64 @@ export class Codegen {
904
1239
  // slice(0, end), as SLICE counts it.
905
1240
  this.scoped(() => builder.abc('SLICE', this.load('int', 0).index, this.valueAs(statement.end, 'int').index, 0, this.listPool(statement.list).slot.index));
906
1241
  return;
1242
+ case 'removeItem':
1243
+ this.scoped(() => this.removeItem(statement));
1244
+ return;
1245
+ case 'updateItems':
1246
+ this.scoped(() => this.updateItems(statement));
1247
+ return;
1248
+ case 'setRow':
1249
+ this.scoped(() => this.setRow(statement));
1250
+ return;
1251
+ case 'filterItems':
1252
+ this.scoped(() => this.filterItems(statement));
1253
+ return;
1254
+ case 'sortItems':
1255
+ this.scoped(() => this.sortItems(statement));
1256
+ return;
1257
+ case 'fillOrder':
1258
+ this.scoped(() => this.fillOrder(statement));
1259
+ return;
1260
+ case 'splitItems':
1261
+ this.scoped(() => this.splitItems(statement));
1262
+ return;
907
1263
  case 'stopAnimations':
908
1264
  case 'startAnimations':
909
1265
  case 'startChain':
910
1266
  case 'completeAfter':
911
1267
  animationStatement(this, statement, this.program.animations);
912
1268
  return;
913
- case 'return':
914
- if (!this.onReturn) {
915
- throw new Error('AOT internal: a `return` outside an effect');
1269
+ case 'block': {
1270
+ const end = builder.label();
1271
+ this.blockEnds.push(end);
1272
+ this.statements(statement.body);
1273
+ this.blockEnds.pop();
1274
+ builder.place(end);
1275
+ return;
1276
+ }
1277
+ case 'assignLocal':
1278
+ this.scoped(() => this.assignLocal(statement));
1279
+ return;
1280
+ case 'loop':
1281
+ this.loop(statement);
1282
+ return;
1283
+ case 'break':
1284
+ case 'continue': {
1285
+ const labels = this.loopLabels.at(-1);
1286
+ if (!labels) {
1287
+ throw new Error(`AOT internal: a \`${statement.kind}\` outside a loop`);
1288
+ }
1289
+ builder.branch('JMP', statement.kind === 'break' ? labels.done : labels.next);
1290
+ return;
1291
+ }
1292
+ case 'return': {
1293
+ const end = this.blockEnds.at(-1) ?? this.onReturn;
1294
+ if (!end) {
1295
+ throw new Error('AOT internal: a `return` outside a block or effect');
916
1296
  }
917
- builder.branch('JMP', this.onReturn);
1297
+ builder.branch('JMP', end);
918
1298
  return;
1299
+ }
919
1300
  case 'armCleanup':
920
1301
  this.scoped(() => this.set(required(this.program.armed.get(statement.flag), statement.flag), this.load('bool', 1)));
921
1302
  return;
@@ -923,6 +1304,92 @@ export class Codegen {
923
1304
  updateVector(this, statement, this.program.vectors);
924
1305
  }
925
1306
  }
1307
+ /**
1308
+ * A counted loop, its counter the one for its depth, so a loop inside it counts with another.
1309
+ *
1310
+ * @param bound How many times the body runs.
1311
+ * @param body Lowers the body, given the counter, which goes from `bound` down to 1.
1312
+ */
1313
+ counted(bound, body) {
1314
+ const counter = this.counterAt(this.loopDepth);
1315
+ this.loopDepth++;
1316
+ try {
1317
+ this.builder.loop(counter, bound, () => body(counter));
1318
+ }
1319
+ finally {
1320
+ this.loopDepth--;
1321
+ }
1322
+ }
1323
+ /**
1324
+ * The counter of a depth of loops, taken the first time it is needed.
1325
+ *
1326
+ * @param depth How many loops are around the loop.
1327
+ *
1328
+ * @returns The counter.
1329
+ */
1330
+ counterAt(depth) {
1331
+ return (this.loopCounters[depth] ??= this.builder.reserved('int'));
1332
+ }
1333
+ /**
1334
+ * A `for` or `for…of` loop. A `break` goes past its end, and a `continue` to its step. The body's locals are its
1335
+ * own, so a name it declares again reads the outer local after it.
1336
+ *
1337
+ * @param statement The loop.
1338
+ */
1339
+ loop(statement) {
1340
+ const { builder } = this;
1341
+ if (statement.bound === 0)
1342
+ return;
1343
+ const done = builder.label();
1344
+ const next = builder.label();
1345
+ const outer = new Map(this.locals);
1346
+ this.loopLabels.push({ done, next });
1347
+ this.counted(statement.bound, counter => this.scoped(() => {
1348
+ // The counter runs from the bound down to 1, so bound - counter is the visit's number from 0.
1349
+ if (statement.visit) {
1350
+ const visit = builder.register('int');
1351
+ builder.abc('SUB', visit.index, this.load('int', statement.bound).index, counter.index);
1352
+ this.locals.set(required(statement.visit.name, 'the visit'), {
1353
+ register: visit,
1354
+ });
1355
+ }
1356
+ if (statement.test) {
1357
+ const checkpoint = builder.checkpoint();
1358
+ builder.branch('JF', done, this.condition(statement.test));
1359
+ builder.release(checkpoint);
1360
+ }
1361
+ this.statements(statement.body);
1362
+ builder.place(next);
1363
+ this.statements(statement.step);
1364
+ }));
1365
+ this.loopLabels.pop();
1366
+ this.locals.clear();
1367
+ outer.forEach((binding, name) => this.locals.set(name, binding));
1368
+ builder.place(done);
1369
+ }
1370
+ /**
1371
+ * Sets a `let` local declared before: its register, or its slot when it is kept in one.
1372
+ *
1373
+ * @param statement The assignment.
1374
+ */
1375
+ assignLocal(statement) {
1376
+ const { builder } = this;
1377
+ const binding = this.binding(statement.name);
1378
+ if (!binding) {
1379
+ throw new Error(`AOT internal: no local "${statement.name}"`);
1380
+ }
1381
+ if ('register' in binding) {
1382
+ const { register } = binding;
1383
+ builder.abc('MOVE', register.index, this.valueAs(statement.value, register.type).index);
1384
+ return;
1385
+ }
1386
+ if (slotType(binding.slot) === 'string') {
1387
+ this.text(statement.text?.parts ?? [{ kind: 'value', value: statement.value }]);
1388
+ builder.abx('FMTSET', 0, binding.slot.index);
1389
+ return;
1390
+ }
1391
+ this.set(binding.slot, this.value(statement.value));
1392
+ }
926
1393
  /**
927
1394
  * Appends an item, its fields worked out in order into consecutive registers. A full list drops it.
928
1395
  * A text field is built in its own buffer first.
@@ -932,20 +1399,384 @@ export class Codegen {
932
1399
  appendItem(statement) {
933
1400
  const { builder } = this;
934
1401
  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}"`);
1402
+ const entries = rowEntries(statement.list.struct);
1403
+ const given = new Map(statement.values.map(value => [value.field, value]));
1404
+ const row = builder.consecutive(entries.map(({ field, presence }) => presence ? 'bool' : field.kind === 'string' ? 'string' : field.kind));
1405
+ entries.forEach(({ field, presence }, index) => this.scoped(() => {
1406
+ const itemValue = given.get(field);
1407
+ if (presence || !itemValue) {
1408
+ // A field the item leaves out is 0 or "", and its flag says so.
1409
+ builder.abc('MOVE', row[index].index, presence
1410
+ ? this.load('bool', itemValue ? 1 : 0).index
1411
+ : this.zero(field.kind).index);
1412
+ }
1413
+ else if ('text' in itemValue) {
1414
+ const buffer = required(pool.buffers.get(field.key), `field "${field.key}"`);
939
1415
  this.text(itemValue.text.parts);
940
1416
  builder.abx('FMTSET', 0, buffer.index);
941
1417
  builder.abx('GETS', row[index].index, buffer.index);
942
1418
  }
943
1419
  else {
944
- builder.abc('MOVE', row[index].index, this.valueAs(itemValue.value, itemValue.field.kind).index);
1420
+ builder.abc('MOVE', row[index].index, this.valueAs(itemValue.value, field.kind).index);
945
1421
  }
946
1422
  }));
947
1423
  builder.abx('APPEND', row[0].index, pool.slot.index);
948
1424
  }
1425
+ /**
1426
+ * Drops a row, moving the rest up. Past either end, nothing is removed.
1427
+ *
1428
+ * @param statement The removal.
1429
+ */
1430
+ removeItem(statement) {
1431
+ const { builder } = this;
1432
+ const pool = this.listPool(statement.list).slot;
1433
+ let index = this.valueAs(statement.index, 'int');
1434
+ if (statement.negative === 'sliced') {
1435
+ // [...items.slice(0, -1), ...items.slice(0)] repeats the list, which a list can't hold.
1436
+ const list = statement.list.name;
1437
+ this.trapWhen('EQ', index, -1, `[...${list}.slice(0, -1), ...${list}.slice(0)] repeats the list`);
1438
+ }
1439
+ if (statement.negative !== 'none') {
1440
+ index = this.countedBack(index, pool, statement.negative === 'spliced');
1441
+ }
1442
+ builder.abx('REMOVE', index.index, pool.index);
1443
+ }
1444
+ /**
1445
+ * Stops the app with a message when a whole number compares to a constant: is equal to it, or below it.
1446
+ *
1447
+ * @param compare EQ or LT.
1448
+ * @param value The number.
1449
+ * @param constant The constant.
1450
+ * @param message Why it stops.
1451
+ */
1452
+ trapWhen(compare, value, constant, message) {
1453
+ const { builder } = this;
1454
+ const stops = builder.register('bool');
1455
+ builder.abc(compare, stops.index, value.index, this.load('int', constant).index);
1456
+ const goesOn = builder.label();
1457
+ builder.branch('JF', goesOn, stops);
1458
+ builder.abx('TRAP', 0, this.program.tables.string(message));
1459
+ builder.place(goesOn);
1460
+ }
1461
+ /**
1462
+ * A row index with a negative one counted back from the end, as `toSpliced`, `with` and a pair of slices count it.
1463
+ *
1464
+ * @param index The index.
1465
+ * @param pool The list's pool.
1466
+ * @param floor One still negative after counting back is 0, as `toSpliced` makes it.
1467
+ *
1468
+ * @returns The row.
1469
+ */
1470
+ countedBack(index, pool, floor) {
1471
+ const { builder } = this;
1472
+ const negative = builder.register('bool');
1473
+ builder.abc('LT', negative.index, index.index, this.load('int', 0).index);
1474
+ return this.choose(negative, () => {
1475
+ const count = builder.register('int');
1476
+ builder.abx('LEN', count.index, pool.index);
1477
+ const back = builder.register('int');
1478
+ builder.abc('ADD', back.index, index.index, count.index);
1479
+ if (floor) {
1480
+ builder.abc('MAX', back.index, back.index, this.load('int', 0).index);
1481
+ }
1482
+ return back;
1483
+ }, () => index, 'int');
1484
+ }
1485
+ /**
1486
+ * 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
1487
+ * the one row `with` names, which must be in the list.
1488
+ *
1489
+ * @param statement The update.
1490
+ */
1491
+ updateItems(statement) {
1492
+ const { builder } = this;
1493
+ const pool = this.listPool(statement.list).slot;
1494
+ const name = required(statement.row.name, 'the update row');
1495
+ const visit = (row) => {
1496
+ this.locals.set(name, { register: row });
1497
+ this.updatingRow = row;
1498
+ this.statements(statement.body);
1499
+ this.updatingRow = undefined;
1500
+ this.locals.delete(name);
1501
+ };
1502
+ if (statement.index) {
1503
+ const index = this.valueAs(statement.index, 'int');
1504
+ if (statement.negativeKeeps) {
1505
+ const list = statement.list.name;
1506
+ this.trapWhen('LT', index, 0, `${list}.with(n, …) keeps fields of ${list}[n], which is undefined for a negative n`);
1507
+ }
1508
+ const row = this.countedBack(index, pool, false);
1509
+ // A read of the row faults past the end, as with() throws there.
1510
+ const [first] = rowEntries(statement.list.struct);
1511
+ builder.abc('ROWGET', builder.register(first.field.kind).index, row.index, 0, pool.index);
1512
+ visit(row);
1513
+ return;
1514
+ }
1515
+ const count = builder.register('int');
1516
+ builder.abx('LEN', count.index, pool.index);
1517
+ const capacity = this.load('int', statement.list.capacity);
1518
+ const done = builder.label();
1519
+ this.counted(statement.list.capacity, counter => this.scoped(() => {
1520
+ const row = builder.register('int');
1521
+ builder.abc('SUB', row.index, capacity.index, counter.index);
1522
+ const inList = builder.register('bool');
1523
+ builder.abc('LT', inList.index, row.index, count.index);
1524
+ builder.branch('JF', done, inList);
1525
+ visit(row);
1526
+ }));
1527
+ builder.place(done);
1528
+ }
1529
+ /**
1530
+ * 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.
1531
+ *
1532
+ * @param list The list.
1533
+ * @param backwards Visit the last row first.
1534
+ * @param visit Lowers the body, given the row.
1535
+ */
1536
+ eachRow(list, backwards, visit) {
1537
+ const { builder } = this;
1538
+ const pool = this.listPool(list).slot;
1539
+ const count = builder.register('int');
1540
+ builder.abx('LEN', count.index, pool.index);
1541
+ const capacity = this.load('int', list.capacity);
1542
+ const done = builder.label();
1543
+ this.counted(list.capacity, counter => this.scoped(() => {
1544
+ // The counter runs from the cap down to 1, so cap - counter is the visit's number from 0.
1545
+ const row = builder.register('int');
1546
+ builder.abc('SUB', row.index, capacity.index, counter.index);
1547
+ const inList = builder.register('bool');
1548
+ if (backwards) {
1549
+ builder.abc('SUB', row.index, count.index, row.index);
1550
+ builder.abc('SUB', row.index, row.index, this.load('int', 1).index);
1551
+ builder.abc('LE', inList.index, this.load('int', 0).index, row.index);
1552
+ }
1553
+ else {
1554
+ builder.abc('LT', inList.index, row.index, count.index);
1555
+ }
1556
+ builder.branch('JF', done, inList);
1557
+ visit(row);
1558
+ }));
1559
+ builder.place(done);
1560
+ }
1561
+ /**
1562
+ * Drops the rows a filter doesn't keep, last to first, so the rows still to test stay where they are.
1563
+ *
1564
+ * @param statement The filter.
1565
+ */
1566
+ filterItems(statement) {
1567
+ const { builder } = this;
1568
+ const pool = this.listPool(statement.list).slot;
1569
+ const name = required(statement.position.name, 'the filtered row');
1570
+ this.eachRow(statement.list, true, row => {
1571
+ this.locals.set(name, { register: row });
1572
+ const kept = builder.label();
1573
+ builder.branch('JT', kept, this.condition(statement.keep));
1574
+ builder.abx('REMOVE', row.index, pool.index);
1575
+ builder.place(kept);
1576
+ this.locals.delete(name);
1577
+ });
1578
+ }
1579
+ /**
1580
+ * Fills a list of strings with a string's pieces. Without a limit it keeps every piece the list holds; without a
1581
+ * separator, the whole string.
1582
+ *
1583
+ * @param statement The split.
1584
+ */
1585
+ splitItems(statement) {
1586
+ const { builder } = this;
1587
+ const pool = this.listPool(statement.list).slot;
1588
+ if (!statement.separator) {
1589
+ // The string is read before the clear, which only resets the count, so a row of this list still reads.
1590
+ const text = this.valueAs(statement.text, 'string');
1591
+ builder.abx('CLEAR', 0, pool.index);
1592
+ builder.abx('APPEND', text.index, pool.index);
1593
+ return;
1594
+ }
1595
+ builder.abc('SPLIT', this.valueAs(statement.text, 'string').index, this.valueAs(statement.separator, 'string').index, (statement.limit
1596
+ ? this.valueAs(statement.limit, 'int')
1597
+ : this.load('int', -1)).index, pool.index);
1598
+ }
1599
+ /**
1600
+ * Fills a filtered or sorted list with the source rows its first filter keeps, or all of them.
1601
+ *
1602
+ * @param statement The fill.
1603
+ */
1604
+ fillOrder(statement) {
1605
+ const { builder } = this;
1606
+ const pool = this.listPool(statement.list).slot;
1607
+ const source = required(statement.list.derived?.source, 'a filtered or sorted list');
1608
+ const name = required(statement.row.name, 'the visited row');
1609
+ builder.abx('CLEAR', 0, pool.index);
1610
+ this.eachRow(source, false, row => {
1611
+ const skip = builder.label();
1612
+ if (statement.keep) {
1613
+ this.locals.set(name, { register: row });
1614
+ builder.branch('JF', skip, this.condition(statement.keep));
1615
+ this.locals.delete(name);
1616
+ }
1617
+ builder.abx('APPEND', row.index, pool.index);
1618
+ builder.place(skip);
1619
+ });
1620
+ }
1621
+ /**
1622
+ * Sorts a list's rows in place by insertion: each row moves back past the rows before it that go after it, so
1623
+ * equal rows keep their order, as JS's sort does.
1624
+ *
1625
+ * @param statement The sort.
1626
+ */
1627
+ sortItems(statement) {
1628
+ const { builder } = this;
1629
+ const { list } = statement;
1630
+ const pool = this.listPool(list).slot;
1631
+ const firstName = required(statement.first.name, 'the first row');
1632
+ const secondName = required(statement.second.name, 'the second row');
1633
+ const count = builder.register('int');
1634
+ builder.abx('LEN', count.index, pool.index);
1635
+ const capacity = this.load('int', list.capacity);
1636
+ const one = this.load('int', 1);
1637
+ // Both counters are taken before the loops, ahead of the registers the loops work in.
1638
+ this.counterAt(this.loopDepth);
1639
+ this.counterAt(this.loopDepth + 1);
1640
+ const sorted = builder.label();
1641
+ this.counted(list.capacity, outer => this.scoped(() => {
1642
+ // Row cap - counter + 1 moves back next, from row 1 on.
1643
+ const moving = builder.register('int');
1644
+ builder.abc('SUB', moving.index, capacity.index, outer.index);
1645
+ builder.abc('ADD', moving.index, moving.index, one.index);
1646
+ const inList = builder.register('bool');
1647
+ builder.abc('LT', inList.index, moving.index, count.index);
1648
+ builder.branch('JF', sorted, inList);
1649
+ const placed = builder.label();
1650
+ this.counted(list.capacity, inner => this.scoped(() => {
1651
+ // It is at row moving - (cap - counter) now; it stops at row 0.
1652
+ const second = builder.register('int');
1653
+ builder.abc('SUB', second.index, capacity.index, inner.index);
1654
+ builder.abc('SUB', second.index, moving.index, second.index);
1655
+ const above = builder.register('bool');
1656
+ builder.abc('LT', above.index, this.load('int', 0).index, second.index);
1657
+ builder.branch('JF', placed, above);
1658
+ const first = builder.register('int');
1659
+ builder.abc('SUB', first.index, second.index, one.index);
1660
+ this.locals.set(firstName, { register: first });
1661
+ this.locals.set(secondName, { register: second });
1662
+ builder.branch('JF', placed, this.after(statement.order));
1663
+ this.locals.delete(firstName);
1664
+ this.locals.delete(secondName);
1665
+ this.swapRows(list, first, second);
1666
+ }));
1667
+ builder.place(placed);
1668
+ }));
1669
+ builder.place(sorted);
1670
+ }
1671
+ /**
1672
+ * Whether a compare function's result puts the first row after the second: it is above zero.
1673
+ *
1674
+ * @param order The result.
1675
+ *
1676
+ * @returns A bool register.
1677
+ */
1678
+ after(order) {
1679
+ const { builder } = this;
1680
+ const value = this.value(order);
1681
+ const type = value.type;
1682
+ const result = builder.register('bool');
1683
+ if (type === 'bool') {
1684
+ // true is 1, which puts the first row after the second.
1685
+ builder.abc('MOVE', result.index, value.index);
1686
+ }
1687
+ else if (type === 'float' || type === 'double') {
1688
+ builder.abc(type === 'float' ? 'FLT' : 'DLT', result.index, this.load(type, 0).index, value.index);
1689
+ }
1690
+ else if (type === 'int64') {
1691
+ builder.abc('LLT', result.index, this.load('int64', 0).index, value.index);
1692
+ }
1693
+ else {
1694
+ builder.abc('LT', result.index, this.load('int', 0).index, value.index);
1695
+ }
1696
+ return result;
1697
+ }
1698
+ /**
1699
+ * Swaps two rows of a list, field by field. A string goes through its field's own buffer.
1700
+ *
1701
+ * @param list The list.
1702
+ * @param first One row.
1703
+ * @param second The other.
1704
+ */
1705
+ swapRows(list, first, second) {
1706
+ const { builder } = this;
1707
+ const pool = this.listPool(list);
1708
+ rowEntries(list.struct).forEach(({ field, presence }, index) => this.scoped(() => {
1709
+ const extension = pool.slot.index | (index << 16);
1710
+ const read = (row, type) => {
1711
+ const register = builder.register(type);
1712
+ builder.abc('ROWGET', register.index, row.index, 0, extension);
1713
+ return register;
1714
+ };
1715
+ const write = (value, row) => builder.abc('ROWSET', value.index, row.index, 0, extension);
1716
+ if (!presence && field.kind === 'string') {
1717
+ const buffer = required(pool.buffers.get(field.key), `field "${field.key}"`);
1718
+ builder.abx('SETS', read(first, 'string').index, buffer.index);
1719
+ write(read(second, 'string'), first);
1720
+ const kept = builder.register('string');
1721
+ builder.abx('GETS', kept.index, buffer.index);
1722
+ write(kept, second);
1723
+ return;
1724
+ }
1725
+ const type = presence ? 'bool' : field.kind;
1726
+ const firstValue = read(first, type);
1727
+ const secondValue = read(second, type);
1728
+ write(secondValue, first);
1729
+ write(firstValue, second);
1730
+ }));
1731
+ }
1732
+ /**
1733
+ * Sets fields of the row an update visits. Every value is worked out before any is stored, text in its field's
1734
+ * own buffer, so a value that reads another field of the row reads it as it was.
1735
+ *
1736
+ * @param statement The fields.
1737
+ */
1738
+ setRow(statement) {
1739
+ const { builder } = this;
1740
+ const { struct } = statement.list;
1741
+ const pool = this.listPool(statement.list);
1742
+ const row = required(this.updatingRow, 'the row an update visits');
1743
+ const writes = [];
1744
+ for (const itemValue of statement.values) {
1745
+ const { field } = itemValue;
1746
+ let value;
1747
+ if ('text' in itemValue) {
1748
+ const buffer = required(pool.buffers.get(field.key), `field "${field.key}"`);
1749
+ this.text(itemValue.text.parts);
1750
+ builder.abx('FMTSET', 0, buffer.index);
1751
+ value = builder.register('string');
1752
+ builder.abx('GETS', value.index, buffer.index);
1753
+ }
1754
+ else {
1755
+ value = this.valueAs(itemValue.value, field.kind);
1756
+ }
1757
+ writes.push({ index: rowIndexOf(struct, field), value });
1758
+ if (field.optional) {
1759
+ writes.push({
1760
+ index: rowIndexOf(struct, field, true),
1761
+ value: this.load('bool', 1),
1762
+ });
1763
+ }
1764
+ }
1765
+ // A field set to undefined is 0 or "", and its flag says it isn't there.
1766
+ for (const field of statement.cleared) {
1767
+ writes.push({
1768
+ index: rowIndexOf(struct, field),
1769
+ value: this.zero(field.kind),
1770
+ });
1771
+ writes.push({
1772
+ index: rowIndexOf(struct, field, true),
1773
+ value: this.load('bool', 0),
1774
+ });
1775
+ }
1776
+ for (const { index, value } of writes) {
1777
+ builder.abc('ROWSET', value.index, row.index, 0, pool.slot.index | (index << 16));
1778
+ }
1779
+ }
949
1780
  /**
950
1781
  * Starts a timer, keeping its id in a local when the app names it.
951
1782
  *
@@ -1216,6 +2047,14 @@ export class Codegen {
1216
2047
  stateSlot(state) {
1217
2048
  return required(this.program.states.get(state), `state "${state.name}"`);
1218
2049
  }
2050
+ /** The slot a read of a state takes: the copy its body keeps, unless an updater reads it. */
2051
+ readSlot({ state, latest }) {
2052
+ return this.keptStates.has(state) &&
2053
+ !latest &&
2054
+ !this.readsLatest?.has(state)
2055
+ ? this.program.kept.get(state)
2056
+ : this.stateSlot(state);
2057
+ }
1219
2058
  listPool(list) {
1220
2059
  return required(this.program.lists.get(list), `list "${list.name}"`);
1221
2060
  }