embedded-react 0.18.0 → 0.20.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 (117) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +8 -4
  3. package/aot/compile.mjs +178 -58
  4. package/aot/compiler/animations.mjs +290 -281
  5. package/aot/compiler/boot.mjs +70 -33
  6. package/aot/compiler/branch-merge.mjs +4 -3
  7. package/aot/compiler/check.mjs +9 -9
  8. package/aot/compiler/collect.mjs +324 -205
  9. package/aot/compiler/control-flow.mjs +209 -197
  10. package/aot/compiler/diagnostics.mjs +22 -25
  11. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  12. package/aot/compiler/elements/dial.mjs +91 -77
  13. package/aot/compiler/elements/flat-list.mjs +24 -22
  14. package/aot/compiler/elements/image.mjs +51 -50
  15. package/aot/compiler/elements/modal.mjs +31 -30
  16. package/aot/compiler/elements/props.mjs +23 -23
  17. package/aot/compiler/elements/switch.mjs +42 -34
  18. package/aot/compiler/elements/text-input.mjs +34 -32
  19. package/aot/compiler/expressions.mjs +372 -333
  20. package/aot/compiler/handlers.mjs +473 -387
  21. package/aot/compiler/ir/functions.mjs +11 -1
  22. package/aot/compiler/ir/nodes.mjs +4 -4
  23. package/aot/compiler/ir/reads.mjs +19 -19
  24. package/aot/compiler/ir/types.mjs +14 -14
  25. package/aot/compiler/ir/vectors.mjs +5 -1
  26. package/aot/compiler/keyboard.mjs +17 -7
  27. package/aot/compiler/lower.mjs +77 -80
  28. package/aot/compiler/nodes.mjs +169 -152
  29. package/aot/compiler/options.mjs +35 -30
  30. package/aot/compiler/out.mjs +18 -22
  31. package/aot/compiler/package/animations.mjs +669 -0
  32. package/aot/compiler/package/arena.mjs +252 -0
  33. package/aot/compiler/package/assemble.mjs +177 -0
  34. package/aot/compiler/package/bytecode.mjs +286 -0
  35. package/aot/compiler/package/checks.mjs +1022 -0
  36. package/aot/compiler/package/codegen.mjs +1329 -0
  37. package/aot/compiler/package/enums.mjs +138 -0
  38. package/aot/compiler/package/format.mjs +760 -0
  39. package/aot/compiler/package/layouts.mjs +136 -0
  40. package/aot/compiler/package/lower.mjs +1606 -0
  41. package/aot/compiler/package/props.mjs +118 -0
  42. package/aot/compiler/package/tables.mjs +103 -0
  43. package/aot/compiler/package/vectors.mjs +502 -0
  44. package/aot/compiler/package/writer.mjs +664 -0
  45. package/aot/compiler/pan-responder.mjs +69 -61
  46. package/aot/compiler/parse.mjs +21 -21
  47. package/aot/compiler/static-eval.mjs +25 -23
  48. package/aot/compiler/style-text.mjs +161 -172
  49. package/aot/compiler/svg.mjs +477 -251
  50. package/aot/screenshot-smoke.mjs +55 -41
  51. package/aot/style-map.mjs +102 -90
  52. package/assets/bake-font.mjs +123 -77
  53. package/assets/bake-image.mjs +39 -22
  54. package/assets/bake-svg.mjs +361 -262
  55. package/assets/build-builtin-font.mjs +14 -10
  56. package/assets/emit-c.mjs +83 -62
  57. package/assets/emit-container.mjs +124 -38
  58. package/assets/emit-pack.mjs +77 -67
  59. package/assets/font-config.mjs +9 -6
  60. package/assets/font-sizes.mjs +163 -123
  61. package/assets/glyph-coverage.mjs +74 -54
  62. package/assets/index.mjs +31 -9
  63. package/assets/rasterize.mjs +126 -99
  64. package/assets/svg-loader.mjs +8 -8
  65. package/build.mjs +16 -14
  66. package/cli.mjs +359 -172
  67. package/compile-bin.mjs +5 -5
  68. package/flash.mjs +537 -0
  69. package/hotreload/dev-device.mjs +90 -33
  70. package/hotreload/pack-app.mjs +55 -43
  71. package/hotreload/pack-split.mjs +46 -37
  72. package/hotreload/package-transfer.mjs +175 -0
  73. package/hotreload/protocol.mjs +51 -38
  74. package/hotreload/uploader.mjs +38 -27
  75. package/hotreload/watch-tree.mjs +19 -19
  76. package/pack-container.mjs +31 -23
  77. package/package.json +11 -12
  78. package/persist-transform.mjs +34 -28
  79. package/qjsc-wasm.mjs +25 -14
  80. package/sim/embedded-react.cjs +1 -1
  81. package/sim/embedded-react.js +1 -1
  82. package/sim/embedded-react.wasm +0 -0
  83. package/sim/index.html +94 -85
  84. package/sim-server.mjs +101 -82
  85. package/src/embedded-react/Animated.js +24 -24
  86. package/src/embedded-react/Easing.js +1 -1
  87. package/src/embedded-react/FlatList.js +4 -4
  88. package/src/embedded-react/LayoutAnimation.js +8 -5
  89. package/src/embedded-react/PanResponder.js +75 -71
  90. package/src/embedded-react/Pressable.js +2 -8
  91. package/src/embedded-react/SectionList.js +6 -6
  92. package/src/embedded-react/StyleSheet.js +4 -3
  93. package/src/embedded-react/TouchableOpacity.js +13 -8
  94. package/src/embedded-react/index.d.ts +5 -5
  95. package/src/embedded-react/layout-anim-config.js +10 -4
  96. package/src/embedded-react/list-child.js +5 -5
  97. package/src/embedded-react/named-colors.js +1 -1
  98. package/src/embedded-react/split-style.js +11 -11
  99. package/src/embedded-react/svg-ops.js +760 -593
  100. package/src/embedded-react/useHostValue.js +3 -3
  101. package/src/embedded-react/usePersistentState.js +6 -6
  102. package/src/embedded-react/warn-props.js +1 -1
  103. package/src/host-config.js +60 -53
  104. package/src/props.js +49 -41
  105. package/src/renderer.js +7 -4
  106. package/aot/compiler/assemble.mjs +0 -944
  107. package/aot/compiler/c/animations.mjs +0 -436
  108. package/aot/compiler/c/boot.mjs +0 -127
  109. package/aot/compiler/c/expressions.mjs +0 -270
  110. package/aot/compiler/c/functions.mjs +0 -268
  111. package/aot/compiler/c/keyboard.mjs +0 -96
  112. package/aot/compiler/c/nodes.mjs +0 -303
  113. package/aot/compiler/c/pan-responder.mjs +0 -136
  114. package/aot/compiler/c/statements.mjs +0 -319
  115. package/aot/compiler/c/text.mjs +0 -83
  116. package/aot/compiler/c/vectors.mjs +0 -381
  117. package/aot/compiler/c-syntax.mjs +0 -127
@@ -0,0 +1,1329 @@
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
+ /*----------------------------------------------------------------------------------------------------------------------
32
+ - Constants
33
+ ---------------------------------------------------------------------------------------------------------------------*/
34
+ /** What rounding a double adds before it floors: a half rounds up. */
35
+ const ROUND_HALF_UP = 0.5;
36
+ /** The whole-number helpers' opcodes; the 64-bit ones add L. */
37
+ const HELPER_OPCODES = {
38
+ add: 'ADD',
39
+ sub: 'SUB',
40
+ mul: 'MUL',
41
+ neg: 'NEG',
42
+ mod: 'MOD',
43
+ abs: 'ABS',
44
+ min: 'MIN',
45
+ max: 'MAX',
46
+ floordiv: 'FLOORDIV',
47
+ ceildiv: 'CEILDIV',
48
+ rounddiv: 'ROUNDDIV',
49
+ div: 'DIV',
50
+ };
51
+ /** The arithmetic opcodes for each type. */
52
+ const ARITHMETIC_OPCODES = {
53
+ int: { '+': 'ADD', '-': 'SUB', '*': 'MUL', '/': 'DIV', '%': 'MOD' },
54
+ int64: { '+': 'ADDL', '-': 'SUBL', '*': 'MULL', '/': 'DIVL', '%': 'MODL' },
55
+ float: { '+': 'FADD', '-': 'FSUB', '*': 'FMUL', '/': 'FDIV' },
56
+ double: { '+': 'DADD', '-': 'DSUB', '*': 'DMUL', '/': 'DDIV' },
57
+ };
58
+ /** The comparison opcodes for each type: equal, less than, at most. */
59
+ const COMPARE_OPCODES = {
60
+ int: ['EQ', 'LT', 'LE'],
61
+ int64: ['LEQ', 'LLT', 'LLE'],
62
+ float: ['FEQ', 'FLT', 'FLE'],
63
+ double: ['DEQ', 'DLT', 'DLE'],
64
+ };
65
+ /** The conversion opcodes, by source and destination type. */
66
+ const CONVERSIONS = {
67
+ 'int>float': 'ITOF',
68
+ 'int>double': 'ITOD',
69
+ 'int>int64': 'ITOL',
70
+ 'float>int': 'FTOI',
71
+ 'float>double': 'FTOD',
72
+ 'float>int64': 'FTOL',
73
+ 'double>int': 'DTOI',
74
+ 'double>float': 'DTOF',
75
+ 'double>int64': 'DTOL',
76
+ 'int64>int': 'LTOI',
77
+ 'int64>float': 'LTOF',
78
+ 'int64>double': 'LTOD',
79
+ };
80
+ /** The event field each touch field, and what a <Dial> passes, reads. */
81
+ const EVENT_FIELDS = {
82
+ x: EventField.x,
83
+ y: EventField.y,
84
+ dx: EventField.dx,
85
+ dy: EventField.dy,
86
+ vx: EventField.vx,
87
+ vy: EventField.vy,
88
+ value: EventField.value,
89
+ value_start: EventField.valueStart,
90
+ };
91
+ /** The event field each onLayout field reads. */
92
+ const LAYOUT_FIELDS = {
93
+ x: EventField.layoutX,
94
+ y: EventField.layoutY,
95
+ width: EventField.layoutWidth,
96
+ height: EventField.layoutHeight,
97
+ };
98
+ /** The engine's display values. */
99
+ const DISPLAY_FLEX = 0;
100
+ const DISPLAY_NONE = 1;
101
+ /** A timer delay is ToInt32 of the value: its low 32 bits. */
102
+ const TWO_TO_32 = 2 ** 32;
103
+ const INT32_MAX = 0x7fffffff;
104
+ /** The int range, for an immediate that fits LOADI. */
105
+ const IMMEDIATE_MIN = -32768;
106
+ const IMMEDIATE_MAX = 32767;
107
+ /*----------------------------------------------------------------------------------------------------------------------
108
+ - Classes
109
+ ---------------------------------------------------------------------------------------------------------------------*/
110
+ /**
111
+ * Lowers IR into one function.
112
+ *
113
+ * @class Codegen
114
+ */
115
+ export class Codegen {
116
+ builder;
117
+ program;
118
+ inDoubles;
119
+ input;
120
+ onReturn;
121
+ row;
122
+ locals = new Map();
123
+ /** A string register nothing writes, so it stays the empty string. Reserved, so no release reuses it. */
124
+ emptyString = null;
125
+ /**
126
+ * @param builder The function being built.
127
+ * @param program The program's slots and tables.
128
+ * @param options inDoubles: fractions are worked out in double precision, for a value worked out at boot.
129
+ * input: the <TextInput> a CHANGE_TEXT handler reads.
130
+ * onReturn: where an effect's early `return` goes.
131
+ * row: the row a list row's handler was built for, which its item reads.
132
+ * finished: what an animation completion was passed, which its `finished` reads.
133
+ */
134
+ constructor(builder, program, options = {}) {
135
+ this.builder = builder;
136
+ this.program = program;
137
+ this.inDoubles = options.inDoubles ?? false;
138
+ this.input = options.input ?? null;
139
+ this.onReturn = options.onReturn ?? null;
140
+ this.row = options.row ?? null;
141
+ if (options.finished) {
142
+ this.locals.set('finished', { register: options.finished });
143
+ }
144
+ }
145
+ /*--------------------------------------------------------------------------------------------------------------------
146
+ - Types
147
+ -------------------------------------------------------------------------------------------------------------------*/
148
+ /**
149
+ * The type an expression is worked out in.
150
+ *
151
+ * @param expression The expression.
152
+ *
153
+ * @returns Its type.
154
+ */
155
+ typeOf(expression) {
156
+ const fraction = this.inDoubles ? 'double' : 'float';
157
+ switch (expression.kind) {
158
+ case 'number':
159
+ return expression.type.kind === 'float'
160
+ ? fraction
161
+ : expression.type.kind === 'int64'
162
+ ? 'int64'
163
+ : expression.type.kind === 'bool'
164
+ ? 'bool'
165
+ : 'int';
166
+ case 'string':
167
+ return 'string';
168
+ case 'boolean':
169
+ return 'bool';
170
+ case 'state':
171
+ // An interned state still reads as a string.
172
+ return this.program.enums.has(expression.state)
173
+ ? 'string'
174
+ : slotType(this.stateSlot(expression.state));
175
+ case 'boot':
176
+ return slotType(this.bootSlot(expression.slot));
177
+ case 'ref':
178
+ return slotType(this.refSlot(expression.ref));
179
+ case 'local': {
180
+ if (expression.local.expression) {
181
+ return this.typeOf(expression.local.expression);
182
+ }
183
+ const binding = this.binding(expression.local.name);
184
+ return !binding
185
+ ? 'string'
186
+ : 'register' in binding
187
+ ? binding.register.type
188
+ : slotType(binding.slot);
189
+ }
190
+ case 'event':
191
+ return expression.field === 'changed_text'
192
+ ? 'string'
193
+ : ['vx', 'vy', 'value', 'value_start'].includes(expression.field)
194
+ ? 'float'
195
+ : 'int';
196
+ case 'gesture':
197
+ return expression.field === 'vx' || expression.field === 'vy'
198
+ ? 'float'
199
+ : 'int';
200
+ case 'clock':
201
+ return 'int64';
202
+ case 'itemField':
203
+ return expression.field.kind;
204
+ case 'pi':
205
+ case 'toFloat':
206
+ case 'floatDivide':
207
+ case 'floatMath':
208
+ return fraction;
209
+ case 'unary':
210
+ return expression.operator === '!'
211
+ ? 'bool'
212
+ : promoted(this.typeOf(expression.operand));
213
+ case 'helper':
214
+ return expression.bits === 64 ? 'int64' : 'int';
215
+ case 'arithmetic':
216
+ return usual(this.typeOf(expression.left), this.typeOf(expression.right));
217
+ case 'wholeRound':
218
+ return this.typeOf(expression.operand);
219
+ case 'compare':
220
+ case 'stringEquals':
221
+ case 'logical':
222
+ return 'bool';
223
+ case 'pick':
224
+ return usual(this.typeOf(expression.left), this.typeOf(expression.right));
225
+ case 'conditional':
226
+ return usual(this.typeOf(expression.consequent), this.typeOf(expression.alternate));
227
+ default:
228
+ // layout, narrowRemainder, trunc, toInt, and what a package refuses
229
+ return 'int';
230
+ }
231
+ }
232
+ /*--------------------------------------------------------------------------------------------------------------------
233
+ - Values
234
+ -------------------------------------------------------------------------------------------------------------------*/
235
+ /**
236
+ * Works an expression out into a register of its type.
237
+ *
238
+ * @param expression The expression.
239
+ *
240
+ * @returns The register. A local's may be its own: never write to what this returns.
241
+ */
242
+ value(expression) {
243
+ const { builder } = this;
244
+ const type = this.typeOf(expression);
245
+ switch (expression.kind) {
246
+ case 'number':
247
+ return this.load(type, expression.value);
248
+ case 'string': {
249
+ const register = builder.register('string');
250
+ builder.abx('LOADS', register.index, this.program.tables.string(expression.value));
251
+ return register;
252
+ }
253
+ case 'boolean':
254
+ return this.load('bool', expression.value ? 1 : 0);
255
+ case 'state':
256
+ if (this.program.enums.has(expression.state)) {
257
+ throw new Error(`AOT internal: state "${expression.state.name}" is interned, but read as a string`);
258
+ }
259
+ return this.get(this.stateSlot(expression.state));
260
+ case 'boot':
261
+ return this.get(this.bootSlot(expression.slot));
262
+ case 'ref':
263
+ return this.get(this.refSlot(expression.ref));
264
+ case 'local':
265
+ return this.local(expression);
266
+ case 'listLength': {
267
+ const register = builder.register('int');
268
+ builder.abx('LEN', register.index, this.listPool(expression.list).slot.index);
269
+ return register;
270
+ }
271
+ case 'itemField':
272
+ return this.itemField(expression.item, expression.field.key, type);
273
+ case 'gesture':
274
+ return this.gesture(expression);
275
+ case 'event':
276
+ return expression.field === 'changed_text'
277
+ ? this.changedText()
278
+ : this.event(type, EVENT_FIELDS[expression.field]);
279
+ case 'layout':
280
+ return this.event('int', LAYOUT_FIELDS[expression.field]);
281
+ case 'clock': {
282
+ const register = builder.register('int64');
283
+ builder.abc(expression.clock === 'Date' ? 'DATENOW' : 'NOW', register.index);
284
+ return register;
285
+ }
286
+ case 'pi':
287
+ return this.load(type, Math.PI);
288
+ case 'toFloat':
289
+ case 'wholeRound':
290
+ return this.convert(this.value(expression.operand), type);
291
+ case 'unary':
292
+ return this.unary(expression.operator, expression.operand, type);
293
+ case 'helper': {
294
+ const argumentType = expression.bits === 64 ? 'int64' : 'int';
295
+ const argumentRegisters = expression.callArguments.map(argument => this.valueAs(argument, argumentType));
296
+ const register = builder.register(argumentType);
297
+ builder.abc(HELPER_OPCODES[expression.helper] +
298
+ (expression.bits === 64 ? 'L' : ''), register.index, argumentRegisters[0].index, (argumentRegisters[1] ?? argumentRegisters[0]).index);
299
+ return register;
300
+ }
301
+ case 'arithmetic':
302
+ return this.arithmetic(expression.operator, expression.left, expression.right, type);
303
+ case 'floatDivide':
304
+ return this.arithmetic('/', expression.left, expression.right, type);
305
+ case 'narrowRemainder': {
306
+ const operandType = usual(this.typeOf(expression.left), this.typeOf(expression.right));
307
+ return this.convert(this.arithmetic('%', expression.left, expression.right, operandType), 'int');
308
+ }
309
+ case 'floatMath': {
310
+ const argumentRegisters = expression.callArguments.map(argument => this.valueAs(argument, type));
311
+ const register = builder.register(type);
312
+ builder.abc(type === 'double' ? 'DMATH' : 'FMATH', register.index, argumentRegisters[0].index, (argumentRegisters[1] ?? argumentRegisters[0]).index, MathFn[expression.mathFunction]);
313
+ return register;
314
+ }
315
+ case 'trunc':
316
+ case 'toInt':
317
+ // Worked out as a float, or a double at boot.
318
+ return this.convert(this.valueAs(expression.operand, this.inDoubles ? 'double' : 'float'), 'int');
319
+ case 'compare':
320
+ return this.compare(expression.operator, expression.left, expression.right);
321
+ case 'stringEquals': {
322
+ if (this.enumOf(expression.left) || this.enumOf(expression.right)) {
323
+ return this.enumEquals(expression.operator, expression.left, expression.right);
324
+ }
325
+ const register = builder.register('bool');
326
+ builder.abc('SEQ', register.index, this.valueAs(expression.left, 'string').index, this.valueAs(expression.right, 'string').index);
327
+ if (expression.operator === '!=') {
328
+ builder.abc('NOT', register.index, register.index);
329
+ }
330
+ return register;
331
+ }
332
+ case 'logical': {
333
+ const register = builder.register('bool');
334
+ const end = builder.label();
335
+ builder.abc('MOVE', register.index, this.condition(expression.left).index);
336
+ builder.branch(expression.operator === '&&' ? 'JF' : 'JT', end, register);
337
+ builder.abc('MOVE', register.index, this.condition(expression.right).index);
338
+ builder.place(end);
339
+ return register;
340
+ }
341
+ case 'pick':
342
+ return this.pick(expression.operator, expression.left, expression.right, type);
343
+ case 'conditional':
344
+ return this.choose(this.condition(expression.test), () => this.valueAs(expression.consequent, type), () => this.valueAs(expression.alternate, type), type);
345
+ }
346
+ }
347
+ /**
348
+ * The set of an interned state an expression reads, or null when it reads none.
349
+ *
350
+ * @param expression The expression.
351
+ *
352
+ * @returns The set.
353
+ */
354
+ enumOf(expression) {
355
+ return expression.kind === 'state'
356
+ ? (this.program.enums.get(expression.state) ?? null)
357
+ : null;
358
+ }
359
+ /**
360
+ * A comparison of an interned state with a literal, or with itself, as an int compare. A literal it never
361
+ * holds is never equal.
362
+ *
363
+ * @param operator `==` or `!=`.
364
+ * @param left One side.
365
+ * @param right The other.
366
+ *
367
+ * @returns A bool register.
368
+ */
369
+ enumEquals(operator, left, right) {
370
+ const read = (this.enumOf(left) ? left : right);
371
+ const other = read === left ? right : left;
372
+ const { set, values } = this.enumOf(read);
373
+ if (other.kind !== 'string') {
374
+ return this.load('bool', operator === '==' ? 1 : 0);
375
+ }
376
+ const index = values.indexOf(other.value);
377
+ if (index < 0) {
378
+ return this.load('bool', operator === '==' ? 0 : 1);
379
+ }
380
+ 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);
382
+ if (operator === '!=') {
383
+ this.builder.abc('NOT', register.index, register.index);
384
+ }
385
+ return register;
386
+ }
387
+ /**
388
+ * One value of an enum set in a register.
389
+ *
390
+ * @param set The set.
391
+ * @param index The value's index in it.
392
+ *
393
+ * @returns The register.
394
+ */
395
+ enumValue(set, index) {
396
+ const register = this.builder.register('enum');
397
+ this.builder.abx('LOADE', register.index, index, set);
398
+ return register;
399
+ }
400
+ /**
401
+ * Works an expression out and converts it as an assignment to a type does.
402
+ *
403
+ * @param expression The expression.
404
+ * @param type The type it goes into.
405
+ *
406
+ * @returns A register of that type.
407
+ */
408
+ valueAs(expression, type) {
409
+ return this.convert(this.value(expression), type);
410
+ }
411
+ /**
412
+ * An expression as a condition: true exactly when JS finds it truthy. A string is truthy
413
+ * when it isn't empty.
414
+ *
415
+ * @param expression The expression.
416
+ *
417
+ * @returns A bool register.
418
+ */
419
+ condition(expression) {
420
+ return this.truthy(this.value(expression));
421
+ }
422
+ /**
423
+ * Converts a register to another type, as an assignment does. A number to a boolean is a test against
424
+ * zero; a boolean to a number is 0 or 1.
425
+ *
426
+ * @param register The register.
427
+ * @param type The type.
428
+ *
429
+ * @returns A register of that type: this one when it already is.
430
+ */
431
+ convert(register, type) {
432
+ const from = register.type;
433
+ if (from === type) {
434
+ return register;
435
+ }
436
+ if (type === 'bool') {
437
+ return this.truthy(register);
438
+ }
439
+ if (from === 'bool') {
440
+ const whole = this.builder.register('int');
441
+ const end = this.builder.label();
442
+ this.builder.abx('LOADI', whole.index, 0);
443
+ this.builder.branch('JF', end, register);
444
+ this.builder.abx('LOADI', whole.index, 1);
445
+ this.builder.place(end);
446
+ return this.convert(whole, type);
447
+ }
448
+ const opcode = CONVERSIONS[`${from}>${type}`];
449
+ if (!opcode) {
450
+ throw new Error(`AOT internal: no conversion from ${from} to ${type}`);
451
+ }
452
+ const converted = this.builder.register(type);
453
+ this.builder.abc(opcode, converted.index, register.index);
454
+ return converted;
455
+ }
456
+ /**
457
+ * Whether a register's value is truthy.
458
+ *
459
+ * @param register The register.
460
+ *
461
+ * @returns A bool register.
462
+ */
463
+ truthy(register) {
464
+ if (register.type === 'bool') {
465
+ return register;
466
+ }
467
+ const test = this.builder.register('bool');
468
+ if (register.type === 'string') {
469
+ this.builder.abc('SEQ', test.index, register.index, this.zero('string').index);
470
+ }
471
+ else {
472
+ const zero = this.load(register.type, 0);
473
+ this.builder.abc(COMPARE_OPCODES[register.type][0], test.index, register.index, zero.index);
474
+ }
475
+ this.builder.abc('NOT', test.index, test.index);
476
+ return test;
477
+ }
478
+ /**
479
+ * A constant in a register of a type.
480
+ *
481
+ * @param type The type.
482
+ * @param value The value.
483
+ *
484
+ * @returns The register.
485
+ */
486
+ load(type, value) {
487
+ const { builder } = this;
488
+ const { tables } = this.program;
489
+ const register = builder.register(type);
490
+ switch (type) {
491
+ case 'int':
492
+ case 'bool': {
493
+ const whole = Math.trunc(value) | 0;
494
+ if (whole >= IMMEDIATE_MIN && whole <= IMMEDIATE_MAX) {
495
+ builder.abx('LOADI', register.index, whole);
496
+ }
497
+ else {
498
+ builder.abx('LOADK', register.index, tables.constant32(whole));
499
+ }
500
+ break;
501
+ }
502
+ case 'float':
503
+ builder.abx('LOADK', register.index, tables.constant32(floatBits(value)));
504
+ break;
505
+ case 'double':
506
+ builder.abx('LOADK64', register.index, tables.constant64(doubleBits(value)));
507
+ break;
508
+ case 'int64':
509
+ builder.abx('LOADK64', register.index, tables.constant64(BigInt(Math.trunc(value))));
510
+ break;
511
+ default:
512
+ throw new Error(`AOT internal: no ${type} constant`);
513
+ }
514
+ return register;
515
+ }
516
+ /**
517
+ * Whether two registers of one type hold the same value.
518
+ *
519
+ * @param left One.
520
+ * @param right The other.
521
+ *
522
+ * @returns A bool register.
523
+ */
524
+ same(left, right) {
525
+ const register = this.builder.register('bool');
526
+ const opcode = left.type === 'string'
527
+ ? 'SEQ'
528
+ : left.type === 'bool' || left.type === 'enum'
529
+ ? 'EQ'
530
+ : COMPARE_OPCODES[left.type][0];
531
+ this.builder.abc(opcode, register.index, left.index, right.index);
532
+ return register;
533
+ }
534
+ /**
535
+ * A slot's value in a register of its type.
536
+ *
537
+ * @param slot The slot.
538
+ *
539
+ * @returns The register.
540
+ */
541
+ get(slot) {
542
+ const type = slotType(slot);
543
+ const register = this.builder.register(type);
544
+ const opcode = type === 'string'
545
+ ? 'GETS'
546
+ : type === 'int64' || type === 'double'
547
+ ? 'GET64'
548
+ : 'GET32';
549
+ this.builder.abx(opcode, register.index, slot.index);
550
+ return register;
551
+ }
552
+ /**
553
+ * Writes a register to a slot, converting it to the slot's type. A slot with a dirty bit has it set when the
554
+ * value changes.
555
+ *
556
+ * @param slot The slot.
557
+ * @param value The value.
558
+ */
559
+ set(slot, value) {
560
+ const type = slotType(slot);
561
+ const register = this.convert(value, type);
562
+ const opcode = type === 'string'
563
+ ? 'SETS'
564
+ : type === 'int64' || type === 'double'
565
+ ? 'SET64'
566
+ : 'SET32';
567
+ this.builder.abx(opcode, register.index, slot.index);
568
+ }
569
+ event(type, field) {
570
+ const register = this.builder.register(type);
571
+ this.builder.abc('EVT', register.index, field);
572
+ return register;
573
+ }
574
+ /**
575
+ * A gestureState field: travel from the grant, x0/y0 from the responder's state, the rest
576
+ * off the event.
577
+ *
578
+ * @param expression The field.
579
+ *
580
+ * @returns The register.
581
+ */
582
+ gesture(expression) {
583
+ const slots = this.program.gestures.get(expression.statePrefix);
584
+ switch (expression.field) {
585
+ case 'dx':
586
+ case 'dy': {
587
+ const travel = this.event('int', EVENT_FIELDS[expression.field]);
588
+ const base = this.get(expression.field === 'dx' ? slots.baseDeltaX : slots.baseDeltaY);
589
+ const register = this.builder.register('int');
590
+ this.builder.abc('SUB', register.index, travel.index, base.index);
591
+ return register;
592
+ }
593
+ case 'moveX':
594
+ return this.event('int', EventField.x);
595
+ case 'moveY':
596
+ return this.event('int', EventField.y);
597
+ case 'x0':
598
+ return this.get(slots.x0);
599
+ case 'y0':
600
+ return this.get(slots.y0);
601
+ case 'vx':
602
+ case 'vy':
603
+ return this.event('float', EVENT_FIELDS[expression.field]);
604
+ case 'numberActiveTouches':
605
+ return this.event('int', EventField.touches);
606
+ case 'stateID':
607
+ return this.load('int', expression.stateID);
608
+ }
609
+ }
610
+ /** The text a <TextInput> holds now, as its CHANGE_TEXT handler receives it. */
611
+ changedText() {
612
+ if (!this.input) {
613
+ throw new Error('AOT internal: changed text outside a CHANGE_TEXT handler');
614
+ }
615
+ const node = this.builder.register('node');
616
+ this.builder.abx('GET64', node.index, this.input.node.index);
617
+ this.builder.abx('INPUT', node.index, this.input.text.index);
618
+ return this.get(this.input.text);
619
+ }
620
+ /**
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 "".
622
+ *
623
+ * @param item The row's item.
624
+ * @param key The field.
625
+ * @param type Its type.
626
+ *
627
+ * @returns The register.
628
+ */
629
+ itemField(item, key, type) {
630
+ const { builder } = this;
631
+ const list = required(item.list, `the list of "${item.name}"`);
632
+ const field = list.struct.fields.findIndex(entry => entry.key === key);
633
+ 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, () => {
640
+ const register = builder.register(type);
641
+ builder.abc('ROWGET', register.index, row.index, 0, pool.index | (field << 16));
642
+ return register;
643
+ }, () => this.zero(type), type);
644
+ }
645
+ /** Zero, or the empty string, in a register of a type. */
646
+ zero(type) {
647
+ if (type !== 'string') {
648
+ return this.load(type, 0);
649
+ }
650
+ this.emptyString ??= this.builder.reserved('string');
651
+ return this.emptyString;
652
+ }
653
+ local(expression) {
654
+ // A memo, a component's prop or a helper's argument stands for its expression.
655
+ if (expression.local.expression) {
656
+ return this.value(expression.local.expression);
657
+ }
658
+ const binding = this.binding(expression.local.name);
659
+ if (!binding) {
660
+ return notYet('the value an element passes its callback');
661
+ }
662
+ return 'register' in binding ? binding.register : this.get(binding.slot);
663
+ }
664
+ /** A local's value, by name: this function's own, or an effect local kept in a slot. */
665
+ binding(name) {
666
+ const hoisted = this.program.hoisted.get(name);
667
+ return this.locals.get(name) ?? (hoisted && { slot: hoisted });
668
+ }
669
+ unary(operator, operand, type) {
670
+ if (operator === '!') {
671
+ const register = this.builder.register('bool');
672
+ this.builder.abc('NOT', register.index, this.condition(operand).index);
673
+ return register;
674
+ }
675
+ const value = this.valueAs(operand, type);
676
+ if (operator === '+') {
677
+ return value;
678
+ }
679
+ const register = this.builder.register(type);
680
+ const negateOpcode = {
681
+ int: 'NEG',
682
+ int64: 'NEGL',
683
+ float: 'FNEG',
684
+ double: 'DNEG',
685
+ }[type];
686
+ this.builder.abc(negateOpcode, register.index, value.index);
687
+ return register;
688
+ }
689
+ arithmetic(operator, left, right, type) {
690
+ const leftRegister = this.valueAs(left, type);
691
+ const rightRegister = this.valueAs(right, type);
692
+ const register = this.builder.register(type);
693
+ // The IR's float remainder is fmod.
694
+ if (operator === '%' && (type === 'float' || type === 'double')) {
695
+ this.builder.abc(type === 'double' ? 'DMATH' : 'FMATH', register.index, leftRegister.index, rightRegister.index, MathFn.mod);
696
+ return register;
697
+ }
698
+ this.builder.abc(ARITHMETIC_OPCODES[type][operator], register.index, leftRegister.index, rightRegister.index);
699
+ return register;
700
+ }
701
+ compare(operator, left, right) {
702
+ const type = promoted(usual(this.typeOf(left), this.typeOf(right)));
703
+ const leftRegister = this.valueAs(left, type);
704
+ const rightRegister = this.valueAs(right, type);
705
+ const [equal, less, atMost] = COMPARE_OPCODES[type];
706
+ const register = this.builder.register('bool');
707
+ const [opcode, first, second] = operator === '<'
708
+ ? [less, leftRegister, rightRegister]
709
+ : operator === '>'
710
+ ? [less, rightRegister, leftRegister]
711
+ : operator === '<='
712
+ ? [atMost, leftRegister, rightRegister]
713
+ : operator === '>='
714
+ ? [atMost, rightRegister, leftRegister]
715
+ : [equal, leftRegister, rightRegister];
716
+ this.builder.abc(opcode, register.index, first.index, second.index);
717
+ if (operator === '!=') {
718
+ this.builder.abc('NOT', register.index, register.index);
719
+ }
720
+ return register;
721
+ }
722
+ /** `a || b` as `(a ? a : b)`, and `a && b` as `(a ? b : a)`. */
723
+ pick(operator, left, right, type) {
724
+ // A string slot always reads as set here.
725
+ if (type === 'string') {
726
+ return this.valueAs(operator === '||' ? left : right, type);
727
+ }
728
+ const leftValue = this.value(left);
729
+ return this.choose(this.truthy(leftValue), () => this.convert(operator === '||' ? leftValue : this.value(right), type), () => this.convert(operator === '||' ? this.value(right) : leftValue, type), type);
730
+ }
731
+ /**
732
+ * `test ? whenTrue : whenFalse`, each side worked out only when it is chosen.
733
+ *
734
+ * @param test A bool register.
735
+ * @param whenTrue Works out the value when the test holds.
736
+ * @param whenFalse Works out the value when it doesn't.
737
+ * @param type The result's type.
738
+ *
739
+ * @returns The result.
740
+ */
741
+ choose(test, whenTrue, whenFalse, type) {
742
+ const { builder } = this;
743
+ const register = builder.register(type);
744
+ const otherwise = builder.label();
745
+ const end = builder.label();
746
+ builder.branch('JF', otherwise, test);
747
+ builder.abc('MOVE', register.index, whenTrue().index);
748
+ builder.branch('JMP', end);
749
+ builder.place(otherwise);
750
+ builder.abc('MOVE', register.index, whenFalse().index);
751
+ builder.place(end);
752
+ return register;
753
+ }
754
+ /*--------------------------------------------------------------------------------------------------------------------
755
+ - Text
756
+ -------------------------------------------------------------------------------------------------------------------*/
757
+ /**
758
+ * Builds a text in the format buffer, each part printed in turn. The caller puts it
759
+ * somewhere (FMTTEXT, FMTSET, or FMTSPAN), which empties the buffer.
760
+ *
761
+ * @param parts The text's parts.
762
+ */
763
+ text(parts) {
764
+ const { builder } = this;
765
+ for (const part of parts) {
766
+ const checkpoint = builder.checkpoint();
767
+ if (part.kind === 'literal') {
768
+ if (part.text) {
769
+ builder.abx('FMTK', 0, this.program.tables.string(part.text));
770
+ }
771
+ }
772
+ else if (part.kind === 'booleanWord') {
773
+ builder.abc('FMTB', this.condition(part.value).index);
774
+ }
775
+ else if (this.enumOf(part.value)) {
776
+ const value = part.value;
777
+ builder.abx('FMTE', this.get(this.stateSlot(value.state)).index, this.enumOf(value).set);
778
+ }
779
+ else {
780
+ // The spec is by the value's IR type: a float is printed from a float, so a boot double is narrowed first.
781
+ const type = part.value.type.kind;
782
+ const [opcode, formatType] = type === 'string'
783
+ ? ['FMTS', 'string']
784
+ : type === 'float'
785
+ ? ['FMTF', 'float']
786
+ : type === 'int64'
787
+ ? ['FMTL', 'int64']
788
+ : ['FMTI', 'int'];
789
+ builder.abc(opcode, this.valueAs(part.value, formatType).index);
790
+ }
791
+ builder.release(checkpoint);
792
+ }
793
+ }
794
+ /*--------------------------------------------------------------------------------------------------------------------
795
+ - Statements
796
+ -------------------------------------------------------------------------------------------------------------------*/
797
+ /**
798
+ * Lowers statements, in order.
799
+ *
800
+ * @param statements The statements.
801
+ */
802
+ statements(statements) {
803
+ for (const statement of statements) {
804
+ this.statement(statement);
805
+ }
806
+ }
807
+ statement(statement) {
808
+ const { builder } = this;
809
+ builder.at(statement.location);
810
+ switch (statement.kind) {
811
+ case 'declareLocal': {
812
+ const hoisted = this.program.hoisted.get(statement.name);
813
+ if (statement.isHoisted && !hoisted) {
814
+ throw new Error(`AOT internal: no slot for local "${statement.name}"`);
815
+ }
816
+ if (hoisted && slotType(hoisted) !== 'string') {
817
+ this.scoped(() => this.set(hoisted, this.value(statement.initializer)));
818
+ this.locals.set(statement.name, { slot: hoisted });
819
+ return;
820
+ }
821
+ if (this.typeOf(statement.initializer) === 'string') {
822
+ // 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
+ const slot = hoisted ?? this.program.stringLocals.get(statement.name);
824
+ const checkpoint = builder.checkpoint();
825
+ this.text([{ kind: 'value', value: statement.initializer }]);
826
+ builder.abx('FMTSET', 0, slot.index);
827
+ builder.release(checkpoint);
828
+ this.locals.set(statement.name, { slot });
829
+ return;
830
+ }
831
+ const type = declaredType(statement.initializer);
832
+ const register = builder.register(type);
833
+ const checkpoint = builder.checkpoint();
834
+ builder.abc('MOVE', register.index, this.valueAs(statement.initializer, type).index);
835
+ builder.release(checkpoint);
836
+ this.locals.set(statement.name, { register });
837
+ return;
838
+ }
839
+ case 'setState':
840
+ this.scoped(() => this.set(this.stateSlot(statement.state), this.value(statement.value)));
841
+ return;
842
+ case 'setStateText':
843
+ this.scoped(() => {
844
+ // An interned state is set to the index of the constant it is given.
845
+ const set = this.program.enums.get(statement.state);
846
+ if (set) {
847
+ const index = set.values.indexOf(constantText(statement.text));
848
+ builder.abx('SET32', this.enumValue(set.set, index).index, this.stateSlot(statement.state).index);
849
+ return;
850
+ }
851
+ this.text(statement.text.parts);
852
+ builder.abx('FMTSET', 0, this.stateSlot(statement.state).index);
853
+ });
854
+ return;
855
+ case 'writeRef':
856
+ this.scoped(() => this.writeRef(statement.ref, statement.operator, statement.value));
857
+ return;
858
+ case 'stepRef':
859
+ this.scoped(() => {
860
+ const slot = this.refSlot(statement.ref);
861
+ const type = slotType(slot);
862
+ const register = builder.register(type);
863
+ builder.abc(ARITHMETIC_OPCODES[type][statement.operator === '++' ? '+' : '-'], register.index, this.get(slot).index, this.load(type, 1).index);
864
+ this.set(slot, register);
865
+ });
866
+ return;
867
+ case 'if': {
868
+ const otherwise = builder.label();
869
+ const checkpoint = builder.checkpoint();
870
+ builder.branch('JF', otherwise, this.condition(statement.test));
871
+ builder.release(checkpoint);
872
+ this.statements(statement.consequent);
873
+ if (statement.alternate) {
874
+ const end = builder.label();
875
+ builder.branch('JMP', end);
876
+ builder.place(otherwise);
877
+ this.statements(statement.alternate);
878
+ builder.place(end);
879
+ }
880
+ else {
881
+ builder.place(otherwise);
882
+ }
883
+ return;
884
+ }
885
+ case 'startTimer':
886
+ this.startTimer(statement.timer, statement.idLocal?.name ?? null);
887
+ return;
888
+ case 'clearTimer':
889
+ this.scoped(() => builder.abc('TCLEAR', this.valueAs(statement.id, 'int').index));
890
+ return;
891
+ case 'clearList':
892
+ builder.abx('CLEAR', 0, this.listPool(statement.list).slot.index);
893
+ return;
894
+ case 'appendItem':
895
+ this.scoped(() => this.appendItem(statement));
896
+ return;
897
+ case 'dropLastItem':
898
+ builder.abx('POP', 0, this.listPool(statement.list).slot.index);
899
+ return;
900
+ case 'keepFirstItems':
901
+ this.scoped(() => builder.abx('KEEP', this.load('int', statement.count).index, this.listPool(statement.list).slot.index));
902
+ return;
903
+ case 'sliceItems':
904
+ // slice(0, end), as SLICE counts it.
905
+ this.scoped(() => builder.abc('SLICE', this.load('int', 0).index, this.valueAs(statement.end, 'int').index, 0, this.listPool(statement.list).slot.index));
906
+ return;
907
+ case 'stopAnimations':
908
+ case 'startAnimations':
909
+ case 'startChain':
910
+ case 'completeAfter':
911
+ animationStatement(this, statement, this.program.animations);
912
+ return;
913
+ case 'return':
914
+ if (!this.onReturn) {
915
+ throw new Error('AOT internal: a `return` outside an effect');
916
+ }
917
+ builder.branch('JMP', this.onReturn);
918
+ return;
919
+ case 'armCleanup':
920
+ this.scoped(() => this.set(required(this.program.armed.get(statement.flag), statement.flag), this.load('bool', 1)));
921
+ return;
922
+ case 'updateVector':
923
+ updateVector(this, statement, this.program.vectors);
924
+ }
925
+ }
926
+ /**
927
+ * Appends an item, its fields worked out in order into consecutive registers. A full list drops it.
928
+ * A text field is built in its own buffer first.
929
+ *
930
+ * @param statement The append.
931
+ */
932
+ appendItem(statement) {
933
+ const { builder } = this;
934
+ 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}"`);
939
+ this.text(itemValue.text.parts);
940
+ builder.abx('FMTSET', 0, buffer.index);
941
+ builder.abx('GETS', row[index].index, buffer.index);
942
+ }
943
+ else {
944
+ builder.abc('MOVE', row[index].index, this.valueAs(itemValue.value, itemValue.field.kind).index);
945
+ }
946
+ }));
947
+ builder.abx('APPEND', row[0].index, pool.slot.index);
948
+ }
949
+ /**
950
+ * Starts a timer, keeping its id in a local when the app names it.
951
+ *
952
+ * @param timer The timer.
953
+ * @param idLocal The local's name, or null.
954
+ */
955
+ startTimer(timer, idLocal) {
956
+ const { builder } = this;
957
+ const hoisted = idLocal === null ? undefined : this.program.hoisted.get(idLocal);
958
+ const start = (id) => this.scoped(() => {
959
+ builder.abc('TSTART', id.index, this.timerDelay(timer.delay).index, timer.isRepeating ? 1 : 0, required(this.program.timerFunctions.get(timer.functionName), `timer "${timer.functionName}"`));
960
+ if (hoisted) {
961
+ this.set(hoisted, id);
962
+ }
963
+ });
964
+ if (idLocal === null || hoisted) {
965
+ this.scoped(() => start(builder.register('int')));
966
+ if (hoisted) {
967
+ this.locals.set(idLocal, { slot: hoisted });
968
+ }
969
+ return;
970
+ }
971
+ // The id outlives this statement, so its register is taken outside the scope.
972
+ const id = builder.register('int');
973
+ start(id);
974
+ this.locals.set(idLocal, { register: id });
975
+ }
976
+ /**
977
+ * A timer's delay in ms: a 64-bit or fractional delay through ToInt32, with a
978
+ * negative one as 0. (The runtime waits at least 1 ms.)
979
+ *
980
+ * @param delay The delay, or null for none.
981
+ *
982
+ * @returns An int register.
983
+ */
984
+ timerDelay(delay) {
985
+ if (!delay) {
986
+ return this.load('int', 0);
987
+ }
988
+ const kind = delay.type.kind;
989
+ if (kind !== 'int64' && kind !== 'float') {
990
+ return this.valueAs(delay, 'int');
991
+ }
992
+ // A float delay becomes a 64-bit int; the VM's conversion saturates.
993
+ const { builder } = this;
994
+ const whole = kind === 'float'
995
+ ? this.convert(this.valueAs(delay, 'float'), 'int64')
996
+ : this.valueAs(delay, 'int64');
997
+ const modulus = this.load('int64', TWO_TO_32);
998
+ const low = builder.register('int64');
999
+ builder.abc('MODL', low.index, whole.index, modulus.index);
1000
+ builder.abc('ADDL', low.index, low.index, modulus.index);
1001
+ builder.abc('MODL', low.index, low.index, modulus.index);
1002
+ const tooBig = builder.register('bool');
1003
+ builder.abc('LLT', tooBig.index, this.load('int64', INT32_MAX).index, low.index);
1004
+ return this.choose(tooBig, () => this.load('int', 0), () => this.convert(low, 'int'), 'int');
1005
+ }
1006
+ writeRef(ref, operator, value) {
1007
+ const slot = this.refSlot(ref);
1008
+ if (operator === '=') {
1009
+ this.set(slot, this.value(value));
1010
+ return;
1011
+ }
1012
+ // `ref op= value` is `ref = ref op value`, worked out in the wider of the two types.
1013
+ const type = usual(slotType(slot), this.typeOf(value));
1014
+ const register = this.builder.register(type);
1015
+ this.builder.abc(ARITHMETIC_OPCODES[type][operator.slice(0, -1)], register.index, this.convert(this.get(slot), type).index, this.valueAs(value, type).index);
1016
+ this.set(slot, register);
1017
+ }
1018
+ /**
1019
+ * Runs a piece of lowering, then releases the registers it took.
1020
+ *
1021
+ * @param lower The lowering.
1022
+ */
1023
+ scoped(lower) {
1024
+ const checkpoint = this.builder.checkpoint();
1025
+ lower();
1026
+ this.builder.release(checkpoint);
1027
+ }
1028
+ /*--------------------------------------------------------------------------------------------------------------------
1029
+ - Props
1030
+ -------------------------------------------------------------------------------------------------------------------*/
1031
+ /**
1032
+ * Sets a state-driven prop in the props scratch, converting its value to the ERProps field's type.
1033
+ *
1034
+ * @param field The ERProps field.
1035
+ * @param value Its value.
1036
+ */
1037
+ setProp(field, value) {
1038
+ this.scoped(() => {
1039
+ const prop = abiProp(field);
1040
+ const result = this.propValue(value);
1041
+ const { builder } = this;
1042
+ if (result.conversion === 'opacity' || prop.kind === 'float') {
1043
+ // The runtime's PSETF scales an opacity to the engine's byte.
1044
+ builder.abx('PSETF', this.convert(result.register, 'float').index, prop.id);
1045
+ return;
1046
+ }
1047
+ if (result.conversion === 'dimension') {
1048
+ this.setDimension(prop.id, result.register);
1049
+ return;
1050
+ }
1051
+ // Any other field is a whole number: a fraction goes in truncated.
1052
+ builder.abx('PSETI', this.convert(result.register, 'int').index, prop.id);
1053
+ });
1054
+ }
1055
+ /**
1056
+ * A state-driven prop value, such as a paint's color, in the type it is worked out in.
1057
+ *
1058
+ * @param value The value.
1059
+ *
1060
+ * @returns The register.
1061
+ */
1062
+ propRegister(value) {
1063
+ const result = this.propValue(value);
1064
+ if (result.conversion) {
1065
+ notYet(`a ${result.conversion} outside a prop`);
1066
+ }
1067
+ return result.register;
1068
+ }
1069
+ /**
1070
+ * A dimension, rounded: halves up, clamped to int16, NaN as 0.
1071
+ *
1072
+ * @param prop The prop's id.
1073
+ * @param value The value.
1074
+ */
1075
+ setDimension(prop, value) {
1076
+ const { builder } = this;
1077
+ if (value.type === 'int' || value.type === 'bool') {
1078
+ builder.abx('PSETI', this.convert(value, 'int').index, prop);
1079
+ return;
1080
+ }
1081
+ if (value.type === 'float') {
1082
+ // The runtime rounds a float.
1083
+ builder.abx('PSETF', value.index, prop);
1084
+ return;
1085
+ }
1086
+ // A double (or a 64-bit int, which becomes a double) is rounded here, since a float can't hold it exactly.
1087
+ const rounded = builder.register('double');
1088
+ builder.abc('DADD', rounded.index, this.convert(value, 'double').index, this.load('double', ROUND_HALF_UP).index);
1089
+ builder.abc('DMATH', rounded.index, rounded.index, rounded.index, MathFn.floor);
1090
+ builder.abx('PSETI', this.convert(rounded, 'int').index, prop);
1091
+ }
1092
+ /**
1093
+ * A state-driven prop value, with the conversion on top of it lifted out. A conversion that maps 0 to
1094
+ * 0 (an opacity, a dimension) gives the same answer applied after a choice as inside it.
1095
+ *
1096
+ * @param value The value.
1097
+ *
1098
+ * @returns Its register, type and conversion.
1099
+ */
1100
+ propValue(value) {
1101
+ const plain = (register) => ({
1102
+ register,
1103
+ type: register.type,
1104
+ conversion: null,
1105
+ });
1106
+ switch (value.kind) {
1107
+ case 'constant':
1108
+ return plain(this.constantValue(value.value));
1109
+ case 'opacity':
1110
+ case 'dimension':
1111
+ return {
1112
+ ...plain(this.value(value.value)),
1113
+ conversion: value.kind,
1114
+ };
1115
+ case 'float':
1116
+ return plain(this.valueAs(value.value, 'float'));
1117
+ case 'byte':
1118
+ return this.propValue(value.value);
1119
+ case 'visible':
1120
+ // This tests the value itself, and a string slot always reads as set.
1121
+ return plain(this.display(value.value.type.kind === 'string'
1122
+ ? this.load('bool', 1)
1123
+ : this.condition(value.value)));
1124
+ case 'shown':
1125
+ return plain(this.display(this.shown(value.show)));
1126
+ case 'flag': {
1127
+ const test = value.truthiness === 'value' && value.test.type.kind === 'string'
1128
+ ? this.load('bool', 1)
1129
+ : this.condition(value.test);
1130
+ const register = this.builder.register('int');
1131
+ const end = this.builder.label();
1132
+ this.builder.abx('LOADI', register.index, 0);
1133
+ this.builder.branch(value.negate ? 'JT' : 'JF', end, test);
1134
+ this.builder.abx('LOADI', register.index, value.whenTrue);
1135
+ this.builder.place(end);
1136
+ return plain(register);
1137
+ }
1138
+ case 'whileShown': {
1139
+ const inner = this.propValue(value.value);
1140
+ return {
1141
+ ...plain(this.choose(this.shown(value.show), () => inner.register, () => this.load(inner.type, 0), inner.type)),
1142
+ conversion: inner.conversion,
1143
+ };
1144
+ }
1145
+ case 'select': {
1146
+ const test = this.condition(value.test);
1147
+ const whenTrue = this.propValue(value.whenTrue);
1148
+ const whenFalse = this.propValue(value.whenFalse);
1149
+ if (whenTrue.conversion !== whenFalse.conversion) {
1150
+ notYet('a state-driven prop that converts one of its choices only');
1151
+ }
1152
+ const type = usual(whenTrue.type, whenFalse.type);
1153
+ return {
1154
+ ...plain(this.choose(test, () => this.convert(whenTrue.register, type), () => this.convert(whenFalse.register, type), type)),
1155
+ conversion: whenTrue.conversion,
1156
+ };
1157
+ }
1158
+ }
1159
+ }
1160
+ /**
1161
+ * A constant prop value in a register.
1162
+ *
1163
+ * @param constant The constant.
1164
+ *
1165
+ * @returns The register.
1166
+ */
1167
+ constantValue(constant) {
1168
+ const value = constantNumber(constant);
1169
+ if (value === null) {
1170
+ return notYet(`the constant \`${constant}\``);
1171
+ }
1172
+ return this.load('int', value);
1173
+ }
1174
+ /** ER_DISPLAY_FLEX while a test holds, else ER_DISPLAY_NONE. */
1175
+ display(test) {
1176
+ const register = this.builder.register('int');
1177
+ const end = this.builder.label();
1178
+ this.builder.abx('LOADI', register.index, DISPLAY_NONE);
1179
+ this.builder.branch('JF', end, test);
1180
+ this.builder.abx('LOADI', register.index, DISPLAY_FLEX);
1181
+ this.builder.place(end);
1182
+ return register;
1183
+ }
1184
+ /**
1185
+ * Whether a node under a state-driven conditional shows: its test, negated for an else branch, within the
1186
+ * conditions it is nested in.
1187
+ *
1188
+ * @param show The condition.
1189
+ *
1190
+ * @returns A bool register.
1191
+ */
1192
+ shown(show) {
1193
+ if (show.kind === 'rowInUse') {
1194
+ const count = this.builder.register('int');
1195
+ const register = this.builder.register('bool');
1196
+ this.builder.abx('LEN', count.index, this.listPool(show.list).slot.index);
1197
+ this.builder.abc('LT', register.index, this.load('int', show.row).index, count.index);
1198
+ return register;
1199
+ }
1200
+ const register = this.builder.register('bool');
1201
+ this.builder.abc('MOVE', register.index, this.condition(show.test).index);
1202
+ if (show.negate) {
1203
+ this.builder.abc('NOT', register.index, register.index);
1204
+ }
1205
+ if (show.within) {
1206
+ const end = this.builder.label();
1207
+ this.builder.branch('JF', end, register);
1208
+ this.builder.abc('MOVE', register.index, this.shown(show.within).index);
1209
+ this.builder.place(end);
1210
+ }
1211
+ return register;
1212
+ }
1213
+ /*--------------------------------------------------------------------------------------------------------------------
1214
+ - Slots
1215
+ -------------------------------------------------------------------------------------------------------------------*/
1216
+ stateSlot(state) {
1217
+ return required(this.program.states.get(state), `state "${state.name}"`);
1218
+ }
1219
+ listPool(list) {
1220
+ return required(this.program.lists.get(list), `list "${list.name}"`);
1221
+ }
1222
+ refSlot(ref) {
1223
+ return ref.kind === 'node'
1224
+ ? notYet('reading a node ref')
1225
+ : required(this.program.refs.get(ref), `ref "${ref.slotName}"`);
1226
+ }
1227
+ bootSlot(slot) {
1228
+ return required(this.program.boot.get(slot), `boot value "${slot.field}"`);
1229
+ }
1230
+ }
1231
+ /*----------------------------------------------------------------------------------------------------------------------
1232
+ - Implementation
1233
+ ---------------------------------------------------------------------------------------------------------------------*/
1234
+ /**
1235
+ * Refuses what a package can't lower yet.
1236
+ *
1237
+ * @param what What the app uses.
1238
+ */
1239
+ export function notYet(what) {
1240
+ throw aotError(`AOT: a package doesn't support ${what} yet`);
1241
+ }
1242
+ /**
1243
+ * A slot or function that has to have been planned.
1244
+ *
1245
+ * @param planned The slot or function, if it was.
1246
+ * @param what What it holds, for the error.
1247
+ *
1248
+ * @returns The slot or function.
1249
+ */
1250
+ function required(planned, what) {
1251
+ if (planned === undefined) {
1252
+ throw new Error(`AOT internal: nothing planned for ${what}`);
1253
+ }
1254
+ return planned;
1255
+ }
1256
+ /**
1257
+ * The type a slot holds.
1258
+ *
1259
+ * @param slot The slot.
1260
+ *
1261
+ * @returns Its type.
1262
+ */
1263
+ export function slotType(slot) {
1264
+ return {
1265
+ [ValueType.int]: 'int',
1266
+ [ValueType.bool]: 'bool',
1267
+ [ValueType.float]: 'float',
1268
+ [ValueType.int64]: 'int64',
1269
+ [ValueType.double]: 'double',
1270
+ [ValueType.string]: 'string',
1271
+ [ValueType.enum]: 'enum',
1272
+ }[slot.type];
1273
+ }
1274
+ /**
1275
+ * 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
1276
+ * int over an int. Two booleans stay a boolean (an int holding 0 or 1).
1277
+ *
1278
+ * @param left One operand's type.
1279
+ * @param right The other's.
1280
+ *
1281
+ * @returns The type.
1282
+ */
1283
+ function usual(left, right) {
1284
+ if (left === 'string' || right === 'string') {
1285
+ return 'string';
1286
+ }
1287
+ if (left === 'bool' && right === 'bool') {
1288
+ return 'bool';
1289
+ }
1290
+ for (const type of ['double', 'float', 'int64']) {
1291
+ if (left === type || right === type) {
1292
+ return type;
1293
+ }
1294
+ }
1295
+ return 'int';
1296
+ }
1297
+ /** A boolean worked on as a number is an int. */
1298
+ const promoted = (type) => (type === 'bool' ? 'int' : type);
1299
+ /**
1300
+ * The type a handler local holds: what its IR type says.
1301
+ *
1302
+ * @param initializer The local's initial value.
1303
+ *
1304
+ * @returns Its type.
1305
+ */
1306
+ function declaredType(initializer) {
1307
+ switch (initializer.type.kind) {
1308
+ case 'bool':
1309
+ return 'bool';
1310
+ case 'float':
1311
+ return 'float';
1312
+ case 'int64':
1313
+ return 'int64';
1314
+ default:
1315
+ return 'int';
1316
+ }
1317
+ }
1318
+ /**
1319
+ * A double's 64 bits.
1320
+ *
1321
+ * @param value The number.
1322
+ *
1323
+ * @returns The bits.
1324
+ */
1325
+ function doubleBits(value) {
1326
+ const view = new DataView(new ArrayBuffer(8));
1327
+ view.setFloat64(0, value, true);
1328
+ return view.getBigUint64(0, true);
1329
+ }