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.
- package/NOTICE +5 -0
- package/README.md +8 -3
- package/aot/app-file-loader.mjs +116 -0
- package/aot/compile.mjs +180 -90
- package/aot/compiler/animations.mjs +568 -317
- package/aot/compiler/boot.mjs +97 -35
- package/aot/compiler/branch-merge.mjs +4 -3
- package/aot/compiler/check.mjs +70 -18
- package/aot/compiler/collect.mjs +787 -288
- package/aot/compiler/contexts.mjs +391 -0
- package/aot/compiler/control-flow.mjs +439 -268
- package/aot/compiler/custom-hooks.mjs +686 -0
- package/aot/compiler/diagnostics.mjs +22 -25
- package/aot/compiler/elements/activity-indicator.mjs +25 -24
- package/aot/compiler/elements/button.mjs +182 -0
- package/aot/compiler/elements/dial.mjs +91 -77
- package/aot/compiler/elements/flat-list.mjs +24 -22
- package/aot/compiler/elements/image-background.mjs +76 -0
- package/aot/compiler/elements/image.mjs +52 -50
- package/aot/compiler/elements/modal.mjs +31 -30
- package/aot/compiler/elements/props.mjs +61 -26
- package/aot/compiler/elements/rewrite.mjs +118 -0
- package/aot/compiler/elements/section-list.mjs +370 -0
- package/aot/compiler/elements/switch.mjs +42 -34
- package/aot/compiler/elements/text-input.mjs +34 -32
- package/aot/compiler/expressions.mjs +1685 -392
- package/aot/compiler/handlers.mjs +2029 -547
- package/aot/compiler/helper-values.mjs +312 -0
- package/aot/compiler/ir/functions.mjs +11 -1
- package/aot/compiler/ir/nodes.mjs +43 -4
- package/aot/compiler/ir/reads.mjs +223 -22
- package/aot/compiler/ir/text.mjs +5 -1
- package/aot/compiler/ir/types.mjs +26 -14
- package/aot/compiler/ir/vectors.mjs +5 -1
- package/aot/compiler/kept-states.mjs +177 -0
- package/aot/compiler/keyboard.mjs +17 -7
- package/aot/compiler/list-items.mjs +226 -0
- package/aot/compiler/list-order.mjs +586 -0
- package/aot/compiler/list-split.mjs +259 -0
- package/aot/compiler/loops.mjs +582 -0
- package/aot/compiler/lower.mjs +246 -111
- package/aot/compiler/native-files.mjs +439 -0
- package/aot/compiler/native-header.mjs +335 -0
- package/aot/compiler/native-modules.mjs +1173 -0
- package/aot/compiler/nodes.mjs +195 -172
- package/aot/compiler/options.mjs +37 -31
- package/aot/compiler/out.mjs +32 -23
- package/aot/compiler/package/animations.mjs +779 -0
- package/aot/compiler/package/arena.mjs +252 -0
- package/aot/compiler/package/assemble.mjs +175 -0
- package/aot/compiler/package/bytecode.mjs +315 -0
- package/aot/compiler/package/checks.mjs +1026 -0
- package/aot/compiler/package/codegen.mjs +2168 -0
- package/aot/compiler/package/enums.mjs +148 -0
- package/aot/compiler/package/format.mjs +771 -0
- package/aot/compiler/package/layouts.mjs +136 -0
- package/aot/compiler/package/lower.mjs +2103 -0
- package/aot/compiler/package/props.mjs +118 -0
- package/aot/compiler/package/string-caps.mjs +515 -0
- package/aot/compiler/package/tables.mjs +127 -0
- package/aot/compiler/package/vectors.mjs +502 -0
- package/aot/compiler/package/writer.mjs +686 -0
- package/aot/compiler/pan-responder.mjs +69 -61
- package/aot/compiler/parse.mjs +23 -21
- package/aot/compiler/record-shapes.mjs +246 -0
- package/aot/compiler/records.mjs +654 -0
- package/aot/compiler/reducers.mjs +272 -0
- package/aot/compiler/static-eval.mjs +340 -30
- package/aot/compiler/style-text.mjs +178 -174
- package/aot/compiler/svg.mjs +480 -251
- package/aot/compiler/switch-cases.mjs +198 -0
- package/aot/compiler/tagged-records.mjs +450 -0
- package/aot/compiler/typing.mjs +307 -0
- package/aot/compiler/updaters.mjs +320 -0
- package/aot/compiler/window-dimensions.mjs +94 -0
- package/aot/compiler/worked-values.mjs +319 -0
- package/aot/demo-file.mjs +30 -0
- package/aot/screenshot-smoke.mjs +54 -40
- package/aot/style-map.mjs +152 -92
- package/assets/bake-font.mjs +123 -77
- package/assets/bake-image.mjs +39 -22
- package/assets/bake-svg.mjs +361 -262
- package/assets/build-builtin-font.mjs +11 -7
- package/assets/emit-c.mjs +77 -58
- package/assets/emit-container.mjs +123 -37
- package/assets/emit-pack.mjs +77 -67
- package/assets/font-config.mjs +9 -6
- package/assets/font-sizes.mjs +163 -123
- package/assets/glyph-coverage.mjs +74 -54
- package/assets/index.mjs +31 -9
- package/assets/rasterize.mjs +126 -99
- package/assets/svg-loader.mjs +8 -8
- package/build.mjs +23 -13
- package/cli.mjs +402 -172
- package/compile-bin.mjs +3 -3
- package/flash.mjs +537 -0
- package/hotreload/dev-device.mjs +90 -33
- package/hotreload/pack-app.mjs +55 -43
- package/hotreload/pack-split.mjs +62 -64
- package/hotreload/package-transfer.mjs +175 -0
- package/hotreload/protocol.mjs +50 -37
- package/hotreload/uploader.mjs +38 -27
- package/hotreload/watch-tree.mjs +19 -19
- package/pack-container.mjs +37 -21
- package/package.json +7 -8
- package/persist-transform.mjs +34 -28
- package/qjsc-wasm.mjs +25 -14
- package/sim/embedded-react.cjs +1 -1
- package/sim/embedded-react.js +1 -1
- package/sim/embedded-react.wasm +0 -0
- package/sim/index.html +94 -85
- package/sim-server.mjs +113 -94
- package/src/embedded-react/Animated.js +24 -24
- package/src/embedded-react/Dimensions.js +37 -0
- package/src/embedded-react/Easing.js +1 -1
- package/src/embedded-react/FlatList.js +3 -3
- package/src/embedded-react/LayoutAnimation.js +8 -5
- package/src/embedded-react/PanResponder.js +75 -71
- package/src/embedded-react/Pressable.js +2 -8
- package/src/embedded-react/SectionList.js +7 -9
- package/src/embedded-react/StyleSheet.js +4 -3
- package/src/embedded-react/TouchableOpacity.js +13 -8
- package/src/embedded-react/index.d.ts +88 -8
- package/src/embedded-react/index.js +2 -0
- package/src/embedded-react/layout-anim-config.js +10 -4
- package/src/embedded-react/list-child.js +5 -5
- package/src/embedded-react/named-colors.js +1 -1
- package/src/embedded-react/nativeModule.js +462 -0
- package/src/embedded-react/split-style.js +11 -11
- package/src/embedded-react/svg-ops.js +760 -593
- package/src/embedded-react/useHostValue.js +3 -3
- package/src/embedded-react/usePersistentState.js +6 -6
- package/src/embedded-react/warn-props.js +1 -1
- package/src/host-config.js +60 -53
- package/src/props.js +49 -41
- package/src/renderer.js +7 -4
- package/aot/compiler/assemble.mjs +0 -944
- package/aot/compiler/c/animations.mjs +0 -436
- package/aot/compiler/c/boot.mjs +0 -127
- package/aot/compiler/c/expressions.mjs +0 -270
- package/aot/compiler/c/functions.mjs +0 -268
- package/aot/compiler/c/keyboard.mjs +0 -96
- package/aot/compiler/c/nodes.mjs +0 -303
- package/aot/compiler/c/pan-responder.mjs +0 -136
- package/aot/compiler/c/statements.mjs +0 -319
- package/aot/compiler/c/text.mjs +0 -83
- package/aot/compiler/c/vectors.mjs +0 -381
- package/aot/compiler/c-syntax.mjs +0 -127
|
@@ -17,22 +17,58 @@
|
|
|
17
17
|
- Imports
|
|
18
18
|
---------------------------------------------------------------------------------------------------------------------*/
|
|
19
19
|
import { parseColor, parsePath } from '../../src/embedded-react/svg-ops.js';
|
|
20
|
-
import { aotError, constantText, withLoc } from './diagnostics.mjs';
|
|
21
|
-
import { evalStatic } from './static-eval.mjs';
|
|
22
|
-
import {
|
|
20
|
+
import { aotError, constantText, ENGINE_STRING_MAX, withLoc, } from './diagnostics.mjs';
|
|
21
|
+
import { evalStatic, foldScope, RuntimeLeaf } from './static-eval.mjs';
|
|
22
|
+
import { fieldsUnder } from './list-items.mjs';
|
|
23
|
+
import { lowerNativeCall, nativeCalleeOf, nativeEventOf, nativeRecordCallOf, recordTreeOf, valueCount, } from './native-modules.mjs';
|
|
24
|
+
import { itemCallback, listChainOf, orderStatements } from './list-order.mjs';
|
|
25
|
+
import { handlerSplitList, lowerSplitInto } from './list-split.mjs';
|
|
26
|
+
import { boundObjectOf, expandObjectDeclarator, lowerRecordSet, objectTreeOf, } from './records.mjs';
|
|
27
|
+
import { narrowOn, narrowed } from './tagged-records.mjs';
|
|
28
|
+
import { exits, helperEnvironment, statementsOf } from './helper-values.mjs';
|
|
29
|
+
import { lowerFor, lowerForOf } from './loops.mjs';
|
|
30
|
+
import { switchAsIf } from './switch-cases.mjs';
|
|
31
|
+
import { isReturnSet, updaterStatements } from './updaters.mjs';
|
|
32
|
+
import { actionChoice, actionEnvironment, prunedStatements, } from './reducers.mjs';
|
|
33
|
+
import { whenTyped } from './check.mjs';
|
|
34
|
+
import { copyLocal, holdLater, localShape, setLater, shapeOf, typedLater, } from './typing.mjs';
|
|
35
|
+
import { bareLocalOf, binarySource, stateRead, is64BitLocal, is64BitSlot, mix64Error, staticInt, isTime64, constDivisor, lowerSource, typeSource, slotValueOf, lowerExpr, lowerExprWide, lowerText, lowerLogText, buildsText, } from './expressions.mjs';
|
|
23
36
|
import { isFn } from './collect.mjs';
|
|
37
|
+
import { keepingStates, readingLatest } from './kept-states.mjs';
|
|
24
38
|
import { isAnimatedCall, resolveAnim, animValues, lowerAnimateStart, stopWaitOwner, } from './animations.mjs';
|
|
25
|
-
import { svgNum, CAP_MAP, JOIN_MAP, arcTape, circleTape, rectTape, lineTape, checkedTapeNumber, checkVectorPaints, vectorPaintOf, } from './svg.mjs';
|
|
26
|
-
import { armedFlag } from './
|
|
27
|
-
import {
|
|
28
|
-
import { FLOAT, INT, isConvertible64, isIntSlot, isTime, refType, slotOf, } from './ir/types.mjs';
|
|
39
|
+
import { svgNum, CAP_MAP, JOIN_MAP, arcTape, circleTape, rectTape, lineTape, checkedTapeNumber, checkVectorPaints, vectorPaintOf, DEFAULT_MITER_LIMIT, } from './svg.mjs';
|
|
40
|
+
import { armedFlag } from './ir/functions.mjs';
|
|
41
|
+
import { INT, isConvertible64, isIntSlot, isTime, refType, STRING, } from './ir/types.mjs';
|
|
29
42
|
/*----------------------------------------------------------------------------------------------------------------------
|
|
30
43
|
- Constants
|
|
31
44
|
---------------------------------------------------------------------------------------------------------------------*/
|
|
45
|
+
/** The slot a native event's value of each type is read as: an Int64 converts like any number. */
|
|
46
|
+
const VALUE_SLOTS = {
|
|
47
|
+
int: { slotKind: 'int' },
|
|
48
|
+
float: { slotKind: 'float' },
|
|
49
|
+
bool: { slotKind: 'int', isBoolean: true },
|
|
50
|
+
int64: { slotKind: 'i64', isLiteral: true },
|
|
51
|
+
string: { slotKind: 'string' },
|
|
52
|
+
};
|
|
32
53
|
/** The constant 0, which a remainder by 0 or ±1 stores. */
|
|
33
54
|
const ZERO = { kind: 'number', value: 0, type: INT };
|
|
55
|
+
/** Keys an AST node keeps besides what it says: where it is, and its comments. */
|
|
56
|
+
const POSITION_KEYS = new Set([
|
|
57
|
+
'loc',
|
|
58
|
+
'start',
|
|
59
|
+
'end',
|
|
60
|
+
'range',
|
|
61
|
+
'extra',
|
|
62
|
+
'leadingComments',
|
|
63
|
+
'trailingComments',
|
|
64
|
+
'innerComments',
|
|
65
|
+
]);
|
|
66
|
+
/** Update locals made so far, which numbers the next one's name. */
|
|
67
|
+
let updateRows = 0;
|
|
68
|
+
/** Counts the native calls whose record is kept, to name its locals as no JS binding can be named. */
|
|
69
|
+
let keptRecords = 0;
|
|
34
70
|
/** Each updateVector shape key and the numbers its array takes, for errors. */
|
|
35
|
-
const
|
|
71
|
+
const UPDATE_VECTOR_ARGUMENTS = {
|
|
36
72
|
arc: '[cx, cy, r, startAngle, endAngle]',
|
|
37
73
|
circle: '[cx, cy, r]',
|
|
38
74
|
rect: '[x, y, width, height] or [x, y, width, height, rx, ry]',
|
|
@@ -41,87 +77,675 @@ const UPDATE_VECTOR_ARGS = {
|
|
|
41
77
|
/*----------------------------------------------------------------------------------------------------------------------
|
|
42
78
|
- Implementation
|
|
43
79
|
---------------------------------------------------------------------------------------------------------------------*/
|
|
80
|
+
/**
|
|
81
|
+
* Whether a value is left out of an item: null or undefined.
|
|
82
|
+
*
|
|
83
|
+
* @param node The value.
|
|
84
|
+
*
|
|
85
|
+
* @returns Whether it is.
|
|
86
|
+
*/
|
|
87
|
+
const leavesOut = (node) => node.type === 'NullLiteral' ||
|
|
88
|
+
(node.type === 'Identifier' && node.name === 'undefined');
|
|
89
|
+
/**
|
|
90
|
+
* Whether two expressions are written the same, wherever they are.
|
|
91
|
+
*
|
|
92
|
+
* @param first One.
|
|
93
|
+
* @param second The other.
|
|
94
|
+
*
|
|
95
|
+
* @returns Whether they are.
|
|
96
|
+
*/
|
|
97
|
+
function sameNode(first, second) {
|
|
98
|
+
if (first === second)
|
|
99
|
+
return true;
|
|
100
|
+
if (!first ||
|
|
101
|
+
!second ||
|
|
102
|
+
typeof first !== 'object' ||
|
|
103
|
+
typeof second !== 'object' ||
|
|
104
|
+
Array.isArray(first) !== Array.isArray(second)) {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
const keysOf = (value) => Object.keys(value).filter(key => !POSITION_KEYS.has(key));
|
|
108
|
+
const firstKeys = keysOf(first);
|
|
109
|
+
return (firstKeys.length === keysOf(second).length &&
|
|
110
|
+
firstKeys.every(key => sameNode(first[key], second[key])));
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Whether an expression reads any of some names.
|
|
114
|
+
*
|
|
115
|
+
* @param node The expression.
|
|
116
|
+
* @param names The names.
|
|
117
|
+
*
|
|
118
|
+
* @returns Whether it does.
|
|
119
|
+
*/
|
|
120
|
+
function mentions(node, names) {
|
|
121
|
+
if (!node || typeof node !== 'object')
|
|
122
|
+
return false;
|
|
123
|
+
if (Array.isArray(node))
|
|
124
|
+
return node.some(child => mentions(child, names));
|
|
125
|
+
const astNode = node;
|
|
126
|
+
if (astNode.type === 'Identifier')
|
|
127
|
+
return names.has(astNode.name);
|
|
128
|
+
return Object.entries(astNode).some(([key, child]) => !POSITION_KEYS.has(key) &&
|
|
129
|
+
!(key === 'property' &&
|
|
130
|
+
(astNode.type === 'MemberExpression' ||
|
|
131
|
+
astNode.type === 'OptionalMemberExpression') &&
|
|
132
|
+
!astNode.computed) &&
|
|
133
|
+
!(key === 'key' &&
|
|
134
|
+
astNode.type === 'ObjectProperty' &&
|
|
135
|
+
!astNode.computed) &&
|
|
136
|
+
mentions(child, names));
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The value an item's field is set to, checked against the field.
|
|
140
|
+
*
|
|
141
|
+
* @param field The field.
|
|
142
|
+
* @param valueNode Its value.
|
|
143
|
+
* @param listState The list.
|
|
144
|
+
* @param environment The expression environment.
|
|
145
|
+
*
|
|
146
|
+
* @returns The value.
|
|
147
|
+
*/
|
|
148
|
+
function itemValue(field, valueNode, listState, environment) {
|
|
149
|
+
if (field.kind === 'string') {
|
|
150
|
+
const text = lowerText(valueNode, environment);
|
|
151
|
+
checkConstantFits(text, `field "${field.key}" of list state "${listState.name}"`);
|
|
152
|
+
return { field, text };
|
|
153
|
+
}
|
|
154
|
+
const value = lowerExpr(valueNode, environment);
|
|
155
|
+
if ((field.kind === 'bool') !== (shapeOf(value) === 'bool')) {
|
|
156
|
+
throw aotError(`AOT: field "${field.key || 'value'}" of list state "${listState.name}" holds ${field.kind === 'bool' ? 'a boolean' : 'a number'}`, 'give it a value of the same kind as the initial ones.');
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
field,
|
|
160
|
+
value: field.kind === 'bool'
|
|
161
|
+
? value
|
|
162
|
+
: storeValue(value, () => field.kind),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The fields an appended item sets, by key: an object literal's, nested ones flattened into dotted keys, or a plain
|
|
167
|
+
* value's one field. A field set to null or undefined is left out.
|
|
168
|
+
*
|
|
169
|
+
* @param item The appended item.
|
|
170
|
+
* @param struct The list's fields.
|
|
171
|
+
* @param listName The list, for errors.
|
|
172
|
+
*
|
|
173
|
+
* @returns Each field's value.
|
|
174
|
+
*/
|
|
175
|
+
function appendedFields(item, struct, listName) {
|
|
176
|
+
const given = new Map();
|
|
177
|
+
if (struct.plain) {
|
|
178
|
+
if (item.type === 'ObjectExpression') {
|
|
179
|
+
throw aotError(`AOT: list state "${listName}" holds plain values, not objects`, 'append a value of the same kind as the initial ones.');
|
|
180
|
+
}
|
|
181
|
+
if (!leavesOut(item)) {
|
|
182
|
+
given.set('', item);
|
|
183
|
+
}
|
|
184
|
+
return given;
|
|
185
|
+
}
|
|
186
|
+
const visit = (object, path) => {
|
|
187
|
+
for (const property of object.properties) {
|
|
188
|
+
if (property.type !== 'ObjectProperty' || property.computed) {
|
|
189
|
+
throw aotError('AOT: an appended item must be an object literal of plain fields', 'write each field out: {title: t, n: 1}. Spreads, methods and computed keys are not lowered.');
|
|
190
|
+
}
|
|
191
|
+
const fieldPath = [...path, propertyKey(property)];
|
|
192
|
+
if (property.value.type === 'ObjectExpression') {
|
|
193
|
+
visit(property.value, fieldPath);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
// A field set to null or undefined, or an object of fields set to one, is left out.
|
|
197
|
+
const name = fieldPath.join('.');
|
|
198
|
+
const isField = struct.fields.some(field => field.key === name);
|
|
199
|
+
if (!isField &&
|
|
200
|
+
!(leavesOut(property.value) && fieldsUnder(struct, fieldPath).length)) {
|
|
201
|
+
throw noField(listName, name);
|
|
202
|
+
}
|
|
203
|
+
if (!leavesOut(property.value)) {
|
|
204
|
+
given.set(name, property.value);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
if (item.type !== 'ObjectExpression') {
|
|
209
|
+
throw new Error('AOT: appended list items must be object literals');
|
|
210
|
+
}
|
|
211
|
+
visit(item, []);
|
|
212
|
+
return given;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* An object property's key.
|
|
216
|
+
*
|
|
217
|
+
* @param property The property.
|
|
218
|
+
*
|
|
219
|
+
* @returns The key.
|
|
220
|
+
*/
|
|
221
|
+
const propertyKey = (property) => property.key.name ??
|
|
222
|
+
String(property.key.value);
|
|
223
|
+
/**
|
|
224
|
+
* The error for a field a list's items don't have.
|
|
225
|
+
*
|
|
226
|
+
* @param listName The list.
|
|
227
|
+
* @param name The field.
|
|
228
|
+
*
|
|
229
|
+
* @returns The error.
|
|
230
|
+
*/
|
|
231
|
+
const noField = (listName, name) => aotError(`AOT: list state "${listName}" has no field "${name}"`, "a list's fields are those of its initial items. Give one of them the field, and leave it out of the " +
|
|
232
|
+
'others to make it optional.');
|
|
233
|
+
/**
|
|
234
|
+
* A list row index: a whole number.
|
|
235
|
+
*
|
|
236
|
+
* @param node The index.
|
|
237
|
+
* @param listName The list, for errors.
|
|
238
|
+
* @param environment The expression environment.
|
|
239
|
+
*
|
|
240
|
+
* @returns The index.
|
|
241
|
+
*/
|
|
242
|
+
function rowIndexOf(node, listName, environment) {
|
|
243
|
+
const index = lowerExpr(node, environment);
|
|
244
|
+
whenTyped(() => {
|
|
245
|
+
if (index.type.kind !== 'int') {
|
|
246
|
+
throw aotError(`AOT: an index into "${listName}" must be a whole number`, 'an index is an int: Math.floor(x) or a whole-number state.');
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
return index;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* The index `items.filter((_, i) => i !== n)` removes: n.
|
|
253
|
+
*
|
|
254
|
+
* @param callback The filter's function.
|
|
255
|
+
*
|
|
256
|
+
* @returns n, or null when the filter is no such test.
|
|
257
|
+
*/
|
|
258
|
+
function filteredIndex(callback) {
|
|
259
|
+
const { itemName, indexName, body } = callback;
|
|
260
|
+
const isIndex = (node) => node.type === 'Identifier' && node.name === indexName;
|
|
261
|
+
const other = indexName &&
|
|
262
|
+
body.type === 'BinaryExpression' &&
|
|
263
|
+
(body.operator === '!==' || body.operator === '!=')
|
|
264
|
+
? isIndex(body.left)
|
|
265
|
+
? body.right
|
|
266
|
+
: isIndex(body.right)
|
|
267
|
+
? body.left
|
|
268
|
+
: null
|
|
269
|
+
: null;
|
|
270
|
+
const names = new Set([itemName, indexName].filter(Boolean));
|
|
271
|
+
return other && !mentions(other, names) ? other : null;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Whether an expression is the object at a path in an item: `base.pos.x` for ['pos', 'x'].
|
|
275
|
+
*
|
|
276
|
+
* @param node The expression.
|
|
277
|
+
* @param path The path.
|
|
278
|
+
* @param isItem Whether an expression is the item.
|
|
279
|
+
*
|
|
280
|
+
* @returns Whether it is.
|
|
281
|
+
*/
|
|
282
|
+
function isPathOf(node, path, isItem) {
|
|
283
|
+
let current = node;
|
|
284
|
+
for (let index = path.length - 1; index >= 0; index--) {
|
|
285
|
+
if (current.type !== 'MemberExpression' ||
|
|
286
|
+
current.computed ||
|
|
287
|
+
current.property.name !== path[index]) {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
current = current.object;
|
|
291
|
+
}
|
|
292
|
+
return isItem(current);
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* The statements an update runs on a row: `if`s for a ternary's tests, and a `setRow` for each item it builds.
|
|
296
|
+
* A branch that gives back the item itself changes nothing.
|
|
297
|
+
*
|
|
298
|
+
* @param node What the update gives the row.
|
|
299
|
+
* @param update The update.
|
|
300
|
+
*
|
|
301
|
+
* @returns The statements.
|
|
302
|
+
*/
|
|
303
|
+
function updateBody(node, update) {
|
|
304
|
+
if (update.isRow(node, [])) {
|
|
305
|
+
return [];
|
|
306
|
+
}
|
|
307
|
+
if (node.type === 'ConditionalExpression') {
|
|
308
|
+
const consequent = updateBody(node.consequent, update);
|
|
309
|
+
const alternate = updateBody(node.alternate, update);
|
|
310
|
+
if (!consequent.length && !alternate.length) {
|
|
311
|
+
return [];
|
|
312
|
+
}
|
|
313
|
+
return [
|
|
314
|
+
{
|
|
315
|
+
kind: 'if',
|
|
316
|
+
test: lowerExprWide(node.test, update.environment),
|
|
317
|
+
consequent,
|
|
318
|
+
alternate: alternate.length ? alternate : null,
|
|
319
|
+
},
|
|
320
|
+
];
|
|
321
|
+
}
|
|
322
|
+
return [setRow(node, update)];
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Sets a row to an item: a spread of the row's own item keeps the fields it doesn't set; without one, every field
|
|
326
|
+
* it leaves out is undefined from then on.
|
|
327
|
+
*
|
|
328
|
+
* @param node The item.
|
|
329
|
+
* @param update The update.
|
|
330
|
+
*
|
|
331
|
+
* @returns The statement.
|
|
332
|
+
*/
|
|
333
|
+
function setRow(node, update) {
|
|
334
|
+
const { list, listName, environment } = update;
|
|
335
|
+
const { struct } = list;
|
|
336
|
+
const given = new Map();
|
|
337
|
+
const cleared = new Set();
|
|
338
|
+
// A key written twice takes its last value, as in JS.
|
|
339
|
+
const give = (field, value) => {
|
|
340
|
+
cleared.delete(field);
|
|
341
|
+
given.set(field, value);
|
|
342
|
+
};
|
|
343
|
+
const clear = (field) => {
|
|
344
|
+
given.delete(field);
|
|
345
|
+
cleared.add(field);
|
|
346
|
+
};
|
|
347
|
+
if (struct.plain) {
|
|
348
|
+
if (node.type === 'ObjectExpression') {
|
|
349
|
+
throw aotError(`AOT: list state "${listName}" holds plain values, not objects`, 'give a value of the same kind as the initial ones.');
|
|
350
|
+
}
|
|
351
|
+
if (leavesOut(node)) {
|
|
352
|
+
clear(struct.fields[0]);
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
give(struct.fields[0], node);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
if (node.type !== 'ObjectExpression') {
|
|
360
|
+
throw aotError(`AOT: an item of "${listName}" must be replaced with an object literal`, 'spread the item and set the fields that change: {...item, done: true}.');
|
|
361
|
+
}
|
|
362
|
+
const visit = (object, path) => {
|
|
363
|
+
const seen = new Set();
|
|
364
|
+
let keeps = false;
|
|
365
|
+
object.properties.forEach((property, position) => {
|
|
366
|
+
if (property.type === 'SpreadElement') {
|
|
367
|
+
if (position !== 0 || !update.isRow(property.argument, path)) {
|
|
368
|
+
throw aotError('AOT: an updated item can spread only the item it replaces, first', path.length
|
|
369
|
+
? `spread the same object: {...item, ${path[0]}: {...item.${path.join('.')}, x: 1}}.`
|
|
370
|
+
: 'spread the item, then set the fields that change: {...item, done: true}.');
|
|
371
|
+
}
|
|
372
|
+
keeps = true;
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
if (property.type !== 'ObjectProperty' || property.computed) {
|
|
376
|
+
throw aotError('AOT: an updated item must be an object literal of plain fields', 'write each field out: {...item, title: t, n: 1}. Methods and computed keys are not lowered.');
|
|
377
|
+
}
|
|
378
|
+
const fieldPath = [...path, propertyKey(property)];
|
|
379
|
+
const fields = fieldsUnder(struct, fieldPath);
|
|
380
|
+
if (!fields.length) {
|
|
381
|
+
throw noField(listName, fieldPath.join('.'));
|
|
382
|
+
}
|
|
383
|
+
// A key written again replaces all an earlier value set under it.
|
|
384
|
+
fields.forEach(field => {
|
|
385
|
+
seen.add(field);
|
|
386
|
+
given.delete(field);
|
|
387
|
+
cleared.delete(field);
|
|
388
|
+
});
|
|
389
|
+
const { value } = property;
|
|
390
|
+
if (value.type === 'ObjectExpression') {
|
|
391
|
+
visit(value, fieldPath);
|
|
392
|
+
}
|
|
393
|
+
else if (leavesOut(value)) {
|
|
394
|
+
fields.forEach(field => clear(field));
|
|
395
|
+
}
|
|
396
|
+
else if (fields.length === 1 &&
|
|
397
|
+
fields[0].key === fieldPath.join('.')) {
|
|
398
|
+
give(fields[0], value);
|
|
399
|
+
}
|
|
400
|
+
else if (!update.isRow(value, fieldPath)) {
|
|
401
|
+
throw aotError(`AOT: field "${fieldPath.join('.')}" of list state "${listName}" holds an object`, `set its fields with an object literal: {...item, ${fieldPath[0]}: {...item.${fieldPath.join('.')}, x: 1}}.`);
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
if (!keeps) {
|
|
405
|
+
for (const field of fieldsUnder(struct, path)) {
|
|
406
|
+
if (!seen.has(field)) {
|
|
407
|
+
clear(field);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
visit(node, []);
|
|
413
|
+
}
|
|
414
|
+
const values = [];
|
|
415
|
+
for (const field of struct.fields) {
|
|
416
|
+
const valueNode = given.get(field);
|
|
417
|
+
if (cleared.has(field)) {
|
|
418
|
+
field.optional = true;
|
|
419
|
+
}
|
|
420
|
+
else if (valueNode) {
|
|
421
|
+
values.push(itemValue(field, valueNode, list, environment));
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return { kind: 'setRow', list, values, cleared: [...cleared] };
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* The local an update's row index is read through. Each has a name of its own, which no JS name can clash with.
|
|
428
|
+
*
|
|
429
|
+
* @returns The local.
|
|
430
|
+
*/
|
|
431
|
+
function updateRowLocal() {
|
|
432
|
+
return { slotKind: 'int', name: `#row${updateRows++}` };
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Whether an expression reads a row of a list by index: `items[k]`, under the list's name or the name a setter's
|
|
436
|
+
* updater gives it.
|
|
437
|
+
*
|
|
438
|
+
* @param node The expression.
|
|
439
|
+
* @param listState The list.
|
|
440
|
+
* @param listName What the setter's argument calls it.
|
|
441
|
+
* @param environment The expression environment.
|
|
442
|
+
*
|
|
443
|
+
* @returns Whether it does.
|
|
444
|
+
*/
|
|
445
|
+
function readsRowsOf(node, listState, listName, environment) {
|
|
446
|
+
if (!node || typeof node !== 'object')
|
|
447
|
+
return false;
|
|
448
|
+
if (Array.isArray(node)) {
|
|
449
|
+
return node.some(child => readsRowsOf(child, listState, listName, environment));
|
|
450
|
+
}
|
|
451
|
+
const astNode = node;
|
|
452
|
+
if ((astNode.type === 'MemberExpression' ||
|
|
453
|
+
astNode.type === 'OptionalMemberExpression') &&
|
|
454
|
+
astNode.computed &&
|
|
455
|
+
astNode.object.type === 'Identifier' &&
|
|
456
|
+
(astNode.object.name === listName ||
|
|
457
|
+
environment.state.get(astNode.object.name) === listState)) {
|
|
458
|
+
return true;
|
|
459
|
+
}
|
|
460
|
+
return Object.entries(astNode).some(([key, child]) => !POSITION_KEYS.has(key) &&
|
|
461
|
+
readsRowsOf(child, listState, listName, environment));
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Lowers `items.map(…)` as a list's next value: each row is visited, and set to what the function gives it.
|
|
465
|
+
*
|
|
466
|
+
* @param listState The list.
|
|
467
|
+
* @param listName What the setter's argument calls it.
|
|
468
|
+
* @param argument The map's function.
|
|
469
|
+
* @param environment The expression environment.
|
|
470
|
+
*
|
|
471
|
+
* @returns The statements.
|
|
472
|
+
*/
|
|
473
|
+
function lowerItemsMap(listState, listName, argument, environment) {
|
|
474
|
+
const { itemName, indexName, body } = itemCallback(argument, `${listName}.map`);
|
|
475
|
+
// The rows are set in place, one after another, so a read of another row could see its new value.
|
|
476
|
+
if (readsRowsOf(body, listState, listName, environment)) {
|
|
477
|
+
throw aotError(`AOT: ${listName}.map's function can't read other items of ${listName}`, 'its items are set in place, so a read of another one could see its new value. Read it into a const ' +
|
|
478
|
+
`before the setter: const first = ${listName}[0].n.`);
|
|
479
|
+
}
|
|
480
|
+
const row = updateRowLocal();
|
|
481
|
+
const locals = new Map(environment.locals);
|
|
482
|
+
if (itemName) {
|
|
483
|
+
locals.set(itemName, {
|
|
484
|
+
name: itemName,
|
|
485
|
+
struct: listState.struct,
|
|
486
|
+
list: listState,
|
|
487
|
+
index: { kind: 'local', local: row, type: INT },
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
if (indexName) {
|
|
491
|
+
locals.set(indexName, row);
|
|
492
|
+
}
|
|
493
|
+
const statements = updateBody(body, {
|
|
494
|
+
list: listState,
|
|
495
|
+
listName,
|
|
496
|
+
environment: { ...environment, locals },
|
|
497
|
+
isRow: (node, path) => isPathOf(node, path, item => item.type === 'Identifier' && item.name === itemName),
|
|
498
|
+
});
|
|
499
|
+
return statements.length
|
|
500
|
+
? [
|
|
501
|
+
{
|
|
502
|
+
kind: 'updateItems',
|
|
503
|
+
list: listState,
|
|
504
|
+
row,
|
|
505
|
+
index: null,
|
|
506
|
+
body: statements,
|
|
507
|
+
},
|
|
508
|
+
]
|
|
509
|
+
: [];
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Lowers `items.with(n, item)` as a list's next value: row n is set to the item. A negative n counts back from the
|
|
513
|
+
* end, and a row past either end stops the app, as JS throws there.
|
|
514
|
+
*
|
|
515
|
+
* @param listState The list.
|
|
516
|
+
* @param listName What the setter's argument calls it.
|
|
517
|
+
* @param argumentNodes The call's arguments.
|
|
518
|
+
* @param environment The expression environment.
|
|
519
|
+
*
|
|
520
|
+
* @returns The statements.
|
|
521
|
+
*/
|
|
522
|
+
function lowerItemsWith(listState, listName, argumentNodes, environment) {
|
|
523
|
+
const [indexNode, itemNode] = argumentNodes;
|
|
524
|
+
if (argumentNodes.length !== 2 ||
|
|
525
|
+
indexNode.type === 'SpreadElement' ||
|
|
526
|
+
itemNode.type === 'SpreadElement') {
|
|
527
|
+
throw aotError(`AOT: ${listName}.with takes an index and an item`, `e.g. ${listName}.with(n, {...${listName}[n], done: true}).`);
|
|
528
|
+
}
|
|
529
|
+
const index = rowIndexOf(indexNode, listName, environment);
|
|
530
|
+
const constantIndex = staticInt(indexNode, environment);
|
|
531
|
+
// The replaced item: items[n], or a row's own item when n is that row's index. For a negative n, with() counts
|
|
532
|
+
// back but items[n] is undefined, so what the update keeps from it isn't the row's.
|
|
533
|
+
let keepsIndexed = false;
|
|
534
|
+
const isItem = (node) => {
|
|
535
|
+
if (node.type === 'MemberExpression' &&
|
|
536
|
+
node.computed &&
|
|
537
|
+
node.object.type === 'Identifier' &&
|
|
538
|
+
node.object.name === listName) {
|
|
539
|
+
const same = sameNode(node.property, indexNode);
|
|
540
|
+
keepsIndexed ||= same;
|
|
541
|
+
return same;
|
|
542
|
+
}
|
|
543
|
+
const local = node.type === 'Identifier'
|
|
544
|
+
? environment.locals.get(node.name)
|
|
545
|
+
: undefined;
|
|
546
|
+
return (local?.list === listState &&
|
|
547
|
+
local.row !== undefined &&
|
|
548
|
+
local.row === constantIndex);
|
|
549
|
+
};
|
|
550
|
+
const row = updateRowLocal();
|
|
551
|
+
const statements = updateBody(itemNode, {
|
|
552
|
+
list: listState,
|
|
553
|
+
listName,
|
|
554
|
+
environment,
|
|
555
|
+
isRow: (node, path) => isPathOf(node, path, isItem),
|
|
556
|
+
});
|
|
557
|
+
if (keepsIndexed && constantIndex !== null && constantIndex < 0) {
|
|
558
|
+
throw aotError(`AOT: ${listName}.with(${constantIndex}, …) keeps fields of ${listName}[${constantIndex}], which is undefined`, `with() counts a negative index back from the end, but ${listName}[${constantIndex}] doesn't. ` +
|
|
559
|
+
`Use the index it counts back to, e.g. ${listName}.length - 1.`);
|
|
560
|
+
}
|
|
561
|
+
// Even an update that changes nothing reads the row, so an index past the end faults.
|
|
562
|
+
return [
|
|
563
|
+
{
|
|
564
|
+
kind: 'updateItems',
|
|
565
|
+
list: listState,
|
|
566
|
+
row,
|
|
567
|
+
index,
|
|
568
|
+
body: statements,
|
|
569
|
+
negativeKeeps: keepsIndexed && constantIndex === null,
|
|
570
|
+
},
|
|
571
|
+
];
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* The arguments of a call to a method of the list: `items.slice(…)`, or null when it is no such call.
|
|
575
|
+
*
|
|
576
|
+
* @param node The expression.
|
|
577
|
+
* @param listName The list's name.
|
|
578
|
+
* @param method The method.
|
|
579
|
+
*
|
|
580
|
+
* @returns The arguments.
|
|
581
|
+
*/
|
|
582
|
+
function listCall(node, listName, method) {
|
|
583
|
+
return node?.type === 'CallExpression' &&
|
|
584
|
+
node.callee.type === 'MemberExpression' &&
|
|
585
|
+
!node.callee.computed &&
|
|
586
|
+
node.callee.object.type === 'Identifier' &&
|
|
587
|
+
node.callee.object.name === listName &&
|
|
588
|
+
node.callee.property.name === method
|
|
589
|
+
? node.arguments
|
|
590
|
+
: null;
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* The index `[...items.slice(0, n), ...items.slice(n + 1)]` removes, or null when the list literal is not that.
|
|
594
|
+
*
|
|
595
|
+
* @param nextList The list literal.
|
|
596
|
+
* @param listName The list's name.
|
|
597
|
+
* @param environment The expression environment.
|
|
598
|
+
*
|
|
599
|
+
* @returns n.
|
|
600
|
+
*/
|
|
601
|
+
function slicedOutIndex(nextList, listName, environment) {
|
|
602
|
+
const [first, second] = nextList.elements;
|
|
603
|
+
if (nextList.elements.length !== 2 ||
|
|
604
|
+
first?.type !== 'SpreadElement' ||
|
|
605
|
+
second?.type !== 'SpreadElement') {
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
const before = listCall(first.argument, listName, 'slice');
|
|
609
|
+
const after = listCall(second.argument, listName, 'slice');
|
|
610
|
+
if (before?.length !== 2 || after?.length !== 1) {
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
const [start, end] = before;
|
|
614
|
+
const [next] = after;
|
|
615
|
+
const constantEnd = staticInt(end, environment);
|
|
616
|
+
const constantNext = staticInt(next, environment);
|
|
617
|
+
const followsOn = (next.type === 'BinaryExpression' &&
|
|
618
|
+
next.operator === '+' &&
|
|
619
|
+
sameNode(next.left, end) &&
|
|
620
|
+
staticInt(next.right, environment) === 1) ||
|
|
621
|
+
(constantEnd !== null && constantNext === constantEnd + 1);
|
|
622
|
+
if (staticInt(start, environment) !== 0 ||
|
|
623
|
+
!followsOn ||
|
|
624
|
+
(constantEnd !== null && constantEnd < 0)) {
|
|
625
|
+
throw aotError(`AOT: only [...${listName}.slice(0, n), ...${listName}.slice(n + 1)] is supported to splice a list`, 'it removes item n, which must not be negative.');
|
|
626
|
+
}
|
|
627
|
+
return end;
|
|
628
|
+
}
|
|
44
629
|
/**
|
|
45
630
|
* Lowers a list-state setter call (`setItems(...)`) to bounded list operations.
|
|
46
631
|
*
|
|
47
632
|
* @param listState The list state.
|
|
48
633
|
* @param nextList The setter's argument: the list's next value.
|
|
49
|
-
* @param
|
|
634
|
+
* @param environment The expression environment.
|
|
635
|
+
* @param listName What the argument calls the list: its name, or an updater's parameter.
|
|
50
636
|
*
|
|
51
637
|
* @returns The statements.
|
|
52
638
|
*/
|
|
53
|
-
function lowerListOp(listState, nextList,
|
|
54
|
-
const {
|
|
55
|
-
//
|
|
639
|
+
function lowerListOp(listState, nextList, environment, listName = listState.name) {
|
|
640
|
+
const { capacity: capacity, struct } = listState;
|
|
641
|
+
// setWords(text.split(',')) — the pieces replace the rows.
|
|
642
|
+
const split = lowerSplitInto(listState, nextList, environment, listName);
|
|
643
|
+
if (split)
|
|
644
|
+
return split;
|
|
645
|
+
// setItems([...items, a, b]) — append; setItems([]) — clear; [...items.slice(0, n), ...items.slice(n + 1)] — remove.
|
|
56
646
|
if (nextList.type === 'ArrayExpression') {
|
|
57
647
|
if (nextList.elements.length === 0) {
|
|
58
648
|
return [{ kind: 'clearList', list: listState }];
|
|
59
649
|
}
|
|
650
|
+
const slicedOut = slicedOutIndex(nextList, listName, environment);
|
|
651
|
+
if (slicedOut) {
|
|
652
|
+
return [
|
|
653
|
+
{
|
|
654
|
+
kind: 'removeItem',
|
|
655
|
+
list: listState,
|
|
656
|
+
index: rowIndexOf(slicedOut, listName, environment),
|
|
657
|
+
negative: 'sliced',
|
|
658
|
+
},
|
|
659
|
+
];
|
|
660
|
+
}
|
|
60
661
|
const [firstElement, ...appendedItems] = nextList.elements;
|
|
61
662
|
if (firstElement?.type !== 'SpreadElement' ||
|
|
62
|
-
firstElement.argument.name !==
|
|
63
|
-
throw new Error(`AOT: a list literal must spread the current list first: [...${
|
|
663
|
+
firstElement.argument.name !== listName) {
|
|
664
|
+
throw new Error(`AOT: a list literal must spread the current list first: [...${listName}, item]`);
|
|
64
665
|
}
|
|
65
|
-
// Each appended
|
|
66
|
-
//
|
|
666
|
+
// Each appended item fills the next free row; a full list drops it. A field it leaves out is 0 or "", and
|
|
667
|
+
// optional from then on, so a read of it sees undefined.
|
|
67
668
|
const statements = [];
|
|
68
669
|
for (const item of appendedItems) {
|
|
69
670
|
if (!item) {
|
|
70
671
|
throw aotError('AOT: a list literal has an empty slot');
|
|
71
672
|
}
|
|
72
|
-
if (item.type
|
|
73
|
-
throw
|
|
673
|
+
if (item.type === 'SpreadElement') {
|
|
674
|
+
throw aotError(`AOT: a list literal can spread only the current list, first: [...${listName}, item]`);
|
|
74
675
|
}
|
|
75
|
-
const
|
|
76
|
-
prop.key.name ??
|
|
77
|
-
prop.key.value,
|
|
78
|
-
prop.value,
|
|
79
|
-
]));
|
|
676
|
+
const given = appendedFields(item, struct, listName);
|
|
80
677
|
const values = [];
|
|
81
678
|
for (const field of struct.fields) {
|
|
82
|
-
const valueNode =
|
|
83
|
-
if (
|
|
84
|
-
values.push(field
|
|
85
|
-
? { field, text: { parts: [] } }
|
|
86
|
-
: {
|
|
87
|
-
field,
|
|
88
|
-
value: {
|
|
89
|
-
kind: 'number',
|
|
90
|
-
value: 0,
|
|
91
|
-
type: field.kind === 'float' ? FLOAT : INT,
|
|
92
|
-
},
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
else if (field.kind === 'string') {
|
|
96
|
-
const text = lowerText(valueNode, env);
|
|
97
|
-
checkConstantFits(text, `field "${field.key}" of list state "${listState.name}"`, env);
|
|
98
|
-
values.push({ field, text });
|
|
679
|
+
const valueNode = given.get(field.key);
|
|
680
|
+
if (valueNode) {
|
|
681
|
+
values.push(itemValue(field, valueNode, listState, environment));
|
|
99
682
|
}
|
|
100
683
|
else {
|
|
101
|
-
|
|
102
|
-
field,
|
|
103
|
-
value: storeValue(lowerExpr(valueNode, env), field.kind),
|
|
104
|
-
});
|
|
684
|
+
field.optional = true;
|
|
105
685
|
}
|
|
106
686
|
}
|
|
107
687
|
statements.push({ kind: 'appendItem', list: listState, values });
|
|
108
688
|
}
|
|
109
689
|
return statements;
|
|
110
690
|
}
|
|
691
|
+
// filter((_, i) => i !== n) removes item n; other filters and sorts change the rows in place.
|
|
692
|
+
const chain = listChainOf(nextList);
|
|
693
|
+
if (chain?.base.type === 'Identifier' && chain.base.name === listName) {
|
|
694
|
+
const [step] = chain.steps;
|
|
695
|
+
const index = chain.steps.length === 1 && step.kind === 'filter'
|
|
696
|
+
? filteredIndex(itemCallback(step.callback, step.what))
|
|
697
|
+
: null;
|
|
698
|
+
if (index) {
|
|
699
|
+
return [
|
|
700
|
+
{
|
|
701
|
+
kind: 'removeItem',
|
|
702
|
+
list: listState,
|
|
703
|
+
index: rowIndexOf(index, listName, environment),
|
|
704
|
+
negative: 'none',
|
|
705
|
+
},
|
|
706
|
+
];
|
|
707
|
+
}
|
|
708
|
+
return lowerListOrder(listState, listName, chain, environment);
|
|
709
|
+
}
|
|
710
|
+
// toSpliced(n, 1) removes item n, counting a negative n back from the end.
|
|
711
|
+
const splicedArguments = listCall(nextList, listName, 'toSpliced');
|
|
712
|
+
if (splicedArguments) {
|
|
713
|
+
const [start, count] = splicedArguments;
|
|
714
|
+
if (splicedArguments.length !== 2 ||
|
|
715
|
+
start.type === 'SpreadElement' ||
|
|
716
|
+
staticInt(count, environment) !== 1) {
|
|
717
|
+
throw aotError(`AOT: only ${listName}.toSpliced(n, 1) is supported on a list`, 'it removes item n.');
|
|
718
|
+
}
|
|
719
|
+
return [
|
|
720
|
+
{
|
|
721
|
+
kind: 'removeItem',
|
|
722
|
+
list: listState,
|
|
723
|
+
index: rowIndexOf(start, listName, environment),
|
|
724
|
+
negative: 'spliced',
|
|
725
|
+
},
|
|
726
|
+
];
|
|
727
|
+
}
|
|
728
|
+
// map(item => …) and with(n, item) set items in place.
|
|
729
|
+
const mapArguments = listCall(nextList, listName, 'map');
|
|
730
|
+
if (mapArguments) {
|
|
731
|
+
return lowerItemsMap(listState, listName, mapArguments[0], environment);
|
|
732
|
+
}
|
|
733
|
+
const withArguments = listCall(nextList, listName, 'with');
|
|
734
|
+
if (withArguments) {
|
|
735
|
+
return lowerItemsWith(listState, listName, withArguments, environment);
|
|
736
|
+
}
|
|
111
737
|
// slice(0, end) keeps the first items by JS rules: a negative end counts back, a large or missing one keeps all.
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
throw aotError(`AOT: only ${listState.name}.slice(0, end) is supported on a list`, `a list is a fixed C array and a count, so a slice can only drop items from the end — ` +
|
|
119
|
-
`e.g. ${listState.name}.slice(0, -1) drops the last one.`);
|
|
738
|
+
const sliceArguments = listCall(nextList, listName, 'slice');
|
|
739
|
+
if (sliceArguments) {
|
|
740
|
+
const [start, end] = sliceArguments;
|
|
741
|
+
if (start && staticInt(start, environment) !== 0) {
|
|
742
|
+
throw aotError(`AOT: only ${listName}.slice(0, end) is supported on a list`, `a list is a fixed pool and a count, so a slice can only drop items from the end — ` +
|
|
743
|
+
`e.g. ${listName}.slice(0, -1) drops the last one.`);
|
|
120
744
|
}
|
|
121
745
|
if (!end)
|
|
122
746
|
return [];
|
|
123
747
|
// Settle a constant end here, clamped to ±capacity (past which nothing changes), so it needs no 64-bit math.
|
|
124
|
-
const staticEnd = staticInt(end,
|
|
748
|
+
const staticEnd = staticInt(end, environment);
|
|
125
749
|
if (staticEnd !== null) {
|
|
126
750
|
const clampedEnd = Math.max(-capacity, Math.min(capacity, staticEnd));
|
|
127
751
|
if (clampedEnd === -1) {
|
|
@@ -138,50 +762,78 @@ function lowerListOp(listState, nextList, env) {
|
|
|
138
762
|
},
|
|
139
763
|
];
|
|
140
764
|
}
|
|
141
|
-
// A runtime end
|
|
765
|
+
// A runtime end applies the same JS rules when it runs.
|
|
142
766
|
return [
|
|
143
|
-
{
|
|
767
|
+
{
|
|
768
|
+
kind: 'sliceItems',
|
|
769
|
+
list: listState,
|
|
770
|
+
end: asInt(lowerExpr(end, environment)),
|
|
771
|
+
},
|
|
144
772
|
];
|
|
145
773
|
}
|
|
146
|
-
throw
|
|
147
|
-
|
|
774
|
+
throw aotError(`AOT: unsupported list operation on "${listName}"`, `use [...${listName}, item], ${listName}.slice(0, n), [], ${listName}.filter(item => …), ` +
|
|
775
|
+
`${listName}.toSorted((a, b) => …), ${listName}.toSpliced(n, 1), ${listName}.map(item => …) or ` +
|
|
776
|
+
`${listName}.with(n, item).`);
|
|
148
777
|
}
|
|
149
778
|
/**
|
|
150
|
-
*
|
|
779
|
+
* Lowers filters and sorts as a list's next value: each changes the rows in place, a filter dropping the rows it
|
|
780
|
+
* doesn't keep and a sort moving them, equal ones kept in order.
|
|
151
781
|
*
|
|
152
|
-
* @param
|
|
782
|
+
* @param listState The list.
|
|
783
|
+
* @param listName What the setter's argument calls it.
|
|
784
|
+
* @param chain The filters and sorts.
|
|
785
|
+
* @param environment The expression environment.
|
|
786
|
+
*
|
|
787
|
+
* @returns The statements.
|
|
788
|
+
*/
|
|
789
|
+
function lowerListOrder(listState, listName, chain, environment) {
|
|
790
|
+
// The rows move as the steps run, so a read of another row could see a different one.
|
|
791
|
+
for (const step of chain.steps) {
|
|
792
|
+
if (readsRowsOf(step.callback, listState, listName, environment)) {
|
|
793
|
+
throw aotError(`AOT: ${step.what}'s function can't read other items of ${listName}`, 'its items move as it runs, so a read of another one could see a different item. Read it into a ' +
|
|
794
|
+
`const before the setter: const first = ${listName}[0].n.`);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
return orderStatements(listState, chain.steps.map(step => ({ ...step, environment })), {
|
|
798
|
+
itemAt: position => ({
|
|
799
|
+
name: `${listName}[]`,
|
|
800
|
+
struct: listState.struct,
|
|
801
|
+
list: listState,
|
|
802
|
+
index: { kind: 'local', local: position, type: INT },
|
|
803
|
+
}),
|
|
804
|
+
listName,
|
|
805
|
+
source: listState,
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Records a value written to a whole-number state, ref or `let` slot, whose kind came from its initial value:
|
|
810
|
+
* from every such value the typing pass infers the slots that hold 64 bits.
|
|
153
811
|
*
|
|
154
|
-
* @
|
|
812
|
+
* @param value The value's source.
|
|
813
|
+
* @param slotName The slot's name.
|
|
814
|
+
* @param target The state or ref, or the `let` local.
|
|
815
|
+
* @param environment The expression environment.
|
|
155
816
|
*/
|
|
156
|
-
function
|
|
157
|
-
|
|
817
|
+
function recordStore(value, slotName, target, environment) {
|
|
818
|
+
environment.stores.push({
|
|
819
|
+
slot: slotName,
|
|
820
|
+
value,
|
|
821
|
+
math64: environment.math64,
|
|
822
|
+
...('kind' in target ? { target } : { local: target }),
|
|
823
|
+
});
|
|
158
824
|
}
|
|
159
825
|
/**
|
|
160
|
-
* Checks a value written to a numeric
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
* @param lowered The value: its source, and its type.
|
|
167
|
-
* @param slotType The slot's C kind.
|
|
168
|
-
* @param isBool The slot holds a boolean.
|
|
169
|
-
* @param widened What the slot holds, if it was widened to 64 bits.
|
|
170
|
-
* @param slotCName The slot's C name, for env.stores.
|
|
826
|
+
* Checks a value written to a numeric slot, once both are typed. A timestamp cannot go into a float or boolean
|
|
827
|
+
* slot (a 64-bit constant can go into a float one), and a 64-bit slot takes no floats.
|
|
828
|
+
*
|
|
829
|
+
* @param value The typed value.
|
|
830
|
+
* @param slot The slot.
|
|
171
831
|
* @param slotDescription The slot, for the message.
|
|
172
|
-
* @param env The expression environment.
|
|
173
832
|
*/
|
|
174
|
-
function
|
|
175
|
-
const
|
|
176
|
-
if ((slotType === 'int' && !isBool) || widened === 'number') {
|
|
177
|
-
env.stores.push({
|
|
178
|
-
slot: slotCName,
|
|
179
|
-
value: lowered.source,
|
|
180
|
-
math64: Boolean(env.math64),
|
|
181
|
-
});
|
|
182
|
-
}
|
|
833
|
+
function checkStored(value, slot, slotDescription) {
|
|
834
|
+
const { slotType, isBoolean } = slot;
|
|
183
835
|
if (value.type.kind === 'int64' && slotType !== 'i64') {
|
|
184
|
-
if (slotType === 'int' && !
|
|
836
|
+
if (slotType === 'int' && !isBoolean)
|
|
185
837
|
return;
|
|
186
838
|
if (isConvertible64(value.type) && slotType === 'float')
|
|
187
839
|
return;
|
|
@@ -192,25 +844,46 @@ function storeCheck(lowered, slotType, isBool, widened, slotCName, slotDescripti
|
|
|
192
844
|
}
|
|
193
845
|
}
|
|
194
846
|
/**
|
|
195
|
-
*
|
|
196
|
-
*
|
|
847
|
+
* The environment a value stored in a slot is lowered in: a 64-bit slot takes int `+ - *` worked out in 64
|
|
848
|
+
* bits.
|
|
197
849
|
*
|
|
198
|
-
* @param
|
|
850
|
+
* @param environment The expression environment.
|
|
851
|
+
* @param is64Bit Whether the slot holds 64 bits, asked once its width is known.
|
|
852
|
+
*
|
|
853
|
+
* @returns The value's environment.
|
|
854
|
+
*/
|
|
855
|
+
function storeEnvironment(environment, is64Bit) {
|
|
856
|
+
const outer = environment.math64;
|
|
857
|
+
return { ...environment, math64: () => is64Bit() || Boolean(outer?.()) };
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* A typed value for an int destination. A float goes through a checked conversion: a plain one is undefined
|
|
861
|
+
* for NaN or a value past the int range.
|
|
862
|
+
*
|
|
863
|
+
* @param value The typed value.
|
|
199
864
|
*
|
|
200
865
|
* @returns The value as an int.
|
|
201
866
|
*/
|
|
202
|
-
const
|
|
867
|
+
const typedAsInt = (value) => value.type.kind === 'float'
|
|
203
868
|
? { kind: 'toInt', operand: value, type: INT }
|
|
204
869
|
: value;
|
|
205
870
|
/**
|
|
206
|
-
* `value` for
|
|
871
|
+
* `value` for an int destination (see typedAsInt).
|
|
872
|
+
*
|
|
873
|
+
* @param value The lowered value.
|
|
874
|
+
*
|
|
875
|
+
* @returns The value as an int.
|
|
876
|
+
*/
|
|
877
|
+
const asInt = (value) => typedLater('number', () => typedAsInt(value), [value]);
|
|
878
|
+
/**
|
|
879
|
+
* `value` for a slot: an int slot takes a float the way asInt does.
|
|
207
880
|
*
|
|
208
881
|
* @param value The lowered value.
|
|
209
|
-
* @param slotType The slot's
|
|
882
|
+
* @param slotType The slot's kind, asked once it is known.
|
|
210
883
|
*
|
|
211
884
|
* @returns The value the slot stores.
|
|
212
885
|
*/
|
|
213
|
-
const storeValue = (value, slotType) => slotType === 'int' ?
|
|
886
|
+
const storeValue = (value, slotType) => typedLater(shapeOf(value), () => (slotType() === 'int' ? typedAsInt(value) : value), [value]);
|
|
214
887
|
/**
|
|
215
888
|
* A read of a ref's current value.
|
|
216
889
|
*
|
|
@@ -224,21 +897,20 @@ const refRead = (ref) => ({
|
|
|
224
897
|
type: refType(ref),
|
|
225
898
|
});
|
|
226
899
|
/**
|
|
227
|
-
* Refuses a constant string too long for the buffer
|
|
900
|
+
* Refuses a constant string too long for the buffer a write is built in, which would cut it short. A string
|
|
228
901
|
* built at run time is checked when it is written instead.
|
|
229
902
|
*
|
|
230
903
|
* @param text The text written.
|
|
231
904
|
* @param what What it is written into, for the error.
|
|
232
|
-
* @param env The expression environment.
|
|
233
905
|
*/
|
|
234
|
-
function checkConstantFits(text, what
|
|
906
|
+
function checkConstantFits(text, what) {
|
|
235
907
|
const constant = constantText(text);
|
|
236
908
|
if (constant === null) {
|
|
237
909
|
return;
|
|
238
910
|
}
|
|
239
911
|
const bytes = Buffer.byteLength(constant, 'utf8');
|
|
240
|
-
if (bytes
|
|
241
|
-
throw aotError(`AOT: ${what} is set to a ${bytes}-byte string, but a
|
|
912
|
+
if (bytes > ENGINE_STRING_MAX.ER_TEXT_MAX) {
|
|
913
|
+
throw aotError(`AOT: ${what} is set to a ${bytes}-byte string, but a write holds ${ENGINE_STRING_MAX.ER_TEXT_MAX} bytes (ER_TEXT_MAX)`, 'shorten the string: a write is built in a buffer that ER_TEXT_MAX in er_scene.h sizes.');
|
|
242
914
|
}
|
|
243
915
|
}
|
|
244
916
|
/**
|
|
@@ -247,45 +919,147 @@ function checkConstantFits(text, what, env) {
|
|
|
247
919
|
*
|
|
248
920
|
* @param scalarState The state slot.
|
|
249
921
|
* @param valueNode The value.
|
|
250
|
-
* @param
|
|
922
|
+
* @param environment The expression environment.
|
|
251
923
|
*
|
|
252
924
|
* @returns The write.
|
|
253
925
|
*/
|
|
254
|
-
function lowerScalarSet(scalarState, valueNode,
|
|
255
|
-
if (scalarState.
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
926
|
+
function lowerScalarSet(scalarState, valueNode, environment) {
|
|
927
|
+
if (scalarState.slotKind !== 'string') {
|
|
928
|
+
const lowered = lowerSource(valueNode, storeEnvironment(environment, () => is64BitSlot(scalarState)));
|
|
929
|
+
const value = lowered.expression;
|
|
930
|
+
if ((scalarState.slotKind === 'int' && !scalarState.isBoolean) ||
|
|
931
|
+
scalarState.widened === 'number') {
|
|
932
|
+
recordStore(lowered.source, scalarState.slotName, scalarState, environment);
|
|
933
|
+
}
|
|
934
|
+
whenTyped(() => checkStored(value, { slotType: scalarState.slotKind, isBoolean: scalarState.isBoolean }, `state "${scalarState.name}"`));
|
|
260
935
|
return {
|
|
261
936
|
kind: 'setState',
|
|
262
937
|
state: scalarState,
|
|
263
|
-
value: storeValue(value, scalarState.
|
|
938
|
+
value: storeValue(value, () => scalarState.slotKind),
|
|
264
939
|
};
|
|
265
940
|
}
|
|
266
|
-
const text = lowerText(valueNode,
|
|
267
|
-
checkConstantFits(text, `state "${scalarState.name}"
|
|
941
|
+
const text = lowerText(valueNode, environment);
|
|
942
|
+
checkConstantFits(text, `state "${scalarState.name}"`);
|
|
268
943
|
return {
|
|
269
944
|
kind: 'setStateText',
|
|
270
945
|
state: scalarState,
|
|
271
946
|
text,
|
|
272
947
|
};
|
|
273
948
|
}
|
|
949
|
+
/** How an object setter's writes are lowered. */
|
|
950
|
+
const RECORD_LOWERING = {
|
|
951
|
+
field: lowerScalarSet,
|
|
952
|
+
test: (node, environment) => lowerExprWide(node, environment),
|
|
953
|
+
};
|
|
954
|
+
/**
|
|
955
|
+
* Works out a write to a value ref, `ref.current = …` or a compound assignment, once the ref and the value are
|
|
956
|
+
* typed. It does not trigger a re-render.
|
|
957
|
+
*
|
|
958
|
+
* @param expression The assignment.
|
|
959
|
+
* @param ref The ref.
|
|
960
|
+
* @param loweredValue The right side: its source, and the typed value.
|
|
961
|
+
* @param environment The expression environment.
|
|
962
|
+
*
|
|
963
|
+
* @returns The write's operator and value.
|
|
964
|
+
*/
|
|
965
|
+
function typedRefWrite(expression, ref, loweredValue, environment) {
|
|
966
|
+
const valueExpression = loweredValue.expression;
|
|
967
|
+
const refHoldsTime = isTime(refType(ref));
|
|
968
|
+
if (expression.operator === '/=' &&
|
|
969
|
+
(refHoldsTime || isTime64(valueExpression))) {
|
|
970
|
+
throw aotError('AOT: `/=` on a 64-bit time value is not supported', 'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.');
|
|
971
|
+
}
|
|
972
|
+
// A 64-bit `%=` keeps its constant divisor.
|
|
973
|
+
const wideModuloDivisor = expression.operator === '%=' && (refHoldsTime || isTime64(valueExpression))
|
|
974
|
+
? constDivisor(expression.right, environment)
|
|
975
|
+
: null;
|
|
976
|
+
checkStored(valueExpression, { slotType: ref.slotKind, isBoolean: false }, `ref "${expression.left.object.name}"`);
|
|
977
|
+
const stored = (value) => ref.slotKind === 'int' ? typedAsInt(value) : value;
|
|
978
|
+
// Whole-ref `+= -= *=`, float `/=` and float `%=` are the binary op, to share its checked and float math.
|
|
979
|
+
const isWholeRef = ref.slotKind === 'int' || ref.slotKind === 'i64';
|
|
980
|
+
const binaryOperation = { '+=': '+', '-=': '-', '*=': '*' }[expression.operator];
|
|
981
|
+
const isFloatModulo = expression.operator === '%=' &&
|
|
982
|
+
(ref.slotKind === 'float' || valueExpression.type.kind === 'float');
|
|
983
|
+
if ((isWholeRef &&
|
|
984
|
+
(binaryOperation ||
|
|
985
|
+
(expression.operator === '/=' &&
|
|
986
|
+
valueExpression.type.kind === 'float'))) ||
|
|
987
|
+
isFloatModulo) {
|
|
988
|
+
const resultExpression = typeSource(binarySource({
|
|
989
|
+
type: 'BinaryExpression',
|
|
990
|
+
operator: binaryOperation ?? expression.operator.slice(0, -1),
|
|
991
|
+
left: expression.left,
|
|
992
|
+
right: expression.right,
|
|
993
|
+
loc: expression.loc,
|
|
994
|
+
}, { kind: 'ref', ref, location: expression.left.loc?.start }, loweredValue.source, environment), ref.slotKind === 'i64' || Boolean(environment.math64?.()));
|
|
995
|
+
return { operator: '=', value: stored(resultExpression) };
|
|
996
|
+
}
|
|
997
|
+
// Whole-number `/=` and `%=` use the checked helpers for JS's answer, in 64 bits on a 64-bit ref that holds no
|
|
998
|
+
// time; a constant divisor other than 0 or -1 needs no check.
|
|
999
|
+
const isWholeValue = isIntSlot(valueExpression.type) ||
|
|
1000
|
+
(valueExpression.type.kind === 'int64' && !isTime64(valueExpression));
|
|
1001
|
+
const refBits = ref.slotKind === 'i64' ? 64 : 32;
|
|
1002
|
+
if (((ref.slotKind === 'int' && isIntSlot(valueExpression.type)) ||
|
|
1003
|
+
(ref.slotKind === 'i64' && !refHoldsTime && isWholeValue)) &&
|
|
1004
|
+
(expression.operator === '/=' || expression.operator === '%=')) {
|
|
1005
|
+
const staticDivisor = staticInt(expression.right, environment);
|
|
1006
|
+
if (expression.operator === '/=' &&
|
|
1007
|
+
(staticDivisor === null || staticDivisor === 0 || staticDivisor === -1)) {
|
|
1008
|
+
return {
|
|
1009
|
+
operator: '=',
|
|
1010
|
+
value: {
|
|
1011
|
+
kind: 'helper',
|
|
1012
|
+
helper: 'div',
|
|
1013
|
+
bits: refBits,
|
|
1014
|
+
callArguments: [refRead(ref), valueExpression],
|
|
1015
|
+
type: refType(ref),
|
|
1016
|
+
},
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
if (expression.operator === '%=' &&
|
|
1020
|
+
(staticDivisor === 0 || staticDivisor === -1)) {
|
|
1021
|
+
return { operator: '=', value: ZERO };
|
|
1022
|
+
}
|
|
1023
|
+
if (expression.operator === '%=' && staticDivisor === null) {
|
|
1024
|
+
return {
|
|
1025
|
+
operator: '=',
|
|
1026
|
+
value: {
|
|
1027
|
+
kind: 'helper',
|
|
1028
|
+
helper: 'mod',
|
|
1029
|
+
bits: refBits,
|
|
1030
|
+
callArguments: [refRead(ref), valueExpression],
|
|
1031
|
+
type: refType(ref),
|
|
1032
|
+
},
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
// A 64-bit `%=` by 0 or ±1 stores 0: no remainder, JS's NaN as 0, and no overflow on INT64_MIN % -1.
|
|
1037
|
+
if (wideModuloDivisor === 0 ||
|
|
1038
|
+
wideModuloDivisor === 1 ||
|
|
1039
|
+
wideModuloDivisor === -1) {
|
|
1040
|
+
return { operator: '=', value: ZERO };
|
|
1041
|
+
}
|
|
1042
|
+
// Everything else is a plain assignment or compound assignment.
|
|
1043
|
+
return {
|
|
1044
|
+
operator: expression.operator,
|
|
1045
|
+
value: expression.operator === '=' ? stored(valueExpression) : valueExpression,
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
274
1048
|
/**
|
|
275
1049
|
* Resolves `node` to its ref when it is `<ref>.current` member access on a known value ref.
|
|
276
1050
|
*
|
|
277
1051
|
* @param node An assignment or update target.
|
|
278
|
-
* @param
|
|
1052
|
+
* @param environment The expression environment.
|
|
279
1053
|
*
|
|
280
1054
|
* @returns The ref, marked used, or null when the node is not such an access.
|
|
281
1055
|
*/
|
|
282
|
-
function refTarget(node,
|
|
1056
|
+
function refTarget(node, environment) {
|
|
283
1057
|
if (node?.type === 'MemberExpression' &&
|
|
284
1058
|
!node.computed &&
|
|
285
1059
|
node.object.type === 'Identifier' &&
|
|
286
1060
|
node.property.name === 'current' &&
|
|
287
|
-
|
|
288
|
-
const ref =
|
|
1061
|
+
environment.refs?.has(node.object.name)) {
|
|
1062
|
+
const ref = environment.refs.get(node.object.name);
|
|
289
1063
|
ref.used = true;
|
|
290
1064
|
return ref;
|
|
291
1065
|
}
|
|
@@ -298,12 +1072,12 @@ function refTarget(node, env) {
|
|
|
298
1072
|
* be unique in the handler block they are written into.
|
|
299
1073
|
*
|
|
300
1074
|
* @param shapeNode The shape's object literal.
|
|
301
|
-
* @param
|
|
1075
|
+
* @param environment The expression environment.
|
|
302
1076
|
* @param tag Names the shape's locals.
|
|
303
1077
|
*
|
|
304
1078
|
* @returns The shape's tape slots, the locals they need, and its paint.
|
|
305
1079
|
*/
|
|
306
|
-
function imperativeShape(shapeNode,
|
|
1080
|
+
function imperativeShape(shapeNode, environment, tag) {
|
|
307
1081
|
// Index the shape's properties by name.
|
|
308
1082
|
if (shapeNode?.type !== 'ObjectExpression') {
|
|
309
1083
|
throw new Error('AOT: each updateVector shape must be an object literal');
|
|
@@ -321,7 +1095,7 @@ function imperativeShape(shapeNode, env, tag) {
|
|
|
321
1095
|
throw new Error(`AOT: updateVector "${key}" must be an array literal`);
|
|
322
1096
|
}
|
|
323
1097
|
const elements = props[key].elements;
|
|
324
|
-
const shapeHint = `${key}: ${
|
|
1098
|
+
const shapeHint = `${key}: ${UPDATE_VECTOR_ARGUMENTS[key]}.`;
|
|
325
1099
|
if (elements.length < required) {
|
|
326
1100
|
throw aotError(`AOT: updateVector "${key}" needs ${required} numbers (got ${elements.length})`, shapeHint);
|
|
327
1101
|
}
|
|
@@ -330,7 +1104,7 @@ function imperativeShape(shapeNode, env, tag) {
|
|
|
330
1104
|
if (!valueNode) {
|
|
331
1105
|
throw aotError(`AOT: updateVector "${key}" has an empty slot at position ${position}`, shapeHint);
|
|
332
1106
|
}
|
|
333
|
-
return { kind: 'float', value: lowerExpr(valueNode,
|
|
1107
|
+
return { kind: 'float', value: lowerExpr(valueNode, environment) };
|
|
334
1108
|
});
|
|
335
1109
|
};
|
|
336
1110
|
let geometry;
|
|
@@ -352,7 +1126,7 @@ function imperativeShape(shapeNode, env, tag) {
|
|
|
352
1126
|
}
|
|
353
1127
|
else if (props.path) {
|
|
354
1128
|
geometry = {
|
|
355
|
-
entries: parsePath(String(evalStatic(props.path,
|
|
1129
|
+
entries: parsePath(String(evalStatic(props.path, environment.constants ?? {}))).map((value) => checkedTapeNumber(value)),
|
|
356
1130
|
locals: [],
|
|
357
1131
|
};
|
|
358
1132
|
}
|
|
@@ -364,7 +1138,7 @@ function imperativeShape(shapeNode, env, tag) {
|
|
|
364
1138
|
if (props[key] == null)
|
|
365
1139
|
return fallback;
|
|
366
1140
|
try {
|
|
367
|
-
return evalStatic(props[key],
|
|
1141
|
+
return evalStatic(props[key], environment.constants ?? {});
|
|
368
1142
|
}
|
|
369
1143
|
catch {
|
|
370
1144
|
throw new Error(`AOT: updateVector paint "${key}" must be static`);
|
|
@@ -374,7 +1148,7 @@ function imperativeShape(shapeNode, env, tag) {
|
|
|
374
1148
|
parseColor(paintValue('fill', 'none')),
|
|
375
1149
|
parseColor(paintValue('stroke', 'none')),
|
|
376
1150
|
svgNum(paintValue('strokeWidth', 1), 1),
|
|
377
|
-
svgNum(paintValue('miter',
|
|
1151
|
+
svgNum(paintValue('miter', DEFAULT_MITER_LIMIT), DEFAULT_MITER_LIMIT),
|
|
378
1152
|
CAP_MAP[paintValue('cap', 'butt')] ?? 0,
|
|
379
1153
|
JOIN_MAP[paintValue('join', 'miter')] ?? 0,
|
|
380
1154
|
paintValue('fillRule', 'nonzero') === 'evenodd' ? 1 : 0,
|
|
@@ -383,58 +1157,60 @@ function imperativeShape(shapeNode, env, tag) {
|
|
|
383
1157
|
}
|
|
384
1158
|
/**
|
|
385
1159
|
* Lowers `updateVector(nodeRef, shapes, [x,y,w,h]?)`: fill a mutable op-tape, push it to the node, and
|
|
386
|
-
* (optionally) hint the dirty sub-rect — the imperative fast path (drag) that bypasses
|
|
387
|
-
* tables are declared
|
|
1160
|
+
* (optionally) hint the dirty sub-rect — the imperative fast path (drag) that bypasses the update. The call's
|
|
1161
|
+
* tables are declared here.
|
|
388
1162
|
*
|
|
389
|
-
* @param
|
|
390
|
-
* @param
|
|
391
|
-
* @param
|
|
1163
|
+
* @param expression The updateVector call.
|
|
1164
|
+
* @param environment The expression environment.
|
|
1165
|
+
* @param context The statement compiler's context.
|
|
392
1166
|
*
|
|
393
1167
|
* @returns The statement.
|
|
394
1168
|
*/
|
|
395
|
-
function lowerUpdateVector(
|
|
1169
|
+
function lowerUpdateVector(expression, environment, context) {
|
|
396
1170
|
// The first argument must be a node ref, and the second an array literal of shapes.
|
|
397
|
-
const
|
|
398
|
-
const [
|
|
399
|
-
const ref =
|
|
1171
|
+
const output = context.output;
|
|
1172
|
+
const [refArgument, shapesArgument, dirtyArgument] = expression.arguments;
|
|
1173
|
+
const ref = refArgument?.type === 'Identifier'
|
|
1174
|
+
? environment.refs?.get(refArgument.name)
|
|
1175
|
+
: null;
|
|
400
1176
|
if (ref?.kind !== 'node') {
|
|
401
1177
|
throw new Error('AOT: updateVector(ref, …) first arg must be a node ref (const r = useRef())');
|
|
402
1178
|
}
|
|
403
1179
|
ref.used = true;
|
|
404
|
-
if (
|
|
1180
|
+
if (shapesArgument?.type !== 'ArrayExpression') {
|
|
405
1181
|
throw new Error('AOT: updateVector(ref, shapes, …) shapes must be an array literal');
|
|
406
1182
|
}
|
|
407
1183
|
// Claim the id first so two updateVector calls in one handler get distinct locals, then lower each shape.
|
|
408
|
-
const vectorId =
|
|
1184
|
+
const vectorId = output.svgCount++;
|
|
409
1185
|
const update = {
|
|
410
1186
|
kind: 'updateVector',
|
|
411
1187
|
id: vectorId,
|
|
412
|
-
node: ref.
|
|
1188
|
+
node: ref.slotName,
|
|
413
1189
|
locals: [],
|
|
414
1190
|
tape: [],
|
|
415
1191
|
paints: [],
|
|
416
1192
|
dirty: null,
|
|
417
1193
|
};
|
|
418
|
-
for (const shapeNode of
|
|
419
|
-
const shape = imperativeShape(shapeNode,
|
|
1194
|
+
for (const shapeNode of shapesArgument.elements) {
|
|
1195
|
+
const shape = imperativeShape(shapeNode, environment, `uv${vectorId}_${update.paints.length}`);
|
|
420
1196
|
update.locals.push(...shape.locals);
|
|
421
|
-
update.tape.push({ kind: 'op',
|
|
1197
|
+
update.tape.push({ kind: 'op', operation: 'ER_VECTOR_OP_SHAPE' }, checkedTapeNumber(update.paints.length), ...shape.entries);
|
|
422
1198
|
update.paints.push(shape.paint);
|
|
423
1199
|
}
|
|
424
|
-
// Declare the op-tape and its paint table
|
|
1200
|
+
// Declare the op-tape and its paint table.
|
|
425
1201
|
checkVectorPaints(update.paints);
|
|
426
|
-
|
|
427
|
-
out.vectors.push({ kind: 'updateVector', update });
|
|
1202
|
+
output.vectors.push({ kind: 'updateVector', update });
|
|
428
1203
|
// Hint the dirty sub-rect when the call gives one.
|
|
429
|
-
if (
|
|
430
|
-
if (
|
|
1204
|
+
if (dirtyArgument) {
|
|
1205
|
+
if (dirtyArgument.type !== 'ArrayExpression' ||
|
|
1206
|
+
dirtyArgument.elements.length < 4) {
|
|
431
1207
|
throw new Error('AOT: updateVector dirtyRect must be a [x, y, w, h] array literal');
|
|
432
1208
|
}
|
|
433
|
-
update.dirty =
|
|
1209
|
+
update.dirty = dirtyArgument.elements.slice(0, 4).map((edgeNode, edge) => {
|
|
434
1210
|
if (!edgeNode) {
|
|
435
1211
|
throw aotError(`AOT: updateVector dirtyRect has an empty slot at position ${edge}`);
|
|
436
1212
|
}
|
|
437
|
-
return lowerExpr(edgeNode,
|
|
1213
|
+
return lowerExpr(edgeNode, environment);
|
|
438
1214
|
});
|
|
439
1215
|
}
|
|
440
1216
|
return update;
|
|
@@ -442,448 +1218,894 @@ function lowerUpdateVector(expr, env, ctx) {
|
|
|
442
1218
|
/**
|
|
443
1219
|
* Lowers setInterval/setTimeout(cb, ms) to a timer, and registers cb as a timer function of its own.
|
|
444
1220
|
*
|
|
445
|
-
* @param
|
|
446
|
-
* @param
|
|
1221
|
+
* @param expression The setInterval / setTimeout call.
|
|
1222
|
+
* @param environment The expression environment.
|
|
447
1223
|
* @param state The component's state table.
|
|
448
|
-
* @param
|
|
1224
|
+
* @param context The statement compiler's context.
|
|
449
1225
|
*
|
|
450
1226
|
* @returns The timer.
|
|
451
1227
|
*/
|
|
452
|
-
function lowerTimer(
|
|
453
|
-
const
|
|
454
|
-
if (!isFn(
|
|
1228
|
+
function lowerTimer(expression, environment, state, context) {
|
|
1229
|
+
const callback = expression.arguments[0];
|
|
1230
|
+
if (!isFn(callback)) {
|
|
455
1231
|
throw aotError('AOT: a setInterval/setTimeout callback must be an inline function', 'pass an inline arrow, e.g. setInterval(() => setTick((t) => t + 1), 1000).');
|
|
456
1232
|
}
|
|
457
1233
|
// Any delay is accepted here; the printer converts a timestamp or float one the way Flow A's setTimeout does.
|
|
458
|
-
const delay =
|
|
459
|
-
? lowerExprWide(
|
|
1234
|
+
const delay = expression.arguments[1]
|
|
1235
|
+
? lowerExprWide(expression.arguments[1], environment)
|
|
460
1236
|
: null;
|
|
461
|
-
const isRepeating =
|
|
1237
|
+
const isRepeating = expression.callee.name === 'setInterval';
|
|
462
1238
|
// Reserve the timer's slot before compiling its body, which may add timers of its own.
|
|
463
|
-
const slot =
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
return { delay, isRepeating, fn: timerFnName };
|
|
1239
|
+
const slot = context.output.timerFunctions.length;
|
|
1240
|
+
const timerFunctionName = `timer_${slot}`;
|
|
1241
|
+
context.output.timerFunctions.push({ name: timerFunctionName, callback: null });
|
|
1242
|
+
context.output.timerFunctions[slot].callback = lowerHandler(callback, environment, state, context.output);
|
|
1243
|
+
return { delay, isRepeating, functionName: timerFunctionName };
|
|
469
1244
|
}
|
|
470
1245
|
/**
|
|
471
|
-
*
|
|
472
|
-
*
|
|
1246
|
+
* Checks a setter called inside a loop. One for a list the loop visits is refused, as the loop would see the rows
|
|
1247
|
+
* it changes, where React's loops over the list as it was. So is a setter given a value that reads its own state:
|
|
1248
|
+
* React's reads the value from before the loop each time, so only the last call counts, where Flow B's would see
|
|
1249
|
+
* each call's.
|
|
1250
|
+
*
|
|
1251
|
+
* @param setter The setter's name.
|
|
1252
|
+
* @param target What it sets.
|
|
1253
|
+
* @param argument What it is given.
|
|
1254
|
+
* @param environment The expression environment.
|
|
1255
|
+
* @param loops The lists each loop around it visits or is bounded by.
|
|
1256
|
+
*/
|
|
1257
|
+
function checkLoopSetter(setter, target, argument, environment, loops) {
|
|
1258
|
+
if (target.kind === 'list' && loops.some(lists => lists.includes(target))) {
|
|
1259
|
+
throw aotError(`AOT: ${setter} can't change ${target.name} inside a loop over it`, 'the loop would see the rows it changes, where React loops over the list as it was. Work out what to ' +
|
|
1260
|
+
'change in the loop, into a let, and set the list after it.');
|
|
1261
|
+
}
|
|
1262
|
+
if (!argument || isFn(argument))
|
|
1263
|
+
return;
|
|
1264
|
+
const names = new Set([target.name]);
|
|
1265
|
+
for (const [name, record] of environment.state) {
|
|
1266
|
+
if (record === target)
|
|
1267
|
+
names.add(name);
|
|
1268
|
+
}
|
|
1269
|
+
if (mentions(argument, names)) {
|
|
1270
|
+
throw aotError(`AOT: ${setter}(…) inside a loop must take an updater to read ${target.name}`, `React reads ${target.name} from before the loop each time, so only the last call would count. Write ` +
|
|
1271
|
+
`${setter}(previous => …), or work the value out in a let and set it after the loop.`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Lowers `x = …`, `x += …` or `x++` on a `let` local. A whole-number `let` given a fraction or a timestamp is
|
|
1276
|
+
* widened to hold it, once every store is lowered; a boolean or a string one holds only those.
|
|
1277
|
+
*
|
|
1278
|
+
* @param expression The assignment or update.
|
|
1279
|
+
* @param target The local's name.
|
|
1280
|
+
* @param local The local.
|
|
1281
|
+
* @param environment The expression environment.
|
|
1282
|
+
*
|
|
1283
|
+
* @returns The statement.
|
|
1284
|
+
*/
|
|
1285
|
+
function lowerLocalAssign(expression, target, local, environment) {
|
|
1286
|
+
const { name } = target;
|
|
1287
|
+
if (!local.assignable) {
|
|
1288
|
+
if (local.list) {
|
|
1289
|
+
throw aotError(`AOT: "${name}" is a list's item, which can't be set`, `copy what you need into a let: let value = ${name}.value;`);
|
|
1290
|
+
}
|
|
1291
|
+
throw aotError(local.counter
|
|
1292
|
+
? `AOT: "${name}" is a loop's counter, which only the loop sets`
|
|
1293
|
+
: `AOT: "${name}" can't be assigned: only a \`let\` can`, local.counter
|
|
1294
|
+
? `copy it into a let of its own first: let at = ${name};`
|
|
1295
|
+
: `declare it with let to change it: let ${name} = …;`);
|
|
1296
|
+
}
|
|
1297
|
+
// What it is set to, as one expression: `x += e` is `x + e`, and `x++` is `x + 1`.
|
|
1298
|
+
const { loc } = expression;
|
|
1299
|
+
let valueNode;
|
|
1300
|
+
if (expression.type === 'UpdateExpression') {
|
|
1301
|
+
valueNode = {
|
|
1302
|
+
type: 'BinaryExpression',
|
|
1303
|
+
operator: expression.operator === '++' ? '+' : '-',
|
|
1304
|
+
left: target,
|
|
1305
|
+
right: { type: 'NumericLiteral', value: 1 },
|
|
1306
|
+
loc,
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
else if (expression.operator === '=') {
|
|
1310
|
+
valueNode = expression.right;
|
|
1311
|
+
}
|
|
1312
|
+
else {
|
|
1313
|
+
const operator = expression.operator.slice(0, -1);
|
|
1314
|
+
valueNode =
|
|
1315
|
+
operator === '&&' || operator === '||' || operator === '??'
|
|
1316
|
+
? {
|
|
1317
|
+
type: 'LogicalExpression',
|
|
1318
|
+
operator,
|
|
1319
|
+
left: target,
|
|
1320
|
+
right: expression.right,
|
|
1321
|
+
loc,
|
|
1322
|
+
}
|
|
1323
|
+
: {
|
|
1324
|
+
type: 'BinaryExpression',
|
|
1325
|
+
operator: operator,
|
|
1326
|
+
left: target,
|
|
1327
|
+
right: expression.right,
|
|
1328
|
+
loc,
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
const holds = (what) => aotError(`AOT: "${name}" holds ${what}, so it can only be set to ${what === 'a string' ? 'strings' : what === 'a boolean' ? 'booleans' : 'numbers'}`, `a let keeps the kind of value it starts with; declare another let for a value of another kind.`);
|
|
1332
|
+
const localName = local.name;
|
|
1333
|
+
// A string is built in the local's buffer, which may be read to build it.
|
|
1334
|
+
if (localShape(local) === 'string') {
|
|
1335
|
+
if (buildsText(valueNode, environment)) {
|
|
1336
|
+
return {
|
|
1337
|
+
kind: 'assignLocal',
|
|
1338
|
+
name: localName,
|
|
1339
|
+
value: { kind: 'string', value: '', type: STRING },
|
|
1340
|
+
text: lowerText(valueNode, environment),
|
|
1341
|
+
};
|
|
1342
|
+
}
|
|
1343
|
+
const value = lowerExpr(valueNode, environment);
|
|
1344
|
+
if (shapeOf(value) !== 'string')
|
|
1345
|
+
throw holds('a string');
|
|
1346
|
+
whenTyped(() => {
|
|
1347
|
+
if (value.kind === 'string') {
|
|
1348
|
+
checkConstantFits({ parts: [{ kind: 'literal', text: value.value }] }, `local "${name}"`);
|
|
1349
|
+
}
|
|
1350
|
+
});
|
|
1351
|
+
return { kind: 'assignLocal', name: localName, value };
|
|
1352
|
+
}
|
|
1353
|
+
const holdsBoolean = localShape(local) === 'bool';
|
|
1354
|
+
const lowered = lowerSource(valueNode, storeEnvironment(environment, () => is64BitLocal(local)));
|
|
1355
|
+
const shape = shapeOf(lowered.expression);
|
|
1356
|
+
if (holdsBoolean ? shape !== 'bool' : shape === 'bool') {
|
|
1357
|
+
throw holds(holdsBoolean ? 'a boolean' : 'a number');
|
|
1358
|
+
}
|
|
1359
|
+
if (shape === 'string')
|
|
1360
|
+
throw holds('a number');
|
|
1361
|
+
if (!holdsBoolean) {
|
|
1362
|
+
recordStore(lowered.source, local.assignable, local, environment);
|
|
1363
|
+
}
|
|
1364
|
+
whenTyped(() => checkStored(lowered.expression, { slotType: local.slotKind, isBoolean: holdsBoolean }, `local "${name}"`));
|
|
1365
|
+
return {
|
|
1366
|
+
kind: 'assignLocal',
|
|
1367
|
+
name: localName,
|
|
1368
|
+
value: storeValue(lowered.expression, () => local.slotKind),
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* The environment an updater's body reads: its parameter names the state's current value. A list's is the list,
|
|
1373
|
+
* an object's its fields, and a scalar's a read of its slot.
|
|
1374
|
+
*
|
|
1375
|
+
* @param target The state set.
|
|
1376
|
+
* @param updater The updater.
|
|
1377
|
+
* @param environment The handler's environment.
|
|
1378
|
+
*
|
|
1379
|
+
* @returns The body's environment.
|
|
1380
|
+
*/
|
|
1381
|
+
function updaterEnvironment(target, updater, environment) {
|
|
1382
|
+
const previousName = updater.params[0]?.name;
|
|
1383
|
+
if (!previousName)
|
|
1384
|
+
return environment;
|
|
1385
|
+
// The parameter hides any local or state of its name.
|
|
1386
|
+
const locals = new Map(environment.locals);
|
|
1387
|
+
locals.delete(previousName);
|
|
1388
|
+
const state = new Map(environment.state);
|
|
1389
|
+
state.delete(previousName);
|
|
1390
|
+
if (target.kind === 'list') {
|
|
1391
|
+
return {
|
|
1392
|
+
...environment,
|
|
1393
|
+
locals,
|
|
1394
|
+
state: state.set(previousName, target),
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
if (target.kind === 'record') {
|
|
1398
|
+
return {
|
|
1399
|
+
...environment,
|
|
1400
|
+
locals,
|
|
1401
|
+
state,
|
|
1402
|
+
constants: { ...environment.constants, [previousName]: target.value },
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
const previous = stateRead(target, true);
|
|
1406
|
+
locals.set(previousName, holdLater({
|
|
1407
|
+
source: {
|
|
1408
|
+
kind: 'state',
|
|
1409
|
+
state: target,
|
|
1410
|
+
latest: true,
|
|
1411
|
+
location: undefined,
|
|
1412
|
+
},
|
|
1413
|
+
expression: previous,
|
|
1414
|
+
}, shapeOf(previous), () => ({
|
|
1415
|
+
slotKind: target.slotKind,
|
|
1416
|
+
isBoolean: target.isBoolean,
|
|
1417
|
+
...(target.widened === 'number' ? { isLiteral: true } : {}),
|
|
1418
|
+
})));
|
|
1419
|
+
return { ...environment, locals, state };
|
|
1420
|
+
}
|
|
1421
|
+
/**
|
|
1422
|
+
* Lowers a setter given an updater with a block body: the body runs in place, and each `return next` sets the
|
|
1423
|
+
* state through an updater of its own, then leaves the body.
|
|
1424
|
+
*
|
|
1425
|
+
* @param setter The setter's name.
|
|
1426
|
+
* @param target The state set.
|
|
1427
|
+
* @param updater The updater.
|
|
1428
|
+
* @param environment The handler's environment.
|
|
1429
|
+
* @param state The component's state table.
|
|
1430
|
+
* @param context The statement compiler's context.
|
|
1431
|
+
* @param what What the updater is, for errors.
|
|
1432
|
+
*
|
|
1433
|
+
* @returns The statements.
|
|
1434
|
+
*/
|
|
1435
|
+
function inlineUpdater(setter, target, updater, environment, state, context, what) {
|
|
1436
|
+
const statements = updaterStatements(setter, updater, target.kind === 'list', what);
|
|
1437
|
+
const { helperList, usedReturn } = context;
|
|
1438
|
+
context.helperList = statements;
|
|
1439
|
+
context.usedReturn = false;
|
|
1440
|
+
try {
|
|
1441
|
+
const lowered = lowerStmts(statements, updaterEnvironment(target, updater, environment), state, context);
|
|
1442
|
+
return context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered;
|
|
1443
|
+
}
|
|
1444
|
+
finally {
|
|
1445
|
+
context.helperList = helperList;
|
|
1446
|
+
context.usedReturn = usedReturn;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* Lowers a dispatch: the reducer runs in place as an updater, its state parameter reading the state and its action
|
|
1451
|
+
* parameter bound to what is dispatched. Branches the action's constant fields rule out are dropped first.
|
|
1452
|
+
*
|
|
1453
|
+
* @param dispatch The dispatch's name.
|
|
1454
|
+
* @param target The state it sets.
|
|
1455
|
+
* @param reducer The state's reducer.
|
|
1456
|
+
* @param action What is dispatched.
|
|
1457
|
+
* @param environment The handler's environment.
|
|
1458
|
+
* @param state The component's state table.
|
|
1459
|
+
* @param context The statement compiler's context.
|
|
1460
|
+
*
|
|
1461
|
+
* @returns The statements.
|
|
1462
|
+
*/
|
|
1463
|
+
function inlineReducer(dispatch, target, { name, functionNode }, action, environment, state, context) {
|
|
1464
|
+
const [stateParameter, actionParameter] = functionNode.params;
|
|
1465
|
+
if (!action || action.type === 'SpreadElement') {
|
|
1466
|
+
throw aotError(`AOT: ${dispatch} must be given an action`, `pass the action itself: ${dispatch}({type: 'increment'}).`);
|
|
1467
|
+
}
|
|
1468
|
+
// An action that picks between two at run time dispatches each in a branch of its own.
|
|
1469
|
+
const choice = actionChoice(action, foldScope(environment, environment.constants ?? {}));
|
|
1470
|
+
if (choice) {
|
|
1471
|
+
const dispatchOf = (picked) => inlineReducer(dispatch, target, { name, functionNode }, picked, environment, state, context);
|
|
1472
|
+
return [
|
|
1473
|
+
{
|
|
1474
|
+
kind: 'if',
|
|
1475
|
+
test: lowerExprWide(choice.test, environment),
|
|
1476
|
+
consequent: dispatchOf(choice.whenTrue),
|
|
1477
|
+
alternate: dispatchOf(choice.whenFalse),
|
|
1478
|
+
},
|
|
1479
|
+
];
|
|
1480
|
+
}
|
|
1481
|
+
const bodyEnvironment = actionEnvironment(actionParameter?.name, action, environment);
|
|
1482
|
+
const statements = functionNode.body.type === 'BlockStatement'
|
|
1483
|
+
? functionNode.body.body
|
|
1484
|
+
: [{ type: 'ReturnStatement', argument: functionNode.body }];
|
|
1485
|
+
const unpruned = {
|
|
1486
|
+
type: 'ArrowFunctionExpression',
|
|
1487
|
+
params: stateParameter ? [stateParameter] : [],
|
|
1488
|
+
body: { type: 'BlockStatement', body: statements, directives: [] },
|
|
1489
|
+
loc: functionNode.loc,
|
|
1490
|
+
};
|
|
1491
|
+
const readEnvironment = updaterEnvironment(target, unpruned, bodyEnvironment);
|
|
1492
|
+
const updater = {
|
|
1493
|
+
...unpruned,
|
|
1494
|
+
body: {
|
|
1495
|
+
...unpruned.body,
|
|
1496
|
+
body: prunedStatements(statements, foldScope(readEnvironment, readEnvironment.constants ?? {})),
|
|
1497
|
+
},
|
|
1498
|
+
};
|
|
1499
|
+
return inlineUpdater(dispatch, target, updater, bodyEnvironment, state, context, `reducer "${name}"`);
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Inlines a handler-statement call to a helper / useCallback: binds the call's args to the helper's params, then
|
|
1503
|
+
* lowers the helper body here in the current env/state/ctx. A `return` in it leaves the helper, which becomes a
|
|
1504
|
+
* block.
|
|
473
1505
|
*
|
|
474
1506
|
* @param helperName The helper's name.
|
|
475
1507
|
* @param helper The helper.
|
|
476
|
-
* @param
|
|
477
|
-
* @param
|
|
1508
|
+
* @param callArguments The call's arguments.
|
|
1509
|
+
* @param environment The expression environment.
|
|
478
1510
|
* @param state The component's state table.
|
|
479
|
-
* @param
|
|
1511
|
+
* @param context The statement compiler's context.
|
|
480
1512
|
*
|
|
481
1513
|
* @returns The helper's body as statements.
|
|
482
1514
|
*/
|
|
483
|
-
function inlineHelperCall(helperName, helper,
|
|
484
|
-
// A helper already being inlined further up this call chain is recursive.
|
|
485
|
-
ctx.inlining = ctx.inlining ?? new Set();
|
|
486
|
-
if (ctx.inlining.has(helperName)) {
|
|
487
|
-
throw aotError(`AOT: helper "${helperName}" is recursive — can't be inlined into a handler`, 'handlers are flattened to straight-line C, so a helper that calls itself (directly ' +
|
|
488
|
-
'or via another helper) has no base case to unroll. Move recursive logic out of the ' +
|
|
489
|
-
'handler, or precompute the value.');
|
|
490
|
-
}
|
|
491
|
-
// Bind each passed argument to its parameter as a local holding the argument's C expression.
|
|
492
|
-
const locals = new Map(env.locals);
|
|
493
|
-
helper.params.forEach((param, paramIndex) => {
|
|
494
|
-
if (param.type !== 'Identifier') {
|
|
495
|
-
throw aotError(`AOT: helper "${helperName}" must take simple (identifier) params to be inlined`, 'a helper called from a handler must use plain positional params (e.g. `(a, b) => …`) ' +
|
|
496
|
-
'— destructuring or default params in the signature are not supported.');
|
|
497
|
-
}
|
|
498
|
-
if (args[paramIndex]) {
|
|
499
|
-
const argExpr = emitSourcedWide(args[paramIndex], env);
|
|
500
|
-
locals.set(param.name, {
|
|
501
|
-
code: argExpr.code,
|
|
502
|
-
cType: argExpr.cType,
|
|
503
|
-
isBool: argExpr.isBool,
|
|
504
|
-
lit: argExpr.lit,
|
|
505
|
-
wide: argExpr.wide,
|
|
506
|
-
source: argExpr.source,
|
|
507
|
-
});
|
|
508
|
-
}
|
|
509
|
-
});
|
|
1515
|
+
function inlineHelperCall(helperName, helper, callArguments, environment, state, context) {
|
|
510
1516
|
// An expression body is a single statement.
|
|
511
1517
|
const body = helper.body;
|
|
512
1518
|
const statements = body.type === 'BlockStatement'
|
|
513
1519
|
? body.body
|
|
514
1520
|
: [{ type: 'ExpressionStatement', expression: body }];
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
ctx.allowReturn = false;
|
|
1521
|
+
const { helperList, usedReturn } = context;
|
|
1522
|
+
context.helperList = statements;
|
|
1523
|
+
context.usedReturn = false;
|
|
519
1524
|
try {
|
|
520
|
-
|
|
1525
|
+
const lowered = lowerStmts(statements, helperEnvironment(helperName, helper, callArguments, environment), state, context);
|
|
1526
|
+
return context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered;
|
|
521
1527
|
}
|
|
522
1528
|
finally {
|
|
523
|
-
|
|
524
|
-
|
|
1529
|
+
context.helperList = helperList;
|
|
1530
|
+
context.usedReturn = usedReturn;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
/** The console methods a package can call, as Flow A has them. */
|
|
1534
|
+
const CONSOLE_METHODS = new Set(['log', 'warn', 'error']);
|
|
1535
|
+
/**
|
|
1536
|
+
* Whether a call is `console.log`, `console.warn` or `console.error`, on the global console: not a local, a state
|
|
1537
|
+
* or a constant of that name.
|
|
1538
|
+
*
|
|
1539
|
+
* @param call The call.
|
|
1540
|
+
* @param environment The expression environment.
|
|
1541
|
+
*
|
|
1542
|
+
* @returns True when it is.
|
|
1543
|
+
*/
|
|
1544
|
+
function isConsoleCall(call, environment) {
|
|
1545
|
+
const { callee } = call;
|
|
1546
|
+
if (callee.type !== 'MemberExpression' ||
|
|
1547
|
+
callee.computed ||
|
|
1548
|
+
callee.object.type !== 'Identifier' ||
|
|
1549
|
+
callee.object.name !== 'console' ||
|
|
1550
|
+
callee.property.type !== 'Identifier' ||
|
|
1551
|
+
environment.locals.has('console') ||
|
|
1552
|
+
environment.state.has('console') ||
|
|
1553
|
+
'console' in (environment.constants ?? {})) {
|
|
1554
|
+
return false;
|
|
1555
|
+
}
|
|
1556
|
+
if (!CONSOLE_METHODS.has(callee.property.name)) {
|
|
1557
|
+
throw aotError(`AOT: console.${callee.property.name} is not supported`, 'a package has console.log, console.warn and console.error, each one line in the host log.');
|
|
525
1558
|
}
|
|
1559
|
+
return true;
|
|
526
1560
|
}
|
|
527
1561
|
/**
|
|
528
1562
|
* Lowers one handler ExpressionStatement: a state setter, ref mutation, timer, updateVector, helper call, or
|
|
529
1563
|
* Animated.*(...).start() / .stop() (see lowerHandlerExpr, the located entry point).
|
|
530
1564
|
*
|
|
531
|
-
* @param
|
|
532
|
-
* @param
|
|
1565
|
+
* @param expression The statement's expression.
|
|
1566
|
+
* @param environment The expression environment.
|
|
533
1567
|
* @param state The component's state table.
|
|
534
|
-
* @param
|
|
1568
|
+
* @param context The statement compiler's context.
|
|
535
1569
|
*
|
|
536
1570
|
* @returns The statements.
|
|
537
1571
|
*/
|
|
538
|
-
function lowerHandlerExprImpl(
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
1572
|
+
function lowerHandlerExprImpl(expression, handlerEnvironment, state, context) {
|
|
1573
|
+
const environment = handlerEnvironment.outsideRender
|
|
1574
|
+
? handlerEnvironment
|
|
1575
|
+
: { ...handlerEnvironment, outsideRender: true };
|
|
1576
|
+
// `Sensors.setLed(on)`: a native method called for what it does.
|
|
1577
|
+
if (expression.type === 'CallExpression') {
|
|
1578
|
+
const nativeCallee = nativeCalleeOf(expression, environment);
|
|
1579
|
+
if (nativeCallee) {
|
|
1580
|
+
return [
|
|
1581
|
+
{
|
|
1582
|
+
kind: 'callNative',
|
|
1583
|
+
call: lowerNativeCall(expression, nativeCallee, environment),
|
|
1584
|
+
},
|
|
1585
|
+
];
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
// console.log / warn / error(…) → one line for the host's log.
|
|
1589
|
+
if (expression.type === 'CallExpression' &&
|
|
1590
|
+
isConsoleCall(expression, environment)) {
|
|
1591
|
+
const text = lowerLogText(expression.arguments, environment);
|
|
1592
|
+
return context.output.release ? [] : [{ kind: 'log', text }];
|
|
1593
|
+
}
|
|
1594
|
+
// updateVector(ref, shapes, dirtyRect?) — imperative vector redraw (no update).
|
|
1595
|
+
if (expression.type === 'CallExpression' &&
|
|
1596
|
+
expression.callee.type === 'Identifier' &&
|
|
1597
|
+
expression.callee.name === 'updateVector') {
|
|
1598
|
+
return [lowerUpdateVector(expression, environment, context)];
|
|
544
1599
|
}
|
|
545
1600
|
// setInterval / setTimeout(cb, ms) → register a host-tick timer (the returned id is discarded here).
|
|
546
|
-
if (
|
|
547
|
-
|
|
548
|
-
(
|
|
1601
|
+
if (expression.type === 'CallExpression' &&
|
|
1602
|
+
expression.callee.type === 'Identifier' &&
|
|
1603
|
+
(expression.callee.name === 'setInterval' ||
|
|
1604
|
+
expression.callee.name === 'setTimeout')) {
|
|
549
1605
|
return [
|
|
550
1606
|
{
|
|
551
1607
|
kind: 'startTimer',
|
|
552
|
-
timer: lowerTimer(
|
|
1608
|
+
timer: lowerTimer(expression, environment, state, context),
|
|
553
1609
|
idLocal: null,
|
|
554
1610
|
},
|
|
555
1611
|
];
|
|
556
1612
|
}
|
|
557
1613
|
// clearInterval / clearTimeout(id) → deactivate the timer slot.
|
|
558
|
-
if (
|
|
559
|
-
|
|
560
|
-
(
|
|
561
|
-
|
|
562
|
-
return [
|
|
1614
|
+
if (expression.type === 'CallExpression' &&
|
|
1615
|
+
expression.callee.type === 'Identifier' &&
|
|
1616
|
+
(expression.callee.name === 'clearInterval' ||
|
|
1617
|
+
expression.callee.name === 'clearTimeout')) {
|
|
1618
|
+
return [
|
|
1619
|
+
{
|
|
1620
|
+
kind: 'clearTimer',
|
|
1621
|
+
id: asInt(lowerExpr(expression.arguments[0], environment)),
|
|
1622
|
+
},
|
|
1623
|
+
];
|
|
563
1624
|
}
|
|
564
|
-
// `
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
}
|
|
570
|
-
// Lower the right side in the ref's width and check it fits; a 64-bit `%=` keeps its constant divisor.
|
|
571
|
-
const refEnv = ref.cType === 'i64' ? { ...env, math64: true } : env;
|
|
572
|
-
const loweredValue = lowerSource(expr.right, refEnv);
|
|
573
|
-
const valueExpr = loweredValue.expr;
|
|
574
|
-
const refHoldsTime = isTime(refType(ref));
|
|
575
|
-
if (expr.operator === '/=' && (refHoldsTime || isTime64(valueExpr))) {
|
|
576
|
-
throw aotError('AOT: `/=` on a 64-bit time value is not supported', 'JS division gives a fraction; write ref.current = Math.floor(ref.current / n) for whole units.');
|
|
577
|
-
}
|
|
578
|
-
const wideModDivisor = expr.operator === '%=' && (refHoldsTime || isTime64(valueExpr))
|
|
579
|
-
? constDivisor(expr.right, env)
|
|
1625
|
+
// `x = …`, `x += …` and `x++` on a local, which must be a `let`.
|
|
1626
|
+
const assigned = expression.type === 'AssignmentExpression'
|
|
1627
|
+
? expression.left
|
|
1628
|
+
: expression.type === 'UpdateExpression'
|
|
1629
|
+
? expression.argument
|
|
580
1630
|
: null;
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
const binaryOp = { '+=': '+', '-=': '-', '*=': '*' }[expr.operator];
|
|
585
|
-
const isFloatMod = expr.operator === '%=' &&
|
|
586
|
-
(ref.cType === 'float' || valueExpr.type.kind === 'float');
|
|
587
|
-
if ((isWholeRef &&
|
|
588
|
-
(binaryOp ||
|
|
589
|
-
(expr.operator === '/=' && valueExpr.type.kind === 'float'))) ||
|
|
590
|
-
isFloatMod) {
|
|
591
|
-
const resultExpr = lowerExprWide({
|
|
592
|
-
type: 'BinaryExpression',
|
|
593
|
-
operator: binaryOp ?? expr.operator.slice(0, -1),
|
|
594
|
-
left: expr.left,
|
|
595
|
-
right: expr.right,
|
|
596
|
-
loc: expr.loc,
|
|
597
|
-
}, refEnv);
|
|
1631
|
+
if (assigned?.type === 'Identifier') {
|
|
1632
|
+
const local = environment.locals.get(assigned.name);
|
|
1633
|
+
if (local) {
|
|
598
1634
|
return [
|
|
599
|
-
|
|
600
|
-
kind: 'writeRef',
|
|
601
|
-
ref,
|
|
602
|
-
op: '=',
|
|
603
|
-
value: storeValue(resultExpr, ref.cType),
|
|
604
|
-
},
|
|
1635
|
+
lowerLocalAssign(expression, assigned, local, environment),
|
|
605
1636
|
];
|
|
606
1637
|
}
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
(ref.cType === 'i64' && !refHoldsTime && isWholeValue)) &&
|
|
614
|
-
(expr.operator === '/=' || expr.operator === '%=')) {
|
|
615
|
-
const staticDivisor = staticInt(expr.right, env);
|
|
616
|
-
if (expr.operator === '/=' &&
|
|
617
|
-
(staticDivisor === null || staticDivisor === 0 || staticDivisor === -1)) {
|
|
618
|
-
return [
|
|
619
|
-
{
|
|
620
|
-
kind: 'writeRef',
|
|
621
|
-
ref,
|
|
622
|
-
op: '=',
|
|
623
|
-
value: {
|
|
624
|
-
kind: 'helper',
|
|
625
|
-
helper: 'div',
|
|
626
|
-
bits: refBits,
|
|
627
|
-
args: [refRead(ref), valueExpr],
|
|
628
|
-
type: refType(ref),
|
|
629
|
-
},
|
|
630
|
-
},
|
|
631
|
-
];
|
|
632
|
-
}
|
|
633
|
-
if (expr.operator === '%=' &&
|
|
634
|
-
(staticDivisor === 0 || staticDivisor === -1)) {
|
|
635
|
-
return [{ kind: 'writeRef', ref, op: '=', value: ZERO }];
|
|
636
|
-
}
|
|
637
|
-
if (expr.operator === '%=' && staticDivisor === null) {
|
|
638
|
-
return [
|
|
639
|
-
{
|
|
640
|
-
kind: 'writeRef',
|
|
641
|
-
ref,
|
|
642
|
-
op: '=',
|
|
643
|
-
value: {
|
|
644
|
-
kind: 'helper',
|
|
645
|
-
helper: 'mod',
|
|
646
|
-
bits: refBits,
|
|
647
|
-
args: [refRead(ref), valueExpr],
|
|
648
|
-
type: refType(ref),
|
|
649
|
-
},
|
|
650
|
-
},
|
|
651
|
-
];
|
|
652
|
-
}
|
|
1638
|
+
}
|
|
1639
|
+
// `ref.current = expr` / `ref.current += expr` — a value ref write; does NOT trigger a re-render.
|
|
1640
|
+
if (expression.type === 'AssignmentExpression') {
|
|
1641
|
+
const ref = refTarget(expression.left, environment);
|
|
1642
|
+
if (!ref) {
|
|
1643
|
+
throw new Error('AOT: a handler can only assign a `let` local or `ref.current`');
|
|
653
1644
|
}
|
|
654
|
-
//
|
|
655
|
-
|
|
656
|
-
|
|
1645
|
+
// Lower the right side; the typing pass works out the write, once it knows the ref's width.
|
|
1646
|
+
const value = lowerSource(expression.right, storeEnvironment(environment, () => is64BitSlot(ref)));
|
|
1647
|
+
if (ref.kind === 'value' && ref.slotKind !== 'float') {
|
|
1648
|
+
recordStore(value.source, ref.slotName, ref, environment);
|
|
657
1649
|
}
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
kind: 'writeRef',
|
|
662
|
-
ref,
|
|
663
|
-
op: expr.operator,
|
|
664
|
-
value: expr.operator === '='
|
|
665
|
-
? storeValue(valueExpr, ref.cType)
|
|
666
|
-
: valueExpr,
|
|
667
|
-
},
|
|
668
|
-
];
|
|
1650
|
+
const statement = { kind: 'writeRef', ref };
|
|
1651
|
+
setLater(statement, ['operator', 'value'], () => typedRefWrite(expression, ref, value, environment));
|
|
1652
|
+
return [statement];
|
|
669
1653
|
}
|
|
670
1654
|
// `ref.current++` / `ref.current--`; a whole-number ref steps through the checked `+ 1` / `- 1`.
|
|
671
|
-
if (
|
|
672
|
-
const ref = refTarget(
|
|
1655
|
+
if (expression.type === 'UpdateExpression') {
|
|
1656
|
+
const ref = refTarget(expression.argument, environment);
|
|
673
1657
|
if (!ref) {
|
|
674
|
-
throw new Error('AOT:
|
|
1658
|
+
throw new Error('AOT: a handler can only use ++/-- on a `let` local or `ref.current`');
|
|
675
1659
|
}
|
|
676
|
-
if (ref.
|
|
1660
|
+
if (ref.slotKind === 'int' || ref.slotKind === 'i64') {
|
|
1661
|
+
const { operator } = expression;
|
|
677
1662
|
return [
|
|
678
1663
|
{
|
|
679
1664
|
kind: 'writeRef',
|
|
680
1665
|
ref,
|
|
681
|
-
|
|
682
|
-
value: {
|
|
1666
|
+
operator: '=',
|
|
1667
|
+
value: typedLater('number', () => ({
|
|
683
1668
|
kind: 'helper',
|
|
684
|
-
helper:
|
|
685
|
-
bits: ref.
|
|
686
|
-
|
|
1669
|
+
helper: operator === '++' ? 'add' : 'sub',
|
|
1670
|
+
bits: ref.slotKind === 'i64' ? 64 : 32,
|
|
1671
|
+
callArguments: [
|
|
1672
|
+
refRead(ref),
|
|
1673
|
+
{ kind: 'number', value: 1, type: INT },
|
|
1674
|
+
],
|
|
687
1675
|
type: refType(ref),
|
|
688
|
-
},
|
|
1676
|
+
})),
|
|
689
1677
|
},
|
|
690
1678
|
];
|
|
691
1679
|
}
|
|
692
|
-
return [{ kind: 'stepRef', ref,
|
|
1680
|
+
return [{ kind: 'stepRef', ref, operator: expression.operator }];
|
|
693
1681
|
}
|
|
694
1682
|
// `anim.stop()` freezes each driven value; the cancel reports !finished, which ends any sequence or loop chain.
|
|
695
|
-
if (
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
isAnimatedCall(resolveAnim(
|
|
1683
|
+
if (expression.type === 'CallExpression' &&
|
|
1684
|
+
expression.callee.type === 'MemberExpression' &&
|
|
1685
|
+
expression.callee.property.name === 'stop' &&
|
|
1686
|
+
isAnimatedCall(resolveAnim(expression.callee.object, environment))) {
|
|
699
1687
|
return [
|
|
700
1688
|
{
|
|
701
1689
|
kind: 'stopAnimations',
|
|
702
|
-
handles: [...animValues(
|
|
703
|
-
waitOwner: stopWaitOwner(
|
|
1690
|
+
handles: [...animValues(expression.callee.object, environment)],
|
|
1691
|
+
waitOwner: stopWaitOwner(expression.callee.object, environment, context),
|
|
704
1692
|
},
|
|
705
1693
|
];
|
|
706
1694
|
}
|
|
707
|
-
// Animated.*(…).start(), atomic or composed, is native-driven, so it sets no state and needs no
|
|
708
|
-
if (
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
return [lowerAnimateStart(
|
|
1695
|
+
// Animated.*(…).start(), atomic or composed, is native-driven, so it sets no state and needs no update.
|
|
1696
|
+
if (expression.type === 'CallExpression' &&
|
|
1697
|
+
expression.callee.type === 'MemberExpression' &&
|
|
1698
|
+
expression.callee.property.name === 'start') {
|
|
1699
|
+
return [lowerAnimateStart(expression, environment, state, context)];
|
|
712
1700
|
}
|
|
713
1701
|
// What is left must be a plain call: to a helper or a state setter.
|
|
714
|
-
if (
|
|
1702
|
+
if (expression.type !== 'CallExpression' ||
|
|
1703
|
+
expression.callee.type !== 'Identifier') {
|
|
715
1704
|
throw aotError('AOT: a handler statement must be a state setter, a ref write, or Animated.timing/spring(...).start()', 'each statement in a handler must be one of: setX(value) / setX(prev => …), a ' +
|
|
716
1705
|
'`ref.current = …` write, an `updateVector(…)` call, or `Animated.timing|spring(v, ' +
|
|
717
1706
|
'…).start()`. Wrap conditional logic in `if (…) { … }`.');
|
|
718
1707
|
}
|
|
719
1708
|
// A call to a helper / useCallback (e.g. `reset();`) → inline its body here so handlers can compose logic.
|
|
720
|
-
const
|
|
721
|
-
|
|
722
|
-
|
|
1709
|
+
const helperFunction = environment.helpers?.get(expression.callee.name) ??
|
|
1710
|
+
environment.callbacks?.get(expression.callee.name);
|
|
1711
|
+
if (helperFunction) {
|
|
1712
|
+
return inlineHelperCall(expression.callee.name, helperFunction, expression.arguments, environment, state, context);
|
|
723
1713
|
}
|
|
724
1714
|
// A state setter. Flag the state change, which tells the caller to re-apply state once the body is done.
|
|
725
|
-
const targetState = state.bySetter.get(
|
|
1715
|
+
const targetState = state.bySetter.get(expression.callee.name);
|
|
726
1716
|
if (!targetState) {
|
|
727
|
-
throw aotError(`AOT: "${
|
|
728
|
-
`a ref write, updateVector(…), or Animated…start(). "${
|
|
729
|
-
`of those — arbitrary functions (fetch,
|
|
1717
|
+
throw aotError(`AOT: "${expression.callee.name}" is not a known state setter`, `a handler can only call a setter from this component's own useState (e.g. setCount), ` +
|
|
1718
|
+
`a ref write, updateVector(…), or Animated…start(). "${expression.callee.name}" isn't one ` +
|
|
1719
|
+
`of those — arbitrary functions (fetch, helpers) can't be lowered.`);
|
|
730
1720
|
}
|
|
731
|
-
|
|
732
|
-
const
|
|
733
|
-
|
|
734
|
-
|
|
1721
|
+
context.stateChanged = true;
|
|
1722
|
+
const setterArgument = expression.arguments[0];
|
|
1723
|
+
const setterCall = expression;
|
|
1724
|
+
// An object's updater and reducer read its fields as they are now. A scalar's parameter is marked itself.
|
|
1725
|
+
if (targetState.kind === 'record' &&
|
|
1726
|
+
(targetState.reducer || isFn(setterArgument))) {
|
|
1727
|
+
const slots = [...targetState.fields.values(), targetState.tag?.state];
|
|
1728
|
+
return readingLatest(lowerSetter(setterCall, targetState, environment, state, context), new Set(slots.filter(slot => slot !== undefined)));
|
|
735
1729
|
}
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
1730
|
+
return lowerSetter(setterCall, targetState, environment, state, context);
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Lowers a state setter's call: a dispatch, an updater, or the new value itself.
|
|
1734
|
+
*
|
|
1735
|
+
* @param expression The call.
|
|
1736
|
+
* @param targetState The state it sets.
|
|
1737
|
+
* @param environment The expression environment.
|
|
1738
|
+
* @param state The component's state table.
|
|
1739
|
+
* @param context The statement compiler's context.
|
|
1740
|
+
*
|
|
1741
|
+
* @returns The statements.
|
|
1742
|
+
*/
|
|
1743
|
+
function lowerSetter(expression, targetState, environment, state, context) {
|
|
1744
|
+
const setterArgument = expression.arguments[0];
|
|
1745
|
+
// A dispatch runs the reducer. Its reads of the state are an updater's, so inside a loop only the list rule holds.
|
|
1746
|
+
if (targetState.reducer && !isReturnSet(expression)) {
|
|
1747
|
+
if (context.loops?.length) {
|
|
1748
|
+
checkLoopSetter(expression.callee.name, targetState, undefined, environment, context.loops);
|
|
751
1749
|
}
|
|
752
|
-
|
|
753
|
-
|
|
1750
|
+
return inlineReducer(expression.callee.name, targetState, targetState.reducer, setterArgument, environment, state, context);
|
|
1751
|
+
}
|
|
1752
|
+
if (context.loops?.length && !isReturnSet(expression)) {
|
|
1753
|
+
checkLoopSetter(expression.callee.name, targetState, setterArgument, environment, context.loops);
|
|
1754
|
+
}
|
|
1755
|
+
// An updater with a block body runs here, each `return next` setting the state.
|
|
1756
|
+
if (isFn(setterArgument) && setterArgument.body.type === 'BlockStatement') {
|
|
1757
|
+
return inlineUpdater(expression.callee.name, targetState, setterArgument, environment, state, context);
|
|
1758
|
+
}
|
|
1759
|
+
if (targetState.kind === 'list') {
|
|
1760
|
+
// setItems(prev => …): the parameter names the list.
|
|
1761
|
+
if (isFn(setterArgument)) {
|
|
1762
|
+
const { itemName: previousName, body } = itemCallback(setterArgument, `${expression.callee.name}'s updater`);
|
|
1763
|
+
if (!previousName) {
|
|
1764
|
+
return lowerListOp(targetState, body, environment);
|
|
1765
|
+
}
|
|
1766
|
+
return lowerListOp(targetState, body, {
|
|
1767
|
+
...environment,
|
|
1768
|
+
state: new Map(environment.state).set(previousName, targetState),
|
|
1769
|
+
}, previousName);
|
|
1770
|
+
}
|
|
1771
|
+
return lowerListOp(targetState, setterArgument, environment);
|
|
1772
|
+
}
|
|
1773
|
+
// An object setter writes each field; setP(prev => …) binds the parameter to the object.
|
|
1774
|
+
if (targetState.kind === 'record') {
|
|
1775
|
+
if (isFn(setterArgument)) {
|
|
1776
|
+
return lowerRecordSet(targetState, setterArgument.body, updaterEnvironment(targetState, setterArgument, environment), RECORD_LOWERING);
|
|
754
1777
|
}
|
|
755
|
-
return
|
|
1778
|
+
return lowerRecordSet(targetState, setterArgument, environment, RECORD_LOWERING);
|
|
756
1779
|
}
|
|
757
|
-
|
|
1780
|
+
// A scalar setter takes either an updater function or the new value itself.
|
|
1781
|
+
if (setterArgument &&
|
|
1782
|
+
(setterArgument.type === 'ArrowFunctionExpression' ||
|
|
1783
|
+
setterArgument.type === 'FunctionExpression')) {
|
|
1784
|
+
// setState(prev => expr): the param reads the current value, and the result is assigned.
|
|
1785
|
+
return [
|
|
1786
|
+
lowerScalarSet(targetState, setterArgument.body, updaterEnvironment(targetState, setterArgument, environment)),
|
|
1787
|
+
];
|
|
1788
|
+
}
|
|
1789
|
+
return [lowerScalarSet(targetState, setterArgument, environment)];
|
|
758
1790
|
}
|
|
759
1791
|
/** lowerHandlerExprImpl, with the expression's source location attached to any AOT error it throws. */
|
|
760
|
-
const
|
|
1792
|
+
const lowerHandlerExpression = withLoc(lowerHandlerExprImpl);
|
|
761
1793
|
/**
|
|
762
1794
|
* Lowers a list of handler statements to the IR. This one-statement lowering runs event handlers, effect bodies
|
|
763
1795
|
* (useEffect), timer callbacks, and inlined helper calls. Supports: `const x = expr` (a local, visible to later
|
|
764
1796
|
* statements), `if (cond) {...} else {...}`, state setters (list setters included), ref writes, timers,
|
|
765
|
-
* updateVector() and Animated.*(...).start()
|
|
766
|
-
* `
|
|
767
|
-
* function of its own). `
|
|
768
|
-
*
|
|
1797
|
+
* updateVector() and Animated.*(...).start(), `switch` (as an if/else chain) and `return`. `context` accumulates
|
|
1798
|
+
* `stateChanged` (→ a trailing update) and `usedReturn` (an early `return` was lowered, so the body or helper is a
|
|
1799
|
+
* block it leaves, or an effect's function of its own). `context.bodyList` and `context.helperList` mark the
|
|
1800
|
+
* statements whose tail `return` needs no jump.
|
|
769
1801
|
*
|
|
770
1802
|
* @param statements The statements.
|
|
771
|
-
* @param
|
|
1803
|
+
* @param environment The expression environment.
|
|
772
1804
|
* @param state The component's state table.
|
|
773
|
-
* @param
|
|
1805
|
+
* @param context The statement compiler's context.
|
|
774
1806
|
*
|
|
775
1807
|
* @returns The lowered statements.
|
|
776
1808
|
*/
|
|
777
|
-
export function lowerStmts(statements,
|
|
1809
|
+
export function lowerStmts(statements, bodyEnvironment, state, context) {
|
|
1810
|
+
let environment = bodyEnvironment.outsideRender
|
|
1811
|
+
? bodyEnvironment
|
|
1812
|
+
: { ...bodyEnvironment, outsideRender: true };
|
|
778
1813
|
const lowered = [];
|
|
1814
|
+
// What each statement lowers to is marked with where it is, once the next one starts, after the values a helper
|
|
1815
|
+
// loops for that it reads.
|
|
1816
|
+
let from = 0;
|
|
1817
|
+
let location;
|
|
1818
|
+
let before;
|
|
1819
|
+
const settle = () => {
|
|
1820
|
+
if (before?.statements.length)
|
|
1821
|
+
lowered.splice(from, 0, ...before.statements);
|
|
1822
|
+
markLoc(lowered, from, location);
|
|
1823
|
+
};
|
|
779
1824
|
for (let statementIndex = 0; statementIndex < statements.length; statementIndex++) {
|
|
1825
|
+
settle();
|
|
780
1826
|
const statement = statements[statementIndex];
|
|
1827
|
+
from = lowered.length;
|
|
1828
|
+
location = startOf(statement);
|
|
1829
|
+
before = { statements: [], state, output: context.output };
|
|
1830
|
+
environment = { ...environment, before };
|
|
781
1831
|
// `const x = …` declares a local that the statements after it can read.
|
|
782
1832
|
if (statement.type === 'VariableDeclaration') {
|
|
783
|
-
|
|
784
|
-
|
|
1833
|
+
// An object's declaration expands into a local per field, put back in the queue.
|
|
1834
|
+
const queue = [
|
|
1835
|
+
...statement.declarations,
|
|
1836
|
+
];
|
|
1837
|
+
// Each initializer's looping values go just before it, as a later one may read an earlier local.
|
|
1838
|
+
const sink = before;
|
|
1839
|
+
let declaratorFrom = lowered.length;
|
|
1840
|
+
const nextDeclarator = () => {
|
|
1841
|
+
lowered.splice(declaratorFrom, 0, ...sink.statements);
|
|
1842
|
+
sink.statements = [];
|
|
1843
|
+
declaratorFrom = lowered.length;
|
|
1844
|
+
};
|
|
1845
|
+
while (queue.length) {
|
|
1846
|
+
nextDeclarator();
|
|
1847
|
+
const entry = queue.shift();
|
|
1848
|
+
if (!('type' in entry)) {
|
|
1849
|
+
const locals = new Map(environment.locals);
|
|
1850
|
+
locals.delete(entry.name);
|
|
1851
|
+
environment = {
|
|
1852
|
+
...environment,
|
|
1853
|
+
locals,
|
|
1854
|
+
constants: {
|
|
1855
|
+
...environment.constants,
|
|
1856
|
+
[entry.name]: boundObjectOf(entry, environment.locals),
|
|
1857
|
+
},
|
|
1858
|
+
};
|
|
1859
|
+
continue;
|
|
1860
|
+
}
|
|
1861
|
+
const declarator = entry;
|
|
1862
|
+
// A native method's record: its values kept in locals, then declared as an object of them, or a field.
|
|
1863
|
+
const recordRoot = nativeRecordRootOf(declarator.init, environment);
|
|
1864
|
+
if (recordRoot) {
|
|
1865
|
+
const kept = keepNativeRecord(recordRoot.call, recordRoot.callee, environment);
|
|
1866
|
+
lowered.push(kept.statement);
|
|
1867
|
+
environment = kept.environment;
|
|
1868
|
+
queue.unshift({
|
|
1869
|
+
...declarator,
|
|
1870
|
+
init: recordRoot.replaced({
|
|
1871
|
+
type: 'Identifier',
|
|
1872
|
+
name: kept.name,
|
|
1873
|
+
}),
|
|
1874
|
+
});
|
|
1875
|
+
continue;
|
|
1876
|
+
}
|
|
1877
|
+
const expanded = expandObjectDeclarator(declarator, environment);
|
|
1878
|
+
if (expanded) {
|
|
1879
|
+
if (statement.kind !== 'const') {
|
|
1880
|
+
throw aotError('AOT: an object in a handler must be a `const`', 'build a new object instead of changing this one, and declare it with const.');
|
|
1881
|
+
}
|
|
1882
|
+
queue.unshift(...expanded.entries);
|
|
1883
|
+
if (expanded.locals.size) {
|
|
1884
|
+
environment = {
|
|
1885
|
+
...environment,
|
|
1886
|
+
locals: new Map([...environment.locals, ...expanded.locals]),
|
|
1887
|
+
};
|
|
1888
|
+
}
|
|
1889
|
+
continue;
|
|
1890
|
+
}
|
|
1891
|
+
if (declarator.id.type !== 'Identifier') {
|
|
785
1892
|
throw new Error('AOT: destructuring a handler local is not supported');
|
|
786
1893
|
}
|
|
787
|
-
if (!
|
|
1894
|
+
if (!declarator.init) {
|
|
788
1895
|
throw new Error('AOT: a handler local must have an initializer');
|
|
789
1896
|
}
|
|
790
|
-
// `const anim = Animated.…` holds no
|
|
791
|
-
if (isAnimatedCall(
|
|
792
|
-
const locals = new Map(
|
|
793
|
-
locals.delete(
|
|
794
|
-
|
|
795
|
-
...
|
|
1897
|
+
// `const anim = Animated.…` holds no value; `anim.start()`/`anim.stop()` compile the animation it names.
|
|
1898
|
+
if (isAnimatedCall(declarator.init)) {
|
|
1899
|
+
const locals = new Map(environment.locals);
|
|
1900
|
+
locals.delete(declarator.id.name);
|
|
1901
|
+
environment = {
|
|
1902
|
+
...environment,
|
|
1903
|
+
locals,
|
|
1904
|
+
animationLocals: new Map(environment.animationLocals).set(declarator.id.name, declarator.init),
|
|
1905
|
+
};
|
|
1906
|
+
continue;
|
|
1907
|
+
}
|
|
1908
|
+
// `const parts = text.split(',')` fills a list of the handler's own, read as `parts[i]` and `parts.length`.
|
|
1909
|
+
const split = handlerSplitList(declarator.id.name, declarator.init, statement.kind, environment);
|
|
1910
|
+
if (split) {
|
|
1911
|
+
lowered.push(...split.statements);
|
|
1912
|
+
const locals = new Map(environment.locals);
|
|
1913
|
+
locals.delete(declarator.id.name);
|
|
1914
|
+
environment = {
|
|
1915
|
+
...environment,
|
|
796
1916
|
locals,
|
|
797
|
-
|
|
1917
|
+
state: new Map(environment.state).set(declarator.id.name, split.list),
|
|
798
1918
|
};
|
|
799
1919
|
continue;
|
|
800
1920
|
}
|
|
801
|
-
// A dep-driven effect's cleanup outlives the call, so the body's locals become
|
|
802
|
-
|
|
803
|
-
const
|
|
804
|
-
|
|
805
|
-
|
|
1921
|
+
// A dep-driven effect's cleanup outlives the call, so the body's locals become slots. A `let`, and a local
|
|
1922
|
+
// that hides an outer one, has a name of its own, so the two keep apart, string buffers too.
|
|
1923
|
+
const isHoisted = Boolean(context.hoist && statements === context.bodyList);
|
|
1924
|
+
const isLet = statement.kind !== 'const';
|
|
1925
|
+
const localName = isHoisted
|
|
1926
|
+
? `${context.hoist.prefix}${declarator.id.name}`
|
|
1927
|
+
: isLet || environment.locals.has(declarator.id.name)
|
|
1928
|
+
? `local_${declarator.id.name}@${declarator.start ?? 0}`
|
|
1929
|
+
: `local_${declarator.id.name}`;
|
|
806
1930
|
// `const id = setInterval/setTimeout(…)` is an int timer-id local, so a later clearInterval(id) resolves.
|
|
807
|
-
if (
|
|
808
|
-
|
|
809
|
-
(
|
|
810
|
-
|
|
1931
|
+
if (declarator.init.type === 'CallExpression' &&
|
|
1932
|
+
declarator.init.callee.type === 'Identifier' &&
|
|
1933
|
+
(declarator.init.callee.name === 'setInterval' ||
|
|
1934
|
+
declarator.init.callee.name === 'setTimeout')) {
|
|
811
1935
|
// The id is only needed for a later clear*(); a mount effect drops its cleanup, so mark it used.
|
|
812
1936
|
if (isHoisted) {
|
|
813
|
-
|
|
1937
|
+
context.hoist.declarations.push({
|
|
1938
|
+
kind: 'local',
|
|
1939
|
+
name: localName,
|
|
1940
|
+
slotKind: 'int',
|
|
1941
|
+
});
|
|
814
1942
|
}
|
|
815
1943
|
lowered.push({
|
|
816
1944
|
kind: 'startTimer',
|
|
817
|
-
timer: lowerTimer(
|
|
818
|
-
idLocal: { name:
|
|
1945
|
+
timer: lowerTimer(declarator.init, environment, state, context),
|
|
1946
|
+
idLocal: { name: localName, isHoisted },
|
|
819
1947
|
});
|
|
820
|
-
|
|
821
|
-
...
|
|
822
|
-
locals: new Map(
|
|
823
|
-
|
|
824
|
-
|
|
1948
|
+
environment = {
|
|
1949
|
+
...environment,
|
|
1950
|
+
locals: new Map(environment.locals).set(declarator.id.name, {
|
|
1951
|
+
name: localName,
|
|
1952
|
+
slotKind: 'int',
|
|
825
1953
|
}),
|
|
826
1954
|
};
|
|
827
1955
|
continue;
|
|
828
1956
|
}
|
|
829
|
-
// Any other initializer must lower to a number, a boolean or a string.
|
|
830
|
-
const
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
1957
|
+
// Any other initializer must lower to a number, a boolean or a string. A built string is text.
|
|
1958
|
+
const text = buildsText(declarator.init, environment)
|
|
1959
|
+
? lowerText(declarator.init, environment)
|
|
1960
|
+
: undefined;
|
|
1961
|
+
const initial = text
|
|
1962
|
+
? {
|
|
1963
|
+
source: undefined,
|
|
1964
|
+
expression: { kind: 'string', value: '', type: STRING },
|
|
834
1965
|
}
|
|
1966
|
+
: lowerSource(declarator.init, environment);
|
|
1967
|
+
const { source: initialSource, expression: initialExpression } = initial;
|
|
1968
|
+
const localId = declarator.id.name;
|
|
1969
|
+
const shape = shapeOf(initialExpression);
|
|
1970
|
+
if (shape === 'string') {
|
|
1971
|
+
whenTyped(() => {
|
|
1972
|
+
if (initialExpression.kind === 'string') {
|
|
1973
|
+
checkConstantFits({ parts: [{ kind: 'literal', text: initialExpression.value }] }, `local "${localId}"`);
|
|
1974
|
+
}
|
|
1975
|
+
});
|
|
835
1976
|
// Copy into a buffer of its own; aliasing a state slot would hide a self-read like `setLabel(t + '!')`.
|
|
836
1977
|
if (isHoisted) {
|
|
837
|
-
|
|
1978
|
+
context.hoist.declarations.push({
|
|
838
1979
|
kind: 'local',
|
|
839
|
-
name:
|
|
840
|
-
|
|
1980
|
+
name: localName,
|
|
1981
|
+
slotKind: 'string',
|
|
841
1982
|
});
|
|
842
1983
|
}
|
|
843
1984
|
}
|
|
844
|
-
else {
|
|
845
|
-
const
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1985
|
+
else if (shape !== 'number' && shape !== 'bool') {
|
|
1986
|
+
throw aotError('AOT: a handler local must hold a number, a boolean or a string', 'bind the value itself — e.g. `const id = item.id` — rather than a list item or a node ref.');
|
|
1987
|
+
}
|
|
1988
|
+
// A whole-number `let` set to a fraction or a timestamp later holds one from the start. Later statements
|
|
1989
|
+
// read the name as the local; a `let` is read from where it is kept, whatever set it last.
|
|
1990
|
+
const letKey = `let@${declarator.id.name}@${declarator.start ?? 0}`;
|
|
1991
|
+
const widthOf = () => isLet && initialExpression.type.kind === 'int'
|
|
1992
|
+
? environment.wide.get(letKey)
|
|
1993
|
+
: undefined;
|
|
1994
|
+
const bare = !isLet && initialSource
|
|
1995
|
+
? bareLocalOf({
|
|
1996
|
+
source: initialSource,
|
|
1997
|
+
expression: initialExpression,
|
|
1998
|
+
})
|
|
1999
|
+
: null;
|
|
2000
|
+
const local = bare
|
|
2001
|
+
? copyLocal(bare, { name: localName, source: initialSource })
|
|
2002
|
+
: holdLater(isLet
|
|
2003
|
+
? {
|
|
2004
|
+
name: localName,
|
|
2005
|
+
assignable: letKey,
|
|
2006
|
+
declared: initialSource,
|
|
2007
|
+
}
|
|
2008
|
+
: { name: localName, source: initialSource }, shape, () => {
|
|
2009
|
+
const width = widthOf();
|
|
2010
|
+
const held = width
|
|
2011
|
+
? width === 'float'
|
|
2012
|
+
? { slotKind: 'float' }
|
|
2013
|
+
: {
|
|
2014
|
+
slotKind: 'i64',
|
|
2015
|
+
...(width === 'number' ? { isLiteral: true } : {}),
|
|
2016
|
+
}
|
|
2017
|
+
: slotValueOf(initialExpression);
|
|
2018
|
+
return isLet
|
|
2019
|
+
? {
|
|
2020
|
+
slotKind: held.slotKind,
|
|
2021
|
+
...(held.isBoolean ? { isBoolean: true } : {}),
|
|
2022
|
+
...(held.isLiteral ? { isLiteral: true } : {}),
|
|
2023
|
+
...(held.wide ? { wide: true } : {}),
|
|
2024
|
+
}
|
|
2025
|
+
: held;
|
|
2026
|
+
});
|
|
2027
|
+
if (isHoisted && shape !== 'string') {
|
|
2028
|
+
const declaration = { kind: 'local', name: localName };
|
|
2029
|
+
context.hoist.declarations.push(declaration);
|
|
2030
|
+
setLater(declaration, ['slotKind'], () => ({
|
|
2031
|
+
slotKind: local.slotKind,
|
|
2032
|
+
}));
|
|
856
2033
|
}
|
|
857
|
-
|
|
2034
|
+
const declare = {
|
|
858
2035
|
kind: 'declareLocal',
|
|
859
|
-
name:
|
|
860
|
-
|
|
2036
|
+
name: localName,
|
|
2037
|
+
initializer: initialExpression,
|
|
2038
|
+
...(text ? { text } : {}),
|
|
861
2039
|
isHoisted,
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
2040
|
+
};
|
|
2041
|
+
if (isLet && shape === 'number') {
|
|
2042
|
+
setLater(declare, ['widenedTo'], () => {
|
|
2043
|
+
const width = widthOf();
|
|
2044
|
+
const widenedTo = !width
|
|
2045
|
+
? undefined
|
|
2046
|
+
: width === 'float'
|
|
2047
|
+
? 'float'
|
|
2048
|
+
: 'int64';
|
|
2049
|
+
return { widenedTo };
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
lowered.push(declare);
|
|
2053
|
+
environment = {
|
|
2054
|
+
...environment,
|
|
2055
|
+
locals: new Map(environment.locals).set(declarator.id.name, local),
|
|
872
2056
|
};
|
|
873
2057
|
}
|
|
2058
|
+
nextDeclarator();
|
|
874
2059
|
continue;
|
|
875
2060
|
}
|
|
876
|
-
//
|
|
877
|
-
if (statement.type === '
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
2061
|
+
// `switch` runs as an if/else chain; a bare block lowers in place, its locals its own.
|
|
2062
|
+
if (statement.type === 'SwitchStatement') {
|
|
2063
|
+
lowered.push(...lowerStmts([switchAsIf(statement)], environment, state, context));
|
|
2064
|
+
continue;
|
|
2065
|
+
}
|
|
2066
|
+
if (statement.type === 'BlockStatement') {
|
|
2067
|
+
lowered.push(...lowerStmts(statement.body, environment, state, context));
|
|
2068
|
+
continue;
|
|
2069
|
+
}
|
|
2070
|
+
// `for` counts to a bound the compiler works out, and `for…of` visits a list's rows.
|
|
2071
|
+
if (statement.type === 'ForStatement') {
|
|
2072
|
+
lowered.push(...lowerFor(statement, environment, state, context, lowerStmts));
|
|
2073
|
+
continue;
|
|
2074
|
+
}
|
|
2075
|
+
if (statement.type === 'ForOfStatement') {
|
|
2076
|
+
lowered.push(...lowerForOf(statement, environment, state, context, lowerStmts));
|
|
2077
|
+
continue;
|
|
2078
|
+
}
|
|
2079
|
+
if (statement.type === 'BreakStatement' ||
|
|
2080
|
+
statement.type === 'ContinueStatement') {
|
|
2081
|
+
const word = statement.type === 'BreakStatement' ? 'break' : 'continue';
|
|
2082
|
+
if (statement.label) {
|
|
2083
|
+
throw located(aotError(`AOT: a labeled \`${word}\` is not supported`, 'leave the inner loop with a plain break and test a let after it, or move the loops into a helper ' +
|
|
2084
|
+
'and return from it.'), statement);
|
|
2085
|
+
}
|
|
2086
|
+
if (!context.loops?.length) {
|
|
2087
|
+
throw located(aotError(`AOT: a \`${word}\` must be inside a loop`), statement);
|
|
884
2088
|
}
|
|
885
|
-
|
|
886
|
-
|
|
2089
|
+
lowered.push({ kind: word });
|
|
2090
|
+
continue;
|
|
2091
|
+
}
|
|
2092
|
+
if (statement.type === 'LabeledStatement') {
|
|
2093
|
+
throw located(aotError('AOT: a labeled statement is not supported', 'leave the inner loop with a plain break and test a let after it, or move the loops into a helper ' +
|
|
2094
|
+
'and return from it.'), statement);
|
|
2095
|
+
}
|
|
2096
|
+
if (statement.type === 'WhileStatement' ||
|
|
2097
|
+
statement.type === 'DoWhileStatement' ||
|
|
2098
|
+
statement.type === 'ForInStatement') {
|
|
2099
|
+
throw located(aotError(`AOT: a ${statement.type === 'ForInStatement' ? 'for…in' : 'while'} loop is not supported`, "a loop needs a bound the compiler can count. Write a for loop from a constant or a list's length to " +
|
|
2100
|
+
'another, or for (const item of items), and break out of it early.'), statement);
|
|
2101
|
+
}
|
|
2102
|
+
// An effect body's tail `return` is the cleanup, dropped on mount and armed if dep-driven; any other `return`
|
|
2103
|
+
// leaves the body or helper, the value it gives unused.
|
|
2104
|
+
if (statement.type === 'ReturnStatement') {
|
|
2105
|
+
const argument = statement.argument;
|
|
2106
|
+
const isLast = statementIndex === statements.length - 1;
|
|
2107
|
+
const isBodyTail = isLast && statements === context.bodyList;
|
|
2108
|
+
if (context.dependencyDriven && isFn(argument) && !isBodyTail) {
|
|
887
2109
|
const error = aotError('AOT: a useEffect cleanup must be the last statement of the effect body', 'a cleanup returned from inside an `if` would be dropped. Return `undefined` from the ' +
|
|
888
2110
|
'guard and put the single `return () => …` at the end of the body.');
|
|
889
2111
|
if (statement.loc) {
|
|
@@ -891,220 +2113,480 @@ export function lowerStmts(statements, env, state, ctx) {
|
|
|
891
2113
|
}
|
|
892
2114
|
throw error;
|
|
893
2115
|
}
|
|
894
|
-
if (
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
lowered.push({ kind: 'armCleanup', flag: ctx.cleanup.armed });
|
|
898
|
-
}
|
|
2116
|
+
if (isBodyTail && context.cleanup && isFn(argument)) {
|
|
2117
|
+
context.cleanup.emit(argument, environment);
|
|
2118
|
+
lowered.push({ kind: 'armCleanup', flag: context.cleanup.armed });
|
|
899
2119
|
continue;
|
|
900
2120
|
}
|
|
901
|
-
|
|
2121
|
+
// A body that works out a value keeps what it returns; elsewhere `return setX(…)` still sets it.
|
|
2122
|
+
if (context.returnsValue && argument) {
|
|
2123
|
+
lowered.push(...context.returnsValue(argument, environment));
|
|
2124
|
+
}
|
|
2125
|
+
else if (argument?.type === 'CallExpression' ||
|
|
2126
|
+
argument?.type === 'AssignmentExpression' ||
|
|
2127
|
+
argument?.type === 'UpdateExpression') {
|
|
2128
|
+
lowered.push(...lowerHandlerExpression(argument, environment, state, context));
|
|
2129
|
+
}
|
|
2130
|
+
if (isLast &&
|
|
2131
|
+
(statements === context.bodyList || statements === context.helperList)) {
|
|
2132
|
+
continue;
|
|
2133
|
+
}
|
|
2134
|
+
context.usedReturn = true;
|
|
902
2135
|
lowered.push({ kind: 'return' });
|
|
903
2136
|
continue;
|
|
904
2137
|
}
|
|
905
2138
|
// `if (…) { … } else { … }` lowers each branch in order: the test, then the consequent, then the alternate.
|
|
906
2139
|
if (statement.type === 'IfStatement') {
|
|
907
|
-
const test = lowerExprWide(statement.test,
|
|
908
|
-
|
|
2140
|
+
const test = lowerExprWide(statement.test, environment);
|
|
2141
|
+
// A test on a tagged object's tag narrows the fields each branch can read.
|
|
2142
|
+
const narrowing = narrowOn(statement.test, environment);
|
|
2143
|
+
const consequentStatements = statementsOf(statement.consequent);
|
|
2144
|
+
const alternateStatements = statement.alternate
|
|
2145
|
+
? statementsOf(statement.alternate)
|
|
2146
|
+
: [];
|
|
2147
|
+
const consequent = lowerStmts(consequentStatements, narrowed(environment, narrowing.whenTrue), state, context);
|
|
909
2148
|
const alternate = statement.alternate
|
|
910
|
-
? lowerStmts(
|
|
2149
|
+
? lowerStmts(alternateStatements, narrowed(environment, narrowing.whenFalse), state, context)
|
|
911
2150
|
: null;
|
|
912
2151
|
lowered.push({ kind: 'if', test, consequent, alternate });
|
|
2152
|
+
// The statements after a branch that returns, breaks or continues read what the other branch's test leaves.
|
|
2153
|
+
const inLoop = Boolean(context.loops?.length);
|
|
2154
|
+
if (exits(consequentStatements, inLoop)) {
|
|
2155
|
+
environment = narrowed(environment, narrowing.whenFalse);
|
|
2156
|
+
}
|
|
2157
|
+
else if (exits(alternateStatements, inLoop)) {
|
|
2158
|
+
environment = narrowed(environment, narrowing.whenTrue);
|
|
2159
|
+
}
|
|
913
2160
|
continue;
|
|
914
2161
|
}
|
|
915
2162
|
// Anything else must be an expression statement: a setter call, a ref write, a timer, and so on.
|
|
916
2163
|
if (statement.type !== 'ExpressionStatement') {
|
|
917
|
-
throw aotError(`AOT: unsupported statement "${statement.type}" in event handler`, 'a handler supports only `const
|
|
918
|
-
'expression statements (setters / ref writes / updateVector / Animated…start).
|
|
919
|
-
'
|
|
920
|
-
'logic into if/else.');
|
|
2164
|
+
throw aotError(`AOT: unsupported statement "${statement.type}" in event handler`, 'a handler supports only `const` and `let` locals, `if`, `switch`, `for`, `for…of`, `return`, and ' +
|
|
2165
|
+
'expression statements (setters / ref and local writes / updateVector / Animated…start). ' +
|
|
2166
|
+
'try/catch is not lowered.');
|
|
921
2167
|
}
|
|
922
|
-
|
|
2168
|
+
// A native method's record given straight to a call that takes one, setFix(Gps.fix()), or a field of it,
|
|
2169
|
+
// setLat(Gps.fix().lat): kept first, then passed by its name.
|
|
2170
|
+
let expression = statement.expression;
|
|
2171
|
+
const keptRoot = (argument, index) => {
|
|
2172
|
+
const recordRoot = nativeRecordRootOf(argument, environment);
|
|
2173
|
+
return recordRoot &&
|
|
2174
|
+
(recordRoot.call !== argument ||
|
|
2175
|
+
takesRecord(expression, index, environment, state))
|
|
2176
|
+
? recordRoot
|
|
2177
|
+
: null;
|
|
2178
|
+
};
|
|
2179
|
+
if (expression.type === 'CallExpression' &&
|
|
2180
|
+
expression.arguments.some(keptRoot)) {
|
|
2181
|
+
const callArguments = expression.arguments.map((argument, index) => {
|
|
2182
|
+
const recordRoot = keptRoot(argument, index);
|
|
2183
|
+
if (!recordRoot)
|
|
2184
|
+
return argument;
|
|
2185
|
+
const kept = keepNativeRecord(recordRoot.call, recordRoot.callee, environment);
|
|
2186
|
+
lowered.push(kept.statement);
|
|
2187
|
+
environment = kept.environment;
|
|
2188
|
+
return recordRoot.replaced({
|
|
2189
|
+
type: 'Identifier',
|
|
2190
|
+
name: kept.name,
|
|
2191
|
+
});
|
|
2192
|
+
});
|
|
2193
|
+
expression = { ...expression, arguments: callArguments };
|
|
2194
|
+
}
|
|
2195
|
+
lowered.push(...lowerHandlerExpression(expression, environment, state, context));
|
|
923
2196
|
}
|
|
2197
|
+
settle();
|
|
924
2198
|
return lowered;
|
|
925
2199
|
}
|
|
2200
|
+
/**
|
|
2201
|
+
* An error located at a statement.
|
|
2202
|
+
*
|
|
2203
|
+
* @param error The error.
|
|
2204
|
+
* @param statement The statement.
|
|
2205
|
+
*
|
|
2206
|
+
* @returns The error.
|
|
2207
|
+
*/
|
|
2208
|
+
function located(error, statement) {
|
|
2209
|
+
if (statement.loc)
|
|
2210
|
+
error.aotLoc = statement.loc.start;
|
|
2211
|
+
return error;
|
|
2212
|
+
}
|
|
2213
|
+
/**
|
|
2214
|
+
* Lowers a body of its own: a handler's, a timer's, an animation completion's or an effect cleanup's. A `return` in
|
|
2215
|
+
* it leaves the block it becomes.
|
|
2216
|
+
*
|
|
2217
|
+
* @param statements The body's statements.
|
|
2218
|
+
* @param environment The expression environment.
|
|
2219
|
+
* @param state The component's state table.
|
|
2220
|
+
* @param context The statement compiler's context, new for this body.
|
|
2221
|
+
*
|
|
2222
|
+
* @returns The lowered statements.
|
|
2223
|
+
*/
|
|
2224
|
+
export function lowerBody(statements, environment, state, context) {
|
|
2225
|
+
context.bodyList = statements;
|
|
2226
|
+
const lowered = lowerStmts(statements, environment, state, context);
|
|
2227
|
+
return keepingStates(context.usedReturn ? [{ kind: 'block', body: lowered }] : lowered, context.output);
|
|
2228
|
+
}
|
|
2229
|
+
/**
|
|
2230
|
+
* Where a statement starts. An expression body made into a statement has no location of its own.
|
|
2231
|
+
*
|
|
2232
|
+
* @param statement The statement.
|
|
2233
|
+
*
|
|
2234
|
+
* @returns Its start, if it has one.
|
|
2235
|
+
*/
|
|
2236
|
+
function startOf(statement) {
|
|
2237
|
+
return (statement.loc?.start ??
|
|
2238
|
+
(statement.type === 'ExpressionStatement'
|
|
2239
|
+
? statement.expression.loc?.start
|
|
2240
|
+
: undefined));
|
|
2241
|
+
}
|
|
2242
|
+
/**
|
|
2243
|
+
* Marks the statements lowered from one source statement with its location. One nested inside it, or inlined
|
|
2244
|
+
* from a helper, keeps its own.
|
|
2245
|
+
*
|
|
2246
|
+
* @param lowered The statements lowered so far.
|
|
2247
|
+
* @param from The first one the source statement lowered to.
|
|
2248
|
+
* @param location Where the source statement is.
|
|
2249
|
+
*/
|
|
2250
|
+
function markLoc(lowered, from, location) {
|
|
2251
|
+
for (let index = from; index < lowered.length; index++) {
|
|
2252
|
+
lowered[index].location ??= location;
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
926
2255
|
/**
|
|
927
2256
|
* Lowers a useEffect (App or child). Two shapes:
|
|
928
|
-
* - `useEffect(fn, [])` — MOUNT-ONCE: body runs after the initial
|
|
929
|
-
* - `useEffect(fn, [dep…])` — DEP-DRIVEN: body becomes a
|
|
930
|
-
* then again
|
|
931
|
-
*
|
|
932
|
-
*
|
|
933
|
-
* A dep-driven `return () => …` becomes `
|
|
2257
|
+
* - `useEffect(fn, [])` — MOUNT-ONCE: body runs after the initial the update (in the build).
|
|
2258
|
+
* - `useEffect(fn, [dep…])` — DEP-DRIVEN: body becomes a function of its own; runs once at mount,
|
|
2259
|
+
* then again after an update whenever a SCALAR dep changes (compared against a stored prev). It runs after
|
|
2260
|
+
* the update pass, and one that set state asks for another pass, which shows it; an effect that keeps changing
|
|
2261
|
+
* its deps stops the app at the runtime's pass limit, where React reports an update loop.
|
|
2262
|
+
* A dep-driven `return () => …` becomes `effect_N_cleanup()`, run at the top of the next re-run.
|
|
934
2263
|
*
|
|
935
2264
|
* @param effect The effect.
|
|
936
|
-
* @param
|
|
2265
|
+
* @param environment The expression environment.
|
|
937
2266
|
* @param state The component's state table.
|
|
938
|
-
* @param
|
|
2267
|
+
* @param output Everything emitted so far; the effect is added to it.
|
|
939
2268
|
*/
|
|
940
|
-
export function lowerEffect(effect,
|
|
2269
|
+
export function lowerEffect(effect, environment, state, output) {
|
|
941
2270
|
// An expression body is a single statement.
|
|
942
|
-
const body = effect.
|
|
2271
|
+
const body = effect.functionNode.body;
|
|
943
2272
|
const statements = body.type === 'BlockStatement'
|
|
944
2273
|
? body.body
|
|
945
2274
|
: [{ type: 'ExpressionStatement', expression: body }];
|
|
946
|
-
// A mount-once effect (`[]`) runs once, from
|
|
947
|
-
const isMount = effect.
|
|
948
|
-
effect.
|
|
2275
|
+
// A mount-once effect (`[]`) runs once, from the build.
|
|
2276
|
+
const isMount = effect.dependencies.type === 'ArrayExpression' &&
|
|
2277
|
+
effect.dependencies.elements.length === 0;
|
|
949
2278
|
if (isMount) {
|
|
950
|
-
const
|
|
2279
|
+
const context = {
|
|
951
2280
|
stateChanged: false,
|
|
952
|
-
|
|
953
|
-
out,
|
|
954
|
-
allowReturn: true,
|
|
2281
|
+
output,
|
|
955
2282
|
bodyList: statements,
|
|
956
2283
|
};
|
|
957
|
-
const lowered = lowerStmts(statements,
|
|
958
|
-
if (!
|
|
959
|
-
|
|
2284
|
+
const lowered = keepingStates(lowerStmts(statements, environment, state, context), output);
|
|
2285
|
+
if (!context.usedReturn) {
|
|
2286
|
+
output.mountEffects.push({
|
|
960
2287
|
kind: 'inline',
|
|
961
|
-
callback: { body: lowered, updatesState:
|
|
2288
|
+
callback: { body: lowered, updatesState: context.stateChanged },
|
|
962
2289
|
});
|
|
963
2290
|
return;
|
|
964
2291
|
}
|
|
965
2292
|
// With an early `return` the body gets its own function, so it cannot skip later mount effects.
|
|
966
|
-
const name = `
|
|
967
|
-
|
|
968
|
-
|
|
2293
|
+
const name = `effect_${output.effectCount++}`;
|
|
2294
|
+
output.effectFunctions.push({ kind: 'mount', name, body: lowered });
|
|
2295
|
+
output.mountEffects.push({
|
|
969
2296
|
kind: 'call',
|
|
970
2297
|
name,
|
|
971
|
-
updatesState:
|
|
2298
|
+
updatesState: context.stateChanged,
|
|
972
2299
|
});
|
|
973
2300
|
return;
|
|
974
2301
|
}
|
|
975
|
-
// A dep-driven effect gets its own
|
|
976
|
-
if (effect.
|
|
2302
|
+
// A dep-driven effect gets its own function; each dep must be scalar, so a change shows against a stored copy.
|
|
2303
|
+
if (effect.dependencies.type !== 'ArrayExpression') {
|
|
977
2304
|
throw aotError('AOT: a useEffect dependency list must be an array literal', 'pass `[]` (run once) or `[a, b]` (re-run when a/b change).');
|
|
978
2305
|
}
|
|
979
|
-
const effectId =
|
|
980
|
-
const
|
|
981
|
-
if (!
|
|
2306
|
+
const effectId = output.effectCount++;
|
|
2307
|
+
const dependencies = effect.dependencies.elements.map(dependencyNode => {
|
|
2308
|
+
if (!dependencyNode) {
|
|
982
2309
|
throw aotError('AOT: a useEffect dependency must be an expression');
|
|
983
2310
|
}
|
|
984
|
-
|
|
985
|
-
|
|
2311
|
+
if (objectTreeOf(dependencyNode, environment)) {
|
|
2312
|
+
throw aotError('AOT: a useEffect dependency on a whole object', 'depend on the fields the effect reads: [p.x, p.y].');
|
|
2313
|
+
}
|
|
2314
|
+
const dependencyExpression = lowerExprWide(dependencyNode, environment);
|
|
2315
|
+
const dependencyShape = shapeOf(dependencyExpression);
|
|
2316
|
+
if (dependencyShape === 'struct' || dependencyShape === 'node') {
|
|
986
2317
|
throw aotError('AOT: useEffect dependencies must be scalar (number / bool / string)', 'depend on scalar state values; object/array dependencies are not yet supported.');
|
|
987
2318
|
}
|
|
988
|
-
return
|
|
2319
|
+
return dependencyExpression;
|
|
989
2320
|
});
|
|
990
2321
|
// React runs the previous cleanup before a re-run; an `armed` flag records whether the last run reached it.
|
|
991
2322
|
const lastStatement = statements[statements.length - 1];
|
|
992
2323
|
const hasCleanup = lastStatement?.type === 'ReturnStatement' && isFn(lastStatement.argument);
|
|
993
|
-
const
|
|
2324
|
+
const dependencyEffect = {
|
|
994
2325
|
id: effectId,
|
|
995
|
-
|
|
2326
|
+
dependencies,
|
|
996
2327
|
body: [],
|
|
997
2328
|
hasCleanup,
|
|
998
2329
|
cleanup: null,
|
|
999
2330
|
};
|
|
1000
|
-
const
|
|
2331
|
+
const context = {
|
|
1001
2332
|
stateChanged: false,
|
|
1002
|
-
|
|
1003
|
-
out,
|
|
1004
|
-
allowReturn: true,
|
|
2333
|
+
output,
|
|
1005
2334
|
bodyList: statements,
|
|
1006
|
-
|
|
2335
|
+
dependencyDriven: true,
|
|
1007
2336
|
};
|
|
1008
2337
|
// With a cleanup, hoist the body's locals and lower the tail `return () => …` into `<effect>_cleanup()`.
|
|
1009
2338
|
if (hasCleanup) {
|
|
1010
|
-
|
|
1011
|
-
|
|
2339
|
+
context.hoist = {
|
|
2340
|
+
prefix: `effect${effectId}_local_`,
|
|
2341
|
+
declarations: output.effectDeclarations,
|
|
2342
|
+
};
|
|
2343
|
+
context.cleanup = {
|
|
1012
2344
|
armed: armedFlag(effectId),
|
|
1013
|
-
emit: (
|
|
1014
|
-
const cleanupBody =
|
|
2345
|
+
emit: (cleanupFunction, cleanupEnvironment) => {
|
|
2346
|
+
const cleanupBody = cleanupFunction.body;
|
|
1015
2347
|
const cleanupStatements = cleanupBody.type === 'BlockStatement'
|
|
1016
2348
|
? cleanupBody.body
|
|
1017
2349
|
: [{ type: 'ExpressionStatement', expression: cleanupBody }];
|
|
1018
|
-
const
|
|
2350
|
+
const cleanupContext = {
|
|
1019
2351
|
stateChanged: false,
|
|
1020
|
-
|
|
1021
|
-
out,
|
|
2352
|
+
output,
|
|
1022
2353
|
};
|
|
1023
|
-
|
|
1024
|
-
|
|
2354
|
+
dependencyEffect.cleanup = lowerBody(cleanupStatements, cleanupEnvironment, state, cleanupContext);
|
|
2355
|
+
output.effectFunctions.push({
|
|
2356
|
+
kind: 'cleanup',
|
|
2357
|
+
effect: dependencyEffect,
|
|
2358
|
+
});
|
|
1025
2359
|
},
|
|
1026
2360
|
};
|
|
1027
|
-
|
|
2361
|
+
output.effectDeclarations.push({ kind: 'armed', effect: dependencyEffect });
|
|
1028
2362
|
}
|
|
1029
2363
|
// The effect function runs the last run's cleanup first, if that run armed it, then the body.
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
// A copy of each dep, taken at mount;
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
2364
|
+
dependencyEffect.body = keepingStates(lowerStmts(statements, environment, state, context), output);
|
|
2365
|
+
output.effectFunctions.push({ kind: 'effect', effect: dependencyEffect });
|
|
2366
|
+
// A copy of each dep, taken at mount; the update re-runs the effect when one no longer matches its copy.
|
|
2367
|
+
output.effectDeclarations.push({ kind: 'deps', effect: dependencyEffect });
|
|
2368
|
+
output.mountEffects.push({ kind: 'depEffect', effect: dependencyEffect });
|
|
2369
|
+
output.dependencyEffects.push(dependencyEffect);
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* The native call that returns a record at the root of an expression: the call itself, or the record a field read
|
|
2373
|
+
* starts from, `Gps.fix().place.lat`.
|
|
2374
|
+
*
|
|
2375
|
+
* @param node The expression.
|
|
2376
|
+
* @param environment The expression environment.
|
|
2377
|
+
*
|
|
2378
|
+
* @returns The call and its callee, and the expression with the call replaced by another; or null.
|
|
2379
|
+
*/
|
|
2380
|
+
function nativeRecordRootOf(node, environment) {
|
|
2381
|
+
if (node?.type === 'MemberExpression') {
|
|
2382
|
+
const root = nativeRecordRootOf(node.object, environment);
|
|
2383
|
+
return (root && {
|
|
2384
|
+
...root,
|
|
2385
|
+
replaced: by => ({ ...node, object: root.replaced(by) }),
|
|
2386
|
+
});
|
|
2387
|
+
}
|
|
2388
|
+
const callee = nativeRecordCallOf(node, environment);
|
|
2389
|
+
return (callee && {
|
|
2390
|
+
call: node,
|
|
2391
|
+
callee,
|
|
2392
|
+
replaced: by => by,
|
|
2393
|
+
});
|
|
2394
|
+
}
|
|
2395
|
+
/**
|
|
2396
|
+
* Whether a call takes a record as one of its arguments: an object state's setter, or a native method's record
|
|
2397
|
+
* parameter.
|
|
2398
|
+
*
|
|
2399
|
+
* @param call The call.
|
|
2400
|
+
* @param index The argument's position.
|
|
2401
|
+
* @param environment The expression environment.
|
|
2402
|
+
* @param state The component's state table.
|
|
2403
|
+
*
|
|
2404
|
+
* @returns True when it does.
|
|
2405
|
+
*/
|
|
2406
|
+
function takesRecord(call, index, environment, state) {
|
|
2407
|
+
if (call.callee.type === 'Identifier' &&
|
|
2408
|
+
state.bySetter.get(call.callee.name)?.kind === 'record') {
|
|
2409
|
+
return true;
|
|
2410
|
+
}
|
|
2411
|
+
const callee = nativeCalleeOf(call, environment);
|
|
2412
|
+
const member = callee?.module.members.get(callee.method);
|
|
2413
|
+
return member?.kind === 'method' && typeof member.params[index] === 'object';
|
|
2414
|
+
}
|
|
2415
|
+
/**
|
|
2416
|
+
* Calls a native method that returns a record, keeping its values in locals, and binds the record to a name no JS
|
|
2417
|
+
* binding has, as an object of them.
|
|
2418
|
+
*
|
|
2419
|
+
* @param node The call.
|
|
2420
|
+
* @param callee Its module, method and record (see nativeRecordCallOf).
|
|
2421
|
+
* @param environment The expression environment.
|
|
2422
|
+
*
|
|
2423
|
+
* @returns The call, the name, and the environment that binds it.
|
|
2424
|
+
*/
|
|
2425
|
+
function keepNativeRecord(node, callee, environment) {
|
|
2426
|
+
const call = lowerNativeCall(node, callee, environment);
|
|
2427
|
+
const name = `#record${keptRecords++}`;
|
|
2428
|
+
const results = call.import.results.map((_, index) => `${name}_${index}`);
|
|
2429
|
+
const tree = recordTreeOf(callee.record, (index, type) => new RuntimeLeaf({ name: results[index], ...VALUE_SLOTS[type] }));
|
|
2430
|
+
return {
|
|
2431
|
+
statement: { kind: 'callNative', call, results },
|
|
2432
|
+
name,
|
|
2433
|
+
environment: {
|
|
2434
|
+
...environment,
|
|
2435
|
+
constants: { ...environment.constants, [name]: tree },
|
|
2436
|
+
},
|
|
2437
|
+
};
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* Lowers a `useNativeEvent(Module, 'event', handler)` to a handler the runtime runs with the event's values. The
|
|
2441
|
+
* handler does nothing while its component isn't mounted: the conditions it is built under, read as it runs.
|
|
2442
|
+
*
|
|
2443
|
+
* @param call The call.
|
|
2444
|
+
* @param environment The component's expression environment.
|
|
2445
|
+
* @param state The component's state table.
|
|
2446
|
+
* @param output Everything emitted so far; the handler is added to it.
|
|
2447
|
+
*/
|
|
2448
|
+
export function lowerNativeEvent(call, environment, state, output) {
|
|
2449
|
+
const { event, values: declared, handler } = nativeEventOf(call, environment);
|
|
2450
|
+
const index = output.nativeEventHandlers.length;
|
|
2451
|
+
// Each value is a register the handler is entered with, read by a name no JS binding can have. A record's fields
|
|
2452
|
+
// are values of their own, and the record is bound as an object of them; destructuring one declares its fields.
|
|
2453
|
+
const values = event.params.map((_, position) => `#native${index}_${position}`);
|
|
2454
|
+
const locals = new Map(environment.locals);
|
|
2455
|
+
const constants = { ...environment.constants };
|
|
2456
|
+
const destructured = [];
|
|
2457
|
+
let first = 0;
|
|
2458
|
+
handler.params.forEach((parameter, position) => {
|
|
2459
|
+
const type = declared[position];
|
|
2460
|
+
const from = first;
|
|
2461
|
+
first += valueCount(type);
|
|
2462
|
+
if (typeof type === 'string') {
|
|
2463
|
+
locals.set(parameter.name, {
|
|
2464
|
+
name: values[from],
|
|
2465
|
+
...VALUE_SLOTS[type],
|
|
2466
|
+
});
|
|
2467
|
+
return;
|
|
2468
|
+
}
|
|
2469
|
+
const name = parameter.type === 'Identifier'
|
|
2470
|
+
? parameter.name
|
|
2471
|
+
: `#value${index}_${position}`;
|
|
2472
|
+
locals.delete(name);
|
|
2473
|
+
constants[name] = recordTreeOf(type, (leaf, leafType) => new RuntimeLeaf({ name: values[leaf], ...VALUE_SLOTS[leafType] }), from);
|
|
2474
|
+
if (parameter.type === 'ObjectPattern') {
|
|
2475
|
+
destructured.push({
|
|
2476
|
+
type: 'VariableDeclaration',
|
|
2477
|
+
kind: 'const',
|
|
2478
|
+
declarations: [
|
|
2479
|
+
{
|
|
2480
|
+
type: 'VariableDeclarator',
|
|
2481
|
+
id: parameter,
|
|
2482
|
+
init: { type: 'Identifier', name },
|
|
2483
|
+
},
|
|
2484
|
+
],
|
|
2485
|
+
});
|
|
2486
|
+
}
|
|
2487
|
+
});
|
|
2488
|
+
const body = handler.body;
|
|
2489
|
+
const statements = [
|
|
2490
|
+
...destructured,
|
|
2491
|
+
...(body.type === 'BlockStatement'
|
|
2492
|
+
? body.body
|
|
2493
|
+
: [{ type: 'ExpressionStatement', expression: body }]),
|
|
2494
|
+
];
|
|
2495
|
+
const context = { stateChanged: false, output };
|
|
2496
|
+
const lowered = lowerBody(statements, { ...environment, locals, constants }, state, context);
|
|
2497
|
+
output.nativeEventHandlers.push({
|
|
2498
|
+
name: `native_event_${index}`,
|
|
2499
|
+
event,
|
|
2500
|
+
values,
|
|
2501
|
+
mounted: environment.mounted ?? null,
|
|
2502
|
+
callback: { body: lowered, updatesState: context.stateChanged },
|
|
2503
|
+
});
|
|
1036
2504
|
}
|
|
1037
2505
|
/**
|
|
1038
2506
|
* Lowers an event handler to a callback. Its first parameter is the event, whose touch fields read
|
|
1039
2507
|
* EREventData; a PanResponder callback's second is RN's gestureState (see lowerGestureField).
|
|
1040
2508
|
*
|
|
1041
|
-
* @param
|
|
1042
|
-
* @param
|
|
2509
|
+
* @param functionNode The handler.
|
|
2510
|
+
* @param environment The expression environment.
|
|
1043
2511
|
* @param state The component's state table.
|
|
1044
|
-
* @param
|
|
2512
|
+
* @param output Everything emitted so far.
|
|
1045
2513
|
* @param pan The PanResponder the handler belongs to, if any.
|
|
1046
2514
|
*
|
|
1047
2515
|
* @returns The callback.
|
|
1048
2516
|
*/
|
|
1049
|
-
export function lowerHandler(
|
|
2517
|
+
export function lowerHandler(functionNode, environment, state, output, pan = null) {
|
|
1050
2518
|
// An expression body is a single statement.
|
|
1051
|
-
const body =
|
|
2519
|
+
const body = functionNode.body;
|
|
1052
2520
|
const statements = body.type === 'BlockStatement'
|
|
1053
2521
|
? body.body
|
|
1054
2522
|
: [{ type: 'ExpressionStatement', expression: body }];
|
|
1055
2523
|
// The first parameter is the event (fields map to EREventData); a PanResponder's second is RN's gestureState.
|
|
1056
|
-
const
|
|
1057
|
-
|
|
1058
|
-
? fnNode.params[1].name
|
|
2524
|
+
const eventParameter = functionNode.params[0]?.type === 'Identifier'
|
|
2525
|
+
? functionNode.params[0].name
|
|
1059
2526
|
: null;
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
2527
|
+
const gestureParameter = pan && functionNode.params[1]?.type === 'Identifier'
|
|
2528
|
+
? functionNode.params[1].name
|
|
2529
|
+
: null;
|
|
2530
|
+
let handlerEnvironment = environment;
|
|
2531
|
+
if (eventParameter) {
|
|
2532
|
+
handlerEnvironment = { ...handlerEnvironment, event: eventParameter };
|
|
1063
2533
|
}
|
|
1064
|
-
if (
|
|
1065
|
-
|
|
2534
|
+
if (gestureParameter) {
|
|
2535
|
+
handlerEnvironment = {
|
|
2536
|
+
...handlerEnvironment,
|
|
2537
|
+
gesture: gestureParameter,
|
|
2538
|
+
pan,
|
|
2539
|
+
};
|
|
1066
2540
|
}
|
|
1067
2541
|
// The body re-applies state-dependent props once at its end if it set state.
|
|
1068
|
-
const
|
|
2542
|
+
const context = { stateChanged: false, output };
|
|
1069
2543
|
return {
|
|
1070
|
-
body:
|
|
1071
|
-
updatesState:
|
|
2544
|
+
body: lowerBody(statements, handlerEnvironment, state, context),
|
|
2545
|
+
updatesState: context.stateChanged,
|
|
1072
2546
|
};
|
|
1073
2547
|
}
|
|
1074
2548
|
/**
|
|
1075
2549
|
* Lowers a value-callback (e.g., Switch onValueChange) — binds its first param to `valueCode`, not an event.
|
|
1076
2550
|
*
|
|
1077
|
-
* @param
|
|
1078
|
-
* @param
|
|
1079
|
-
* @param env The expression environment.
|
|
2551
|
+
* @param functionNode The callback.
|
|
2552
|
+
* @param environment The expression environment.
|
|
1080
2553
|
* @param state The component's state table.
|
|
1081
|
-
* @param
|
|
1082
|
-
* @param
|
|
1083
|
-
* @param
|
|
1084
|
-
* @param
|
|
2554
|
+
* @param output Everything emitted so far.
|
|
2555
|
+
* @param slotKind The value's kind.
|
|
2556
|
+
* @param isBoolean The value is a boolean, so text prints it as true/false.
|
|
2557
|
+
* @param valueExpression The value as a typed expression.
|
|
2558
|
+
* @param secondValueExpression The second parameter's value as a typed expression, if any.
|
|
1085
2559
|
*
|
|
1086
2560
|
* @returns The callback.
|
|
1087
2561
|
*/
|
|
1088
|
-
export function lowerValueHandler(
|
|
2562
|
+
export function lowerValueHandler(functionNode, environment, state, output, slotKind, isBoolean, valueExpression, secondValueExpression) {
|
|
1089
2563
|
// A <Switch> hands its callback a boolean; carry that so `'on=' + v` prints true/false, not 1/0.
|
|
1090
|
-
const
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
2564
|
+
const valueParameter = functionNode.params[0]?.type === 'Identifier'
|
|
2565
|
+
? functionNode.params[0].name
|
|
2566
|
+
: null;
|
|
2567
|
+
const locals = new Map(environment.locals);
|
|
2568
|
+
if (valueParameter) {
|
|
2569
|
+
locals.set(valueParameter, {
|
|
2570
|
+
slotKind,
|
|
2571
|
+
isBoolean,
|
|
2572
|
+
expression: valueExpression,
|
|
2573
|
+
});
|
|
1094
2574
|
}
|
|
1095
|
-
// A RANGE <Dial>'s second parameter binds the same way, lowering to
|
|
1096
|
-
const
|
|
1097
|
-
|
|
1098
|
-
|
|
2575
|
+
// A RANGE <Dial>'s second parameter binds the same way, lowering to the event's value_start with no object on device.
|
|
2576
|
+
const secondParameter = functionNode.params[1]?.type === 'Identifier'
|
|
2577
|
+
? functionNode.params[1].name
|
|
2578
|
+
: null;
|
|
2579
|
+
if (secondParameter && secondValueExpression) {
|
|
2580
|
+
locals.set(secondParameter, { slotKind, expression: secondValueExpression });
|
|
1099
2581
|
}
|
|
1100
2582
|
// Lower the body (an expression body is a single statement); it re-applies state once if it set any.
|
|
1101
|
-
const
|
|
1102
|
-
const body =
|
|
2583
|
+
const context = { stateChanged: false, output };
|
|
2584
|
+
const body = functionNode.body;
|
|
1103
2585
|
const statements = body.type === 'BlockStatement'
|
|
1104
2586
|
? body.body
|
|
1105
2587
|
: [{ type: 'ExpressionStatement', expression: body }];
|
|
1106
2588
|
return {
|
|
1107
|
-
body:
|
|
1108
|
-
updatesState:
|
|
2589
|
+
body: lowerBody(statements, { ...environment, locals }, state, context),
|
|
2590
|
+
updatesState: context.stateChanged,
|
|
1109
2591
|
};
|
|
1110
2592
|
}
|