embedded-react 0.19.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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -0,0 +1,2168 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*
17
+ * Lowers IR expressions, text, statements and state-driven prop values to bytecode.
18
+ *
19
+ * The VM converts nothing by itself, so each value here is worked out in a type of its own, and converted where the
20
+ * language needs it: an int beside a float is a float, a value worked out at boot is a double, and an assignment
21
+ * converts to the field it writes.
22
+ */
23
+ /*----------------------------------------------------------------------------------------------------------------------
24
+ - Imports
25
+ ---------------------------------------------------------------------------------------------------------------------*/
26
+ import { aotError, constantText } from '../diagnostics.mjs';
27
+ import { animationStatement } from './animations.mjs';
28
+ import { EventField, MathFn, ValueType } from './format.mjs';
29
+ import { abiProp, constantNumber, floatBits } from './props.mjs';
30
+ import { updateVector } from './vectors.mjs';
31
+ import { itemReadOf, rowEntries, rowIndexOf } from '../list-items.mjs';
32
+ import { BOOL } from '../ir/types.mjs';
33
+ /*----------------------------------------------------------------------------------------------------------------------
34
+ - Constants
35
+ ---------------------------------------------------------------------------------------------------------------------*/
36
+ /** What rounding a double adds before it floors: a half rounds up. */
37
+ const ROUND_HALF_UP = 0.5;
38
+ /** The whole-number helpers' opcodes; the 64-bit ones add L. */
39
+ const HELPER_OPCODES = {
40
+ add: 'ADD',
41
+ sub: 'SUB',
42
+ mul: 'MUL',
43
+ neg: 'NEG',
44
+ mod: 'MOD',
45
+ abs: 'ABS',
46
+ min: 'MIN',
47
+ max: 'MAX',
48
+ floordiv: 'FLOORDIV',
49
+ ceildiv: 'CEILDIV',
50
+ rounddiv: 'ROUNDDIV',
51
+ div: 'DIV',
52
+ };
53
+ /** The arithmetic opcodes for each type. */
54
+ const ARITHMETIC_OPCODES = {
55
+ int: { '+': 'ADD', '-': 'SUB', '*': 'MUL', '/': 'DIV', '%': 'MOD' },
56
+ int64: { '+': 'ADDL', '-': 'SUBL', '*': 'MULL', '/': 'DIVL', '%': 'MODL' },
57
+ float: { '+': 'FADD', '-': 'FSUB', '*': 'FMUL', '/': 'FDIV' },
58
+ double: { '+': 'DADD', '-': 'DSUB', '*': 'DMUL', '/': 'DDIV' },
59
+ };
60
+ /** The comparison opcodes for each type: equal, less than, at most. */
61
+ const COMPARE_OPCODES = {
62
+ int: ['EQ', 'LT', 'LE'],
63
+ int64: ['LEQ', 'LLT', 'LLE'],
64
+ float: ['FEQ', 'FLT', 'FLE'],
65
+ double: ['DEQ', 'DLT', 'DLE'],
66
+ };
67
+ /** The conversion opcodes, by source and destination type. */
68
+ const CONVERSIONS = {
69
+ 'int>float': 'ITOF',
70
+ 'int>double': 'ITOD',
71
+ 'int>int64': 'ITOL',
72
+ 'float>int': 'FTOI',
73
+ 'float>double': 'FTOD',
74
+ 'float>int64': 'FTOL',
75
+ 'double>int': 'DTOI',
76
+ 'double>float': 'DTOF',
77
+ 'double>int64': 'DTOL',
78
+ 'int64>int': 'LTOI',
79
+ 'int64>float': 'LTOF',
80
+ 'int64>double': 'LTOD',
81
+ };
82
+ /** The event field each touch field, and what a <Dial> passes, reads. */
83
+ const EVENT_FIELDS = {
84
+ x: EventField.x,
85
+ y: EventField.y,
86
+ dx: EventField.dx,
87
+ dy: EventField.dy,
88
+ vx: EventField.vx,
89
+ vy: EventField.vy,
90
+ value: EventField.value,
91
+ value_start: EventField.valueStart,
92
+ };
93
+ /** The event field each onLayout field reads. */
94
+ const LAYOUT_FIELDS = {
95
+ x: EventField.layoutX,
96
+ y: EventField.layoutY,
97
+ width: EventField.layoutWidth,
98
+ height: EventField.layoutHeight,
99
+ };
100
+ /** The engine's display values. */
101
+ const DISPLAY_FLEX = 0;
102
+ const DISPLAY_NONE = 1;
103
+ /** A timer delay is ToInt32 of the value: its low 32 bits. */
104
+ const TWO_TO_32 = 2 ** 32;
105
+ const INT32_MAX = 0x7fffffff;
106
+ /** The int range, for an immediate that fits LOADI. */
107
+ const IMMEDIATE_MIN = -32768;
108
+ const IMMEDIATE_MAX = 32767;
109
+ /*----------------------------------------------------------------------------------------------------------------------
110
+ - Classes
111
+ ---------------------------------------------------------------------------------------------------------------------*/
112
+ /**
113
+ * Lowers IR into one function.
114
+ *
115
+ * @class Codegen
116
+ */
117
+ export class Codegen {
118
+ builder;
119
+ program;
120
+ inDoubles;
121
+ input;
122
+ onReturn;
123
+ /** The end of each block being lowered, innermost last, which a `return` in it goes to. */
124
+ blockEnds = [];
125
+ row;
126
+ locals = new Map();
127
+ /** A string register nothing writes, so it stays the empty string. Reserved, so no release reuses it. */
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;
141
+ /**
142
+ * @param builder The function being built.
143
+ * @param program The program's slots and tables.
144
+ * @param options inDoubles: fractions are worked out in double precision, for a value worked out at boot.
145
+ * input: the <TextInput> a CHANGE_TEXT handler reads.
146
+ * onReturn: where an effect's early `return` goes.
147
+ * row: the row a list row's handler was built for, which its item reads.
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.
150
+ */
151
+ constructor(builder, program, options = {}) {
152
+ this.builder = builder;
153
+ this.program = program;
154
+ this.inDoubles = options.inDoubles ?? false;
155
+ this.input = options.input ?? null;
156
+ this.onReturn = options.onReturn ?? null;
157
+ this.row = options.row ?? null;
158
+ if (options.finished) {
159
+ this.locals.set('finished', { register: options.finished });
160
+ }
161
+ for (const [name, register] of options.values ?? []) {
162
+ this.locals.set(name, { register });
163
+ }
164
+ }
165
+ /*--------------------------------------------------------------------------------------------------------------------
166
+ - Types
167
+ -------------------------------------------------------------------------------------------------------------------*/
168
+ /**
169
+ * The type an expression is worked out in.
170
+ *
171
+ * @param expression The expression.
172
+ *
173
+ * @returns Its type.
174
+ */
175
+ typeOf(expression) {
176
+ const fraction = this.inDoubles ? 'double' : 'float';
177
+ switch (expression.kind) {
178
+ case 'number':
179
+ return expression.type.kind === 'float'
180
+ ? fraction
181
+ : expression.type.kind === 'int64'
182
+ ? 'int64'
183
+ : expression.type.kind === 'bool'
184
+ ? 'bool'
185
+ : 'int';
186
+ case 'string':
187
+ return 'string';
188
+ case 'boolean':
189
+ return 'bool';
190
+ case 'state':
191
+ // An interned state still reads as a string.
192
+ return this.program.enums.has(expression.state)
193
+ ? 'string'
194
+ : slotType(this.readSlot(expression));
195
+ case 'boot':
196
+ return slotType(this.bootSlot(expression.slot));
197
+ case 'ref':
198
+ return slotType(this.refSlot(expression.ref));
199
+ case 'local': {
200
+ if (expression.local.expression) {
201
+ return this.typeOf(expression.local.expression);
202
+ }
203
+ const binding = this.binding(expression.local.name);
204
+ return !binding
205
+ ? 'string'
206
+ : 'register' in binding
207
+ ? binding.register.type
208
+ : slotType(binding.slot);
209
+ }
210
+ case 'event':
211
+ return expression.field === 'changed_text'
212
+ ? 'string'
213
+ : ['vx', 'vy', 'value', 'value_start'].includes(expression.field)
214
+ ? 'float'
215
+ : 'int';
216
+ case 'gesture':
217
+ return expression.field === 'vx' || expression.field === 'vy'
218
+ ? 'float'
219
+ : 'int';
220
+ case 'clock':
221
+ return 'int64';
222
+ case 'native':
223
+ return expression.call.import.result;
224
+ case 'itemField':
225
+ return expression.field.kind;
226
+ case 'itemPresent':
227
+ return 'bool';
228
+ case 'pi':
229
+ case 'toFloat':
230
+ case 'floatDivide':
231
+ case 'floatMath':
232
+ return fraction;
233
+ case 'unary':
234
+ return expression.operator === '!'
235
+ ? 'bool'
236
+ : promoted(this.typeOf(expression.operand));
237
+ case 'helper':
238
+ return expression.bits === 64 ? 'int64' : 'int';
239
+ case 'arithmetic':
240
+ return usual(this.typeOf(expression.left), this.typeOf(expression.right));
241
+ case 'wholeRound':
242
+ return this.typeOf(expression.operand);
243
+ case 'compare':
244
+ case 'stringEquals':
245
+ case 'stringIncludes':
246
+ case 'logical':
247
+ return 'bool';
248
+ case 'pick':
249
+ return usual(this.typeOf(expression.left), this.typeOf(expression.right));
250
+ case 'conditional':
251
+ return usual(this.typeOf(expression.consequent), this.typeOf(expression.alternate));
252
+ default:
253
+ // layout, narrowRemainder, trunc, toInt, and what a package refuses
254
+ return 'int';
255
+ }
256
+ }
257
+ /*--------------------------------------------------------------------------------------------------------------------
258
+ - Values
259
+ -------------------------------------------------------------------------------------------------------------------*/
260
+ /**
261
+ * Works an expression out into a register of its type.
262
+ *
263
+ * @param expression The expression.
264
+ *
265
+ * @returns The register. A local's may be its own: never write to what this returns.
266
+ */
267
+ value(expression) {
268
+ const { builder } = this;
269
+ const type = this.typeOf(expression);
270
+ switch (expression.kind) {
271
+ case 'number':
272
+ return this.load(type, expression.value);
273
+ case 'string': {
274
+ const register = builder.register('string');
275
+ builder.abx('LOADS', register.index, this.program.tables.string(expression.value));
276
+ return register;
277
+ }
278
+ case 'boolean':
279
+ return this.load('bool', expression.value ? 1 : 0);
280
+ case 'state':
281
+ if (this.program.enums.has(expression.state)) {
282
+ throw new Error(`AOT internal: state "${expression.state.name}" is interned, but read as a string`);
283
+ }
284
+ return this.get(this.readSlot(expression));
285
+ case 'boot':
286
+ return this.get(this.bootSlot(expression.slot));
287
+ case 'ref':
288
+ return this.get(this.refSlot(expression.ref));
289
+ case 'local':
290
+ return this.local(expression);
291
+ case 'listLength': {
292
+ const register = builder.register('int');
293
+ builder.abx('LEN', register.index, this.listPool(expression.list).slot.index);
294
+ return register;
295
+ }
296
+ case 'itemField':
297
+ return this.itemField(expression.item, expression.field, type);
298
+ case 'itemPresent':
299
+ return this.itemPresent(expression);
300
+ case 'gesture':
301
+ return this.gesture(expression);
302
+ case 'event':
303
+ return expression.field === 'changed_text'
304
+ ? this.changedText()
305
+ : this.event(type, EVENT_FIELDS[expression.field]);
306
+ case 'layout':
307
+ return this.event('int', LAYOUT_FIELDS[expression.field]);
308
+ case 'clock': {
309
+ const register = builder.register('int64');
310
+ builder.abc(expression.clock === 'Date' ? 'DATENOW' : 'NOW', register.index);
311
+ return register;
312
+ }
313
+ case 'native':
314
+ return this.callNative(expression.call);
315
+ case 'pi':
316
+ return this.load(type, Math.PI);
317
+ case 'toFloat':
318
+ case 'wholeRound':
319
+ return this.convert(this.value(expression.operand), type);
320
+ case 'unary':
321
+ return this.unary(expression.operator, expression.operand, type);
322
+ case 'helper': {
323
+ const argumentType = expression.bits === 64 ? 'int64' : 'int';
324
+ const argumentRegisters = expression.callArguments.map(argument => this.valueAs(argument, argumentType));
325
+ const register = builder.register(argumentType);
326
+ builder.abc(HELPER_OPCODES[expression.helper] +
327
+ (expression.bits === 64 ? 'L' : ''), register.index, argumentRegisters[0].index, (argumentRegisters[1] ?? argumentRegisters[0]).index);
328
+ return register;
329
+ }
330
+ case 'arithmetic':
331
+ return this.arithmetic(expression.operator, expression.left, expression.right, type);
332
+ case 'floatDivide':
333
+ return this.arithmetic('/', expression.left, expression.right, type);
334
+ case 'narrowRemainder': {
335
+ const operandType = usual(this.typeOf(expression.left), this.typeOf(expression.right));
336
+ return this.convert(this.arithmetic('%', expression.left, expression.right, operandType), 'int');
337
+ }
338
+ case 'floatMath': {
339
+ const argumentRegisters = expression.callArguments.map(argument => this.valueAs(argument, type));
340
+ const register = builder.register(type);
341
+ builder.abc(type === 'double' ? 'DMATH' : 'FMATH', register.index, argumentRegisters[0].index, (argumentRegisters[1] ?? argumentRegisters[0]).index, MathFn[expression.mathFunction]);
342
+ return register;
343
+ }
344
+ case 'trunc':
345
+ case 'toInt':
346
+ // Worked out as a float, or a double at boot.
347
+ return this.convert(this.valueAs(expression.operand, this.inDoubles ? 'double' : 'float'), 'int');
348
+ case 'compare':
349
+ return this.compare(expression.operator, expression.left, expression.right);
350
+ case 'stringEquals': {
351
+ if (this.enumOf(expression.left) || this.enumOf(expression.right)) {
352
+ return this.enumEquals(expression.operator, expression.left, expression.right);
353
+ }
354
+ const register = builder.register('bool');
355
+ builder.abc('SEQ', register.index, this.valueAs(expression.left, 'string').index, this.valueAs(expression.right, 'string').index);
356
+ if (expression.operator === '!=') {
357
+ builder.abc('NOT', register.index, register.index);
358
+ }
359
+ return register;
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
+ }
371
+ case 'logical': {
372
+ const register = builder.register('bool');
373
+ const end = builder.label();
374
+ builder.abc('MOVE', register.index, this.condition(expression.left).index);
375
+ builder.branch(expression.operator === '&&' ? 'JF' : 'JT', end, register);
376
+ builder.abc('MOVE', register.index, this.condition(expression.right).index);
377
+ builder.place(end);
378
+ return register;
379
+ }
380
+ case 'pick':
381
+ return this.pick(expression.operator, expression.left, expression.right, type);
382
+ case 'conditional':
383
+ return this.choose(this.condition(expression.test), () => this.valueAs(expression.consequent, type), () => this.valueAs(expression.alternate, type), type);
384
+ }
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
+ }
430
+ /**
431
+ * The set of an interned state an expression reads, or null when it reads none.
432
+ *
433
+ * @param expression The expression.
434
+ *
435
+ * @returns The set.
436
+ */
437
+ enumOf(expression) {
438
+ return expression.kind === 'state'
439
+ ? (this.program.enums.get(expression.state) ?? null)
440
+ : null;
441
+ }
442
+ /**
443
+ * A comparison of an interned state with a literal, or with itself, as an int compare. A literal it never
444
+ * holds is never equal.
445
+ *
446
+ * @param operator `==` or `!=`.
447
+ * @param left One side.
448
+ * @param right The other.
449
+ *
450
+ * @returns A bool register.
451
+ */
452
+ enumEquals(operator, left, right) {
453
+ const read = (this.enumOf(left) ? left : right);
454
+ const other = read === left ? right : left;
455
+ const { set, values } = this.enumOf(read);
456
+ if (other.kind !== 'string') {
457
+ return this.load('bool', operator === '==' ? 1 : 0);
458
+ }
459
+ const index = values.indexOf(other.value);
460
+ if (index < 0) {
461
+ return this.load('bool', operator === '==' ? 0 : 1);
462
+ }
463
+ const register = this.builder.register('bool');
464
+ this.builder.abc('EQ', register.index, this.get(this.readSlot(read)).index, this.enumValue(set, index).index);
465
+ if (operator === '!=') {
466
+ this.builder.abc('NOT', register.index, register.index);
467
+ }
468
+ return register;
469
+ }
470
+ /**
471
+ * One value of an enum set in a register.
472
+ *
473
+ * @param set The set.
474
+ * @param index The value's index in it.
475
+ *
476
+ * @returns The register.
477
+ */
478
+ enumValue(set, index) {
479
+ const register = this.builder.register('enum');
480
+ this.builder.abx('LOADE', register.index, index, set);
481
+ return register;
482
+ }
483
+ /**
484
+ * Works an expression out and converts it as an assignment to a type does.
485
+ *
486
+ * @param expression The expression.
487
+ * @param type The type it goes into.
488
+ *
489
+ * @returns A register of that type.
490
+ */
491
+ valueAs(expression, type) {
492
+ return this.convert(this.value(expression), type);
493
+ }
494
+ /**
495
+ * An expression as a condition: true exactly when JS finds it truthy. A string is truthy
496
+ * when it isn't empty.
497
+ *
498
+ * @param expression The expression.
499
+ *
500
+ * @returns A bool register.
501
+ */
502
+ condition(expression) {
503
+ return this.truthy(this.value(expression));
504
+ }
505
+ /**
506
+ * Converts a register to another type, as an assignment does. A number to a boolean is a test against
507
+ * zero; a boolean to a number is 0 or 1.
508
+ *
509
+ * @param register The register.
510
+ * @param type The type.
511
+ *
512
+ * @returns A register of that type: this one when it already is.
513
+ */
514
+ convert(register, type) {
515
+ const from = register.type;
516
+ if (from === type) {
517
+ return register;
518
+ }
519
+ if (type === 'bool') {
520
+ return this.truthy(register);
521
+ }
522
+ if (from === 'bool') {
523
+ const whole = this.builder.register('int');
524
+ const end = this.builder.label();
525
+ this.builder.abx('LOADI', whole.index, 0);
526
+ this.builder.branch('JF', end, register);
527
+ this.builder.abx('LOADI', whole.index, 1);
528
+ this.builder.place(end);
529
+ return this.convert(whole, type);
530
+ }
531
+ const opcode = CONVERSIONS[`${from}>${type}`];
532
+ if (!opcode) {
533
+ throw new Error(`AOT internal: no conversion from ${from} to ${type}`);
534
+ }
535
+ const converted = this.builder.register(type);
536
+ this.builder.abc(opcode, converted.index, register.index);
537
+ return converted;
538
+ }
539
+ /**
540
+ * Whether a register's value is truthy.
541
+ *
542
+ * @param register The register.
543
+ *
544
+ * @returns A bool register.
545
+ */
546
+ truthy(register) {
547
+ if (register.type === 'bool') {
548
+ return register;
549
+ }
550
+ const test = this.builder.register('bool');
551
+ if (register.type === 'string') {
552
+ this.builder.abc('SEQ', test.index, register.index, this.zero('string').index);
553
+ }
554
+ else {
555
+ const zero = this.load(register.type, 0);
556
+ this.builder.abc(COMPARE_OPCODES[register.type][0], test.index, register.index, zero.index);
557
+ }
558
+ this.builder.abc('NOT', test.index, test.index);
559
+ return test;
560
+ }
561
+ /**
562
+ * A constant in a register of a type.
563
+ *
564
+ * @param type The type.
565
+ * @param value The value.
566
+ *
567
+ * @returns The register.
568
+ */
569
+ load(type, value) {
570
+ const { builder } = this;
571
+ const { tables } = this.program;
572
+ const register = builder.register(type);
573
+ switch (type) {
574
+ case 'int':
575
+ case 'bool': {
576
+ const whole = Math.trunc(value) | 0;
577
+ if (whole >= IMMEDIATE_MIN && whole <= IMMEDIATE_MAX) {
578
+ builder.abx('LOADI', register.index, whole);
579
+ }
580
+ else {
581
+ builder.abx('LOADK', register.index, tables.constant32(whole));
582
+ }
583
+ break;
584
+ }
585
+ case 'float':
586
+ builder.abx('LOADK', register.index, tables.constant32(floatBits(value)));
587
+ break;
588
+ case 'double':
589
+ builder.abx('LOADK64', register.index, tables.constant64(doubleBits(value)));
590
+ break;
591
+ case 'int64':
592
+ builder.abx('LOADK64', register.index, tables.constant64(BigInt(Math.trunc(value))));
593
+ break;
594
+ default:
595
+ throw new Error(`AOT internal: no ${type} constant`);
596
+ }
597
+ return register;
598
+ }
599
+ /**
600
+ * Whether two registers of one type hold the same value.
601
+ *
602
+ * @param left One.
603
+ * @param right The other.
604
+ *
605
+ * @returns A bool register.
606
+ */
607
+ same(left, right) {
608
+ const register = this.builder.register('bool');
609
+ const opcode = left.type === 'string'
610
+ ? 'SEQ'
611
+ : left.type === 'bool' || left.type === 'enum'
612
+ ? 'EQ'
613
+ : COMPARE_OPCODES[left.type][0];
614
+ this.builder.abc(opcode, register.index, left.index, right.index);
615
+ return register;
616
+ }
617
+ /**
618
+ * A slot's value in a register of its type.
619
+ *
620
+ * @param slot The slot.
621
+ *
622
+ * @returns The register.
623
+ */
624
+ get(slot) {
625
+ const type = slotType(slot);
626
+ const register = this.builder.register(type);
627
+ const opcode = type === 'string'
628
+ ? 'GETS'
629
+ : type === 'int64' || type === 'double'
630
+ ? 'GET64'
631
+ : 'GET32';
632
+ this.builder.abx(opcode, register.index, slot.index);
633
+ return register;
634
+ }
635
+ /**
636
+ * Writes a register to a slot, converting it to the slot's type. A slot with a dirty bit has it set when the
637
+ * value changes.
638
+ *
639
+ * @param slot The slot.
640
+ * @param value The value.
641
+ */
642
+ set(slot, value) {
643
+ const type = slotType(slot);
644
+ const register = this.convert(value, type);
645
+ const opcode = type === 'string'
646
+ ? 'SETS'
647
+ : type === 'int64' || type === 'double'
648
+ ? 'SET64'
649
+ : 'SET32';
650
+ this.builder.abx(opcode, register.index, slot.index);
651
+ }
652
+ event(type, field) {
653
+ const register = this.builder.register(type);
654
+ this.builder.abc('EVT', register.index, field);
655
+ return register;
656
+ }
657
+ /**
658
+ * A gestureState field: travel from the grant, x0/y0 from the responder's state, the rest
659
+ * off the event.
660
+ *
661
+ * @param expression The field.
662
+ *
663
+ * @returns The register.
664
+ */
665
+ gesture(expression) {
666
+ const slots = this.program.gestures.get(expression.statePrefix);
667
+ switch (expression.field) {
668
+ case 'dx':
669
+ case 'dy': {
670
+ const travel = this.event('int', EVENT_FIELDS[expression.field]);
671
+ const base = this.get(expression.field === 'dx' ? slots.baseDeltaX : slots.baseDeltaY);
672
+ const register = this.builder.register('int');
673
+ this.builder.abc('SUB', register.index, travel.index, base.index);
674
+ return register;
675
+ }
676
+ case 'moveX':
677
+ return this.event('int', EventField.x);
678
+ case 'moveY':
679
+ return this.event('int', EventField.y);
680
+ case 'x0':
681
+ return this.get(slots.x0);
682
+ case 'y0':
683
+ return this.get(slots.y0);
684
+ case 'vx':
685
+ case 'vy':
686
+ return this.event('float', EVENT_FIELDS[expression.field]);
687
+ case 'numberActiveTouches':
688
+ return this.event('int', EventField.touches);
689
+ case 'stateID':
690
+ return this.load('int', expression.stateID);
691
+ }
692
+ }
693
+ /** The text a <TextInput> holds now, as its CHANGE_TEXT handler receives it. */
694
+ changedText() {
695
+ if (!this.input) {
696
+ throw new Error('AOT internal: changed text outside a CHANGE_TEXT handler');
697
+ }
698
+ const node = this.builder.register('node');
699
+ this.builder.abx('GET64', node.index, this.input.node.index);
700
+ this.builder.abx('INPUT', node.index, this.input.text.index);
701
+ return this.get(this.input.text);
702
+ }
703
+ /**
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.
719
+ *
720
+ * @param item The row's item.
721
+ * @param index The field's index in the row.
722
+ * @param type Its type.
723
+ * @param checked Read zero past the list's end even for an unguarded index.
724
+ *
725
+ * @returns The register.
726
+ */
727
+ rowRead(item, index, type, checked) {
728
+ const { builder } = this;
729
+ const list = required(item.list, `the list of "${item.name}"`);
730
+ const pool = this.listPool(list).slot;
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 = () => {
735
+ const register = builder.register(type);
736
+ builder.abc('ROWGET', register.index, this.sourceRow(item, row).index, 0, pool.index | (index << 16));
737
+ return register;
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);
832
+ }
833
+ /** Zero, or the empty string, in a register of a type. */
834
+ zero(type) {
835
+ if (type !== 'string') {
836
+ return this.load(type, 0);
837
+ }
838
+ this.emptyString ??= this.builder.reserved('string');
839
+ return this.emptyString;
840
+ }
841
+ local(expression) {
842
+ // A memo, a component's prop or a helper's argument stands for its expression.
843
+ if (expression.local.expression) {
844
+ return this.value(expression.local.expression);
845
+ }
846
+ const binding = this.binding(expression.local.name);
847
+ if (!binding) {
848
+ return notYet('the value an element passes its callback');
849
+ }
850
+ return 'register' in binding ? binding.register : this.get(binding.slot);
851
+ }
852
+ /** A local's value, by name: this function's own, or an effect local kept in a slot. */
853
+ binding(name) {
854
+ const hoisted = this.program.hoisted.get(name);
855
+ return this.locals.get(name) ?? (hoisted && { slot: hoisted });
856
+ }
857
+ unary(operator, operand, type) {
858
+ if (operator === '!') {
859
+ const register = this.builder.register('bool');
860
+ this.builder.abc('NOT', register.index, this.condition(operand).index);
861
+ return register;
862
+ }
863
+ const value = this.valueAs(operand, type);
864
+ if (operator === '+') {
865
+ return value;
866
+ }
867
+ const register = this.builder.register(type);
868
+ const negateOpcode = {
869
+ int: 'NEG',
870
+ int64: 'NEGL',
871
+ float: 'FNEG',
872
+ double: 'DNEG',
873
+ }[type];
874
+ this.builder.abc(negateOpcode, register.index, value.index);
875
+ return register;
876
+ }
877
+ arithmetic(operator, left, right, type) {
878
+ const leftRegister = this.valueAs(left, type);
879
+ const rightRegister = this.valueAs(right, type);
880
+ const register = this.builder.register(type);
881
+ // The IR's float remainder is fmod.
882
+ if (operator === '%' && (type === 'float' || type === 'double')) {
883
+ this.builder.abc(type === 'double' ? 'DMATH' : 'FMATH', register.index, leftRegister.index, rightRegister.index, MathFn.mod);
884
+ return register;
885
+ }
886
+ this.builder.abc(ARITHMETIC_OPCODES[type][operator], register.index, leftRegister.index, rightRegister.index);
887
+ return register;
888
+ }
889
+ compare(operator, left, right) {
890
+ const type = promoted(usual(this.typeOf(left), this.typeOf(right)));
891
+ const leftRegister = this.valueAs(left, type);
892
+ const rightRegister = this.valueAs(right, type);
893
+ const [equal, less, atMost] = COMPARE_OPCODES[type];
894
+ const register = this.builder.register('bool');
895
+ const [opcode, first, second] = operator === '<'
896
+ ? [less, leftRegister, rightRegister]
897
+ : operator === '>'
898
+ ? [less, rightRegister, leftRegister]
899
+ : operator === '<='
900
+ ? [atMost, leftRegister, rightRegister]
901
+ : operator === '>='
902
+ ? [atMost, rightRegister, leftRegister]
903
+ : [equal, leftRegister, rightRegister];
904
+ this.builder.abc(opcode, register.index, first.index, second.index);
905
+ if (operator === '!=') {
906
+ this.builder.abc('NOT', register.index, register.index);
907
+ }
908
+ return register;
909
+ }
910
+ /** `a || b` as `(a ? a : b)`, and `a && b` as `(a ? b : a)`. */
911
+ pick(operator, left, right, type) {
912
+ // A string slot always reads as set here.
913
+ if (type === 'string') {
914
+ return this.valueAs(operator === '||' ? left : right, type);
915
+ }
916
+ const leftValue = this.value(left);
917
+ return this.choose(this.truthy(leftValue), () => this.convert(operator === '||' ? leftValue : this.value(right), type), () => this.convert(operator === '||' ? this.value(right) : leftValue, type), type);
918
+ }
919
+ /**
920
+ * `test ? whenTrue : whenFalse`, each side worked out only when it is chosen.
921
+ *
922
+ * @param test A bool register.
923
+ * @param whenTrue Works out the value when the test holds.
924
+ * @param whenFalse Works out the value when it doesn't.
925
+ * @param type The result's type.
926
+ *
927
+ * @returns The result.
928
+ */
929
+ choose(test, whenTrue, whenFalse, type) {
930
+ const { builder } = this;
931
+ const register = builder.register(type);
932
+ const otherwise = builder.label();
933
+ const end = builder.label();
934
+ builder.branch('JF', otherwise, test);
935
+ builder.abc('MOVE', register.index, whenTrue().index);
936
+ builder.branch('JMP', end);
937
+ builder.place(otherwise);
938
+ builder.abc('MOVE', register.index, whenFalse().index);
939
+ builder.place(end);
940
+ return register;
941
+ }
942
+ /*--------------------------------------------------------------------------------------------------------------------
943
+ - Text
944
+ -------------------------------------------------------------------------------------------------------------------*/
945
+ /**
946
+ * Builds a text in the format buffer, each part printed in turn. The caller puts it
947
+ * somewhere (FMTTEXT, FMTSET, or FMTSPAN), which empties the buffer.
948
+ *
949
+ * @param parts The text's parts.
950
+ */
951
+ text(parts) {
952
+ const { builder } = this;
953
+ for (const part of parts) {
954
+ const checkpoint = builder.checkpoint();
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') {
978
+ if (part.text) {
979
+ builder.abx('FMTK', 0, this.program.tables.string(part.text));
980
+ }
981
+ }
982
+ else if (part.kind === 'booleanWord') {
983
+ const positions = this.slicePositions(part.edits);
984
+ builder.abc('FMTB', this.condition(part.value).index);
985
+ this.edits(part.edits, positions, 0);
986
+ }
987
+ else if (this.enumOf(part.value)) {
988
+ const value = part.value;
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);
992
+ }
993
+ else {
994
+ // The spec is by the value's IR type: a float is printed from a float, so a boot double is narrowed first.
995
+ const type = part.value.type.kind;
996
+ const [opcode, formatType] = type === 'string'
997
+ ? ['FMTS', 'string']
998
+ : type === 'float'
999
+ ? ['FMTF', 'float']
1000
+ : type === 'int64'
1001
+ ? ['FMTL', 'int64']
1002
+ : ['FMTI', 'int'];
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
+ }
1019
+ }
1020
+ builder.release(checkpoint);
1021
+ }
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
+ }
1062
+ /*--------------------------------------------------------------------------------------------------------------------
1063
+ - Statements
1064
+ -------------------------------------------------------------------------------------------------------------------*/
1065
+ /**
1066
+ * Lowers statements, in order.
1067
+ *
1068
+ * @param statements The statements.
1069
+ */
1070
+ statements(statements) {
1071
+ for (const statement of statements) {
1072
+ this.statement(statement);
1073
+ }
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
+ }
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) {
1104
+ const { builder } = this;
1105
+ builder.at(statement.location);
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;
1114
+ case 'declareLocal': {
1115
+ const hoisted = this.program.hoisted.get(statement.name);
1116
+ if (statement.isHoisted && !hoisted) {
1117
+ throw new Error(`AOT internal: no slot for local "${statement.name}"`);
1118
+ }
1119
+ if (hoisted && slotType(hoisted) !== 'string') {
1120
+ this.scoped(() => this.set(hoisted, this.value(statement.initializer)));
1121
+ this.locals.set(statement.name, { slot: hoisted });
1122
+ return;
1123
+ }
1124
+ if (this.typeOf(statement.initializer) === 'string') {
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.
1126
+ const slot = hoisted ?? this.program.stringLocals.get(statement.name);
1127
+ const checkpoint = builder.checkpoint();
1128
+ this.text(statement.text?.parts ?? [
1129
+ { kind: 'value', value: statement.initializer },
1130
+ ]);
1131
+ builder.abx('FMTSET', 0, slot.index);
1132
+ builder.release(checkpoint);
1133
+ this.locals.set(statement.name, { slot });
1134
+ return;
1135
+ }
1136
+ const type = statement.widenedTo ?? declaredType(statement.initializer);
1137
+ const register = builder.register(type);
1138
+ const checkpoint = builder.checkpoint();
1139
+ builder.abc('MOVE', register.index, this.valueAs(statement.initializer, type).index);
1140
+ builder.release(checkpoint);
1141
+ this.locals.set(statement.name, { register });
1142
+ return;
1143
+ }
1144
+ case 'setState':
1145
+ this.scoped(() => this.set(this.stateSlot(statement.state), this.value(statement.value)));
1146
+ return;
1147
+ case 'setStateText':
1148
+ this.scoped(() => {
1149
+ // An interned state is set to the index of the constant it is given.
1150
+ const set = this.program.enums.get(statement.state);
1151
+ if (set) {
1152
+ const index = set.values.indexOf(constantText(statement.text));
1153
+ builder.abx('SET32', this.enumValue(set.set, index).index, this.stateSlot(statement.state).index);
1154
+ return;
1155
+ }
1156
+ this.text(statement.text.parts);
1157
+ builder.abx('FMTSET', 0, this.stateSlot(statement.state).index);
1158
+ });
1159
+ return;
1160
+ case 'writeRef':
1161
+ this.scoped(() => this.writeRef(statement.ref, statement.operator, statement.value));
1162
+ return;
1163
+ case 'stepRef':
1164
+ this.scoped(() => {
1165
+ const slot = this.refSlot(statement.ref);
1166
+ const type = slotType(slot);
1167
+ const register = builder.register(type);
1168
+ builder.abc(ARITHMETIC_OPCODES[type][statement.operator === '++' ? '+' : '-'], register.index, this.get(slot).index, this.load(type, 1).index);
1169
+ this.set(slot, register);
1170
+ });
1171
+ return;
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
+ }
1179
+ const otherwise = builder.label();
1180
+ const checkpoint = builder.checkpoint();
1181
+ builder.branch('JF', otherwise, this.condition(statement.test));
1182
+ builder.release(checkpoint);
1183
+ this.statements(statement.consequent);
1184
+ // An else of fields kept as they are does nothing.
1185
+ if (statement.alternate?.some(inner => this.doesSomething(inner))) {
1186
+ const end = builder.label();
1187
+ builder.branch('JMP', end);
1188
+ builder.place(otherwise);
1189
+ this.statements(statement.alternate);
1190
+ builder.place(end);
1191
+ }
1192
+ else {
1193
+ builder.place(otherwise);
1194
+ }
1195
+ return;
1196
+ }
1197
+ case 'startTimer':
1198
+ this.startTimer(statement.timer, statement.idLocal?.name ?? null);
1199
+ return;
1200
+ case 'clearTimer':
1201
+ this.scoped(() => builder.abc('TCLEAR', this.valueAs(statement.id, 'int').index));
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;
1226
+ case 'clearList':
1227
+ builder.abx('CLEAR', 0, this.listPool(statement.list).slot.index);
1228
+ return;
1229
+ case 'appendItem':
1230
+ this.scoped(() => this.appendItem(statement));
1231
+ return;
1232
+ case 'dropLastItem':
1233
+ builder.abx('POP', 0, this.listPool(statement.list).slot.index);
1234
+ return;
1235
+ case 'keepFirstItems':
1236
+ this.scoped(() => builder.abx('KEEP', this.load('int', statement.count).index, this.listPool(statement.list).slot.index));
1237
+ return;
1238
+ case 'sliceItems':
1239
+ // slice(0, end), as SLICE counts it.
1240
+ this.scoped(() => builder.abc('SLICE', this.load('int', 0).index, this.valueAs(statement.end, 'int').index, 0, this.listPool(statement.list).slot.index));
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;
1263
+ case 'stopAnimations':
1264
+ case 'startAnimations':
1265
+ case 'startChain':
1266
+ case 'completeAfter':
1267
+ animationStatement(this, statement, this.program.animations);
1268
+ return;
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');
1296
+ }
1297
+ builder.branch('JMP', end);
1298
+ return;
1299
+ }
1300
+ case 'armCleanup':
1301
+ this.scoped(() => this.set(required(this.program.armed.get(statement.flag), statement.flag), this.load('bool', 1)));
1302
+ return;
1303
+ case 'updateVector':
1304
+ updateVector(this, statement, this.program.vectors);
1305
+ }
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
+ }
1393
+ /**
1394
+ * Appends an item, its fields worked out in order into consecutive registers. A full list drops it.
1395
+ * A text field is built in its own buffer first.
1396
+ *
1397
+ * @param statement The append.
1398
+ */
1399
+ appendItem(statement) {
1400
+ const { builder } = this;
1401
+ const pool = this.listPool(statement.list);
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}"`);
1415
+ this.text(itemValue.text.parts);
1416
+ builder.abx('FMTSET', 0, buffer.index);
1417
+ builder.abx('GETS', row[index].index, buffer.index);
1418
+ }
1419
+ else {
1420
+ builder.abc('MOVE', row[index].index, this.valueAs(itemValue.value, field.kind).index);
1421
+ }
1422
+ }));
1423
+ builder.abx('APPEND', row[0].index, pool.slot.index);
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
+ }
1780
+ /**
1781
+ * Starts a timer, keeping its id in a local when the app names it.
1782
+ *
1783
+ * @param timer The timer.
1784
+ * @param idLocal The local's name, or null.
1785
+ */
1786
+ startTimer(timer, idLocal) {
1787
+ const { builder } = this;
1788
+ const hoisted = idLocal === null ? undefined : this.program.hoisted.get(idLocal);
1789
+ const start = (id) => this.scoped(() => {
1790
+ builder.abc('TSTART', id.index, this.timerDelay(timer.delay).index, timer.isRepeating ? 1 : 0, required(this.program.timerFunctions.get(timer.functionName), `timer "${timer.functionName}"`));
1791
+ if (hoisted) {
1792
+ this.set(hoisted, id);
1793
+ }
1794
+ });
1795
+ if (idLocal === null || hoisted) {
1796
+ this.scoped(() => start(builder.register('int')));
1797
+ if (hoisted) {
1798
+ this.locals.set(idLocal, { slot: hoisted });
1799
+ }
1800
+ return;
1801
+ }
1802
+ // The id outlives this statement, so its register is taken outside the scope.
1803
+ const id = builder.register('int');
1804
+ start(id);
1805
+ this.locals.set(idLocal, { register: id });
1806
+ }
1807
+ /**
1808
+ * A timer's delay in ms: a 64-bit or fractional delay through ToInt32, with a
1809
+ * negative one as 0. (The runtime waits at least 1 ms.)
1810
+ *
1811
+ * @param delay The delay, or null for none.
1812
+ *
1813
+ * @returns An int register.
1814
+ */
1815
+ timerDelay(delay) {
1816
+ if (!delay) {
1817
+ return this.load('int', 0);
1818
+ }
1819
+ const kind = delay.type.kind;
1820
+ if (kind !== 'int64' && kind !== 'float') {
1821
+ return this.valueAs(delay, 'int');
1822
+ }
1823
+ // A float delay becomes a 64-bit int; the VM's conversion saturates.
1824
+ const { builder } = this;
1825
+ const whole = kind === 'float'
1826
+ ? this.convert(this.valueAs(delay, 'float'), 'int64')
1827
+ : this.valueAs(delay, 'int64');
1828
+ const modulus = this.load('int64', TWO_TO_32);
1829
+ const low = builder.register('int64');
1830
+ builder.abc('MODL', low.index, whole.index, modulus.index);
1831
+ builder.abc('ADDL', low.index, low.index, modulus.index);
1832
+ builder.abc('MODL', low.index, low.index, modulus.index);
1833
+ const tooBig = builder.register('bool');
1834
+ builder.abc('LLT', tooBig.index, this.load('int64', INT32_MAX).index, low.index);
1835
+ return this.choose(tooBig, () => this.load('int', 0), () => this.convert(low, 'int'), 'int');
1836
+ }
1837
+ writeRef(ref, operator, value) {
1838
+ const slot = this.refSlot(ref);
1839
+ if (operator === '=') {
1840
+ this.set(slot, this.value(value));
1841
+ return;
1842
+ }
1843
+ // `ref op= value` is `ref = ref op value`, worked out in the wider of the two types.
1844
+ const type = usual(slotType(slot), this.typeOf(value));
1845
+ const register = this.builder.register(type);
1846
+ this.builder.abc(ARITHMETIC_OPCODES[type][operator.slice(0, -1)], register.index, this.convert(this.get(slot), type).index, this.valueAs(value, type).index);
1847
+ this.set(slot, register);
1848
+ }
1849
+ /**
1850
+ * Runs a piece of lowering, then releases the registers it took.
1851
+ *
1852
+ * @param lower The lowering.
1853
+ */
1854
+ scoped(lower) {
1855
+ const checkpoint = this.builder.checkpoint();
1856
+ lower();
1857
+ this.builder.release(checkpoint);
1858
+ }
1859
+ /*--------------------------------------------------------------------------------------------------------------------
1860
+ - Props
1861
+ -------------------------------------------------------------------------------------------------------------------*/
1862
+ /**
1863
+ * Sets a state-driven prop in the props scratch, converting its value to the ERProps field's type.
1864
+ *
1865
+ * @param field The ERProps field.
1866
+ * @param value Its value.
1867
+ */
1868
+ setProp(field, value) {
1869
+ this.scoped(() => {
1870
+ const prop = abiProp(field);
1871
+ const result = this.propValue(value);
1872
+ const { builder } = this;
1873
+ if (result.conversion === 'opacity' || prop.kind === 'float') {
1874
+ // The runtime's PSETF scales an opacity to the engine's byte.
1875
+ builder.abx('PSETF', this.convert(result.register, 'float').index, prop.id);
1876
+ return;
1877
+ }
1878
+ if (result.conversion === 'dimension') {
1879
+ this.setDimension(prop.id, result.register);
1880
+ return;
1881
+ }
1882
+ // Any other field is a whole number: a fraction goes in truncated.
1883
+ builder.abx('PSETI', this.convert(result.register, 'int').index, prop.id);
1884
+ });
1885
+ }
1886
+ /**
1887
+ * A state-driven prop value, such as a paint's color, in the type it is worked out in.
1888
+ *
1889
+ * @param value The value.
1890
+ *
1891
+ * @returns The register.
1892
+ */
1893
+ propRegister(value) {
1894
+ const result = this.propValue(value);
1895
+ if (result.conversion) {
1896
+ notYet(`a ${result.conversion} outside a prop`);
1897
+ }
1898
+ return result.register;
1899
+ }
1900
+ /**
1901
+ * A dimension, rounded: halves up, clamped to int16, NaN as 0.
1902
+ *
1903
+ * @param prop The prop's id.
1904
+ * @param value The value.
1905
+ */
1906
+ setDimension(prop, value) {
1907
+ const { builder } = this;
1908
+ if (value.type === 'int' || value.type === 'bool') {
1909
+ builder.abx('PSETI', this.convert(value, 'int').index, prop);
1910
+ return;
1911
+ }
1912
+ if (value.type === 'float') {
1913
+ // The runtime rounds a float.
1914
+ builder.abx('PSETF', value.index, prop);
1915
+ return;
1916
+ }
1917
+ // A double (or a 64-bit int, which becomes a double) is rounded here, since a float can't hold it exactly.
1918
+ const rounded = builder.register('double');
1919
+ builder.abc('DADD', rounded.index, this.convert(value, 'double').index, this.load('double', ROUND_HALF_UP).index);
1920
+ builder.abc('DMATH', rounded.index, rounded.index, rounded.index, MathFn.floor);
1921
+ builder.abx('PSETI', this.convert(rounded, 'int').index, prop);
1922
+ }
1923
+ /**
1924
+ * A state-driven prop value, with the conversion on top of it lifted out. A conversion that maps 0 to
1925
+ * 0 (an opacity, a dimension) gives the same answer applied after a choice as inside it.
1926
+ *
1927
+ * @param value The value.
1928
+ *
1929
+ * @returns Its register, type and conversion.
1930
+ */
1931
+ propValue(value) {
1932
+ const plain = (register) => ({
1933
+ register,
1934
+ type: register.type,
1935
+ conversion: null,
1936
+ });
1937
+ switch (value.kind) {
1938
+ case 'constant':
1939
+ return plain(this.constantValue(value.value));
1940
+ case 'opacity':
1941
+ case 'dimension':
1942
+ return {
1943
+ ...plain(this.value(value.value)),
1944
+ conversion: value.kind,
1945
+ };
1946
+ case 'float':
1947
+ return plain(this.valueAs(value.value, 'float'));
1948
+ case 'byte':
1949
+ return this.propValue(value.value);
1950
+ case 'visible':
1951
+ // This tests the value itself, and a string slot always reads as set.
1952
+ return plain(this.display(value.value.type.kind === 'string'
1953
+ ? this.load('bool', 1)
1954
+ : this.condition(value.value)));
1955
+ case 'shown':
1956
+ return plain(this.display(this.shown(value.show)));
1957
+ case 'flag': {
1958
+ const test = value.truthiness === 'value' && value.test.type.kind === 'string'
1959
+ ? this.load('bool', 1)
1960
+ : this.condition(value.test);
1961
+ const register = this.builder.register('int');
1962
+ const end = this.builder.label();
1963
+ this.builder.abx('LOADI', register.index, 0);
1964
+ this.builder.branch(value.negate ? 'JT' : 'JF', end, test);
1965
+ this.builder.abx('LOADI', register.index, value.whenTrue);
1966
+ this.builder.place(end);
1967
+ return plain(register);
1968
+ }
1969
+ case 'whileShown': {
1970
+ const inner = this.propValue(value.value);
1971
+ return {
1972
+ ...plain(this.choose(this.shown(value.show), () => inner.register, () => this.load(inner.type, 0), inner.type)),
1973
+ conversion: inner.conversion,
1974
+ };
1975
+ }
1976
+ case 'select': {
1977
+ const test = this.condition(value.test);
1978
+ const whenTrue = this.propValue(value.whenTrue);
1979
+ const whenFalse = this.propValue(value.whenFalse);
1980
+ if (whenTrue.conversion !== whenFalse.conversion) {
1981
+ notYet('a state-driven prop that converts one of its choices only');
1982
+ }
1983
+ const type = usual(whenTrue.type, whenFalse.type);
1984
+ return {
1985
+ ...plain(this.choose(test, () => this.convert(whenTrue.register, type), () => this.convert(whenFalse.register, type), type)),
1986
+ conversion: whenTrue.conversion,
1987
+ };
1988
+ }
1989
+ }
1990
+ }
1991
+ /**
1992
+ * A constant prop value in a register.
1993
+ *
1994
+ * @param constant The constant.
1995
+ *
1996
+ * @returns The register.
1997
+ */
1998
+ constantValue(constant) {
1999
+ const value = constantNumber(constant);
2000
+ if (value === null) {
2001
+ return notYet(`the constant \`${constant}\``);
2002
+ }
2003
+ return this.load('int', value);
2004
+ }
2005
+ /** ER_DISPLAY_FLEX while a test holds, else ER_DISPLAY_NONE. */
2006
+ display(test) {
2007
+ const register = this.builder.register('int');
2008
+ const end = this.builder.label();
2009
+ this.builder.abx('LOADI', register.index, DISPLAY_NONE);
2010
+ this.builder.branch('JF', end, test);
2011
+ this.builder.abx('LOADI', register.index, DISPLAY_FLEX);
2012
+ this.builder.place(end);
2013
+ return register;
2014
+ }
2015
+ /**
2016
+ * Whether a node under a state-driven conditional shows: its test, negated for an else branch, within the
2017
+ * conditions it is nested in.
2018
+ *
2019
+ * @param show The condition.
2020
+ *
2021
+ * @returns A bool register.
2022
+ */
2023
+ shown(show) {
2024
+ if (show.kind === 'rowInUse') {
2025
+ const count = this.builder.register('int');
2026
+ const register = this.builder.register('bool');
2027
+ this.builder.abx('LEN', count.index, this.listPool(show.list).slot.index);
2028
+ this.builder.abc('LT', register.index, this.load('int', show.row).index, count.index);
2029
+ return register;
2030
+ }
2031
+ const register = this.builder.register('bool');
2032
+ this.builder.abc('MOVE', register.index, this.condition(show.test).index);
2033
+ if (show.negate) {
2034
+ this.builder.abc('NOT', register.index, register.index);
2035
+ }
2036
+ if (show.within) {
2037
+ const end = this.builder.label();
2038
+ this.builder.branch('JF', end, register);
2039
+ this.builder.abc('MOVE', register.index, this.shown(show.within).index);
2040
+ this.builder.place(end);
2041
+ }
2042
+ return register;
2043
+ }
2044
+ /*--------------------------------------------------------------------------------------------------------------------
2045
+ - Slots
2046
+ -------------------------------------------------------------------------------------------------------------------*/
2047
+ stateSlot(state) {
2048
+ return required(this.program.states.get(state), `state "${state.name}"`);
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
+ }
2058
+ listPool(list) {
2059
+ return required(this.program.lists.get(list), `list "${list.name}"`);
2060
+ }
2061
+ refSlot(ref) {
2062
+ return ref.kind === 'node'
2063
+ ? notYet('reading a node ref')
2064
+ : required(this.program.refs.get(ref), `ref "${ref.slotName}"`);
2065
+ }
2066
+ bootSlot(slot) {
2067
+ return required(this.program.boot.get(slot), `boot value "${slot.field}"`);
2068
+ }
2069
+ }
2070
+ /*----------------------------------------------------------------------------------------------------------------------
2071
+ - Implementation
2072
+ ---------------------------------------------------------------------------------------------------------------------*/
2073
+ /**
2074
+ * Refuses what a package can't lower yet.
2075
+ *
2076
+ * @param what What the app uses.
2077
+ */
2078
+ export function notYet(what) {
2079
+ throw aotError(`AOT: a package doesn't support ${what} yet`);
2080
+ }
2081
+ /**
2082
+ * A slot or function that has to have been planned.
2083
+ *
2084
+ * @param planned The slot or function, if it was.
2085
+ * @param what What it holds, for the error.
2086
+ *
2087
+ * @returns The slot or function.
2088
+ */
2089
+ function required(planned, what) {
2090
+ if (planned === undefined) {
2091
+ throw new Error(`AOT internal: nothing planned for ${what}`);
2092
+ }
2093
+ return planned;
2094
+ }
2095
+ /**
2096
+ * The type a slot holds.
2097
+ *
2098
+ * @param slot The slot.
2099
+ *
2100
+ * @returns Its type.
2101
+ */
2102
+ export function slotType(slot) {
2103
+ return {
2104
+ [ValueType.int]: 'int',
2105
+ [ValueType.bool]: 'bool',
2106
+ [ValueType.float]: 'float',
2107
+ [ValueType.int64]: 'int64',
2108
+ [ValueType.double]: 'double',
2109
+ [ValueType.string]: 'string',
2110
+ [ValueType.enum]: 'enum',
2111
+ }[slot.type];
2112
+ }
2113
+ /**
2114
+ * The type an operation on two values is worked out in: the wider of the two, a double over a float over a 64-bit
2115
+ * int over an int. Two booleans stay a boolean (an int holding 0 or 1).
2116
+ *
2117
+ * @param left One operand's type.
2118
+ * @param right The other's.
2119
+ *
2120
+ * @returns The type.
2121
+ */
2122
+ function usual(left, right) {
2123
+ if (left === 'string' || right === 'string') {
2124
+ return 'string';
2125
+ }
2126
+ if (left === 'bool' && right === 'bool') {
2127
+ return 'bool';
2128
+ }
2129
+ for (const type of ['double', 'float', 'int64']) {
2130
+ if (left === type || right === type) {
2131
+ return type;
2132
+ }
2133
+ }
2134
+ return 'int';
2135
+ }
2136
+ /** A boolean worked on as a number is an int. */
2137
+ const promoted = (type) => (type === 'bool' ? 'int' : type);
2138
+ /**
2139
+ * The type a handler local holds: what its IR type says.
2140
+ *
2141
+ * @param initializer The local's initial value.
2142
+ *
2143
+ * @returns Its type.
2144
+ */
2145
+ function declaredType(initializer) {
2146
+ switch (initializer.type.kind) {
2147
+ case 'bool':
2148
+ return 'bool';
2149
+ case 'float':
2150
+ return 'float';
2151
+ case 'int64':
2152
+ return 'int64';
2153
+ default:
2154
+ return 'int';
2155
+ }
2156
+ }
2157
+ /**
2158
+ * A double's 64 bits.
2159
+ *
2160
+ * @param value The number.
2161
+ *
2162
+ * @returns The bits.
2163
+ */
2164
+ function doubleBits(value) {
2165
+ const view = new DataView(new ArrayBuffer(8));
2166
+ view.setFloat64(0, value, true);
2167
+ return view.getBigUint64(0, true);
2168
+ }